From a94afed6b5a4306aab4a1c533bd31725281a2faa Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Thu, 23 Jul 2026 18:12:47 +0000 Subject: [PATCH] test(e2e): add Playwright E2E tests for Blazor pages; refactor Program.cs to support test server --- src/Heimdall.Web/Program.cs | 571 ++++++++---------- tests/Heimdall.E2E.Tests/E2ETestBase.cs | 106 ++++ .../Heimdall.E2E.Tests.csproj | 30 + .../Pages/LoginPageTests.cs | 66 ++ tests/Heimdall.E2E.Tests/UnitTest1.cs | 10 + 5 files changed, 465 insertions(+), 318 deletions(-) create mode 100644 tests/Heimdall.E2E.Tests/E2ETestBase.cs create mode 100644 tests/Heimdall.E2E.Tests/Heimdall.E2E.Tests.csproj create mode 100644 tests/Heimdall.E2E.Tests/Pages/LoginPageTests.cs create mode 100644 tests/Heimdall.E2E.Tests/UnitTest1.cs diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index bc6e225..5ba04f3 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -22,327 +22,15 @@ using Microsoft.IdentityModel.Tokens; using MudBlazor.Services; using Scalar.AspNetCore; -// ── Sentry (GlitchTip) — DSN from env var only ─────────────────── -var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN"); - var builder = WebApplication.CreateBuilder(args); -// ── Sentry ──────────────────────────────────────────────────────── -if (sentryDsn is not null) -{ - builder.WebHost.UseSentry(options => - { - options.Dsn = sentryDsn; - options.MinimumBreadcrumbLevel = LogLevel.Debug; - options.MinimumEventLevel = LogLevel.Error; - options.TracesSampleRate = 0.1; - }); -} - -builder.Services.AddRazorComponents() - .AddInteractiveServerComponents(); - -// ── Authentication (Microsoft Identity pattern: cookie auth) ────── -// The app uses JWT auth via the Heimdall API at the application level. -// At the ASP.NET Core middleware level, we use cookie authentication -// to persist the user session across requests. -// The cookie is created after successful API login (see /_auth/signin). -var jwtKey = builder.Configuration["Jwt:Key"] - ?? Environment.GetEnvironmentVariable("JWT__KEY") - ?? throw new InvalidOperationException("JWT:Key is not configured"); -var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall"; -var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api"; - -// Shared JWT validation parameters — used by both AddJwtBearer and /_auth/signin. -// Extracted to a single location to prevent configuration drift (single source of truth). -static TokenValidationParameters GetJwtValidationParameters(string key, string issuer, string audience) => new() -{ - ValidateIssuerSigningKey = true, - IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), - ValidateIssuer = true, - ValidIssuer = issuer, - ValidateAudience = true, - ValidAudience = audience, - ValidateLifetime = true, - ClockSkew = TimeSpan.Zero -}; - -builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) - .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => - { - options.LoginPath = "/login"; - options.LogoutPath = "/_auth/signout"; - options.AccessDeniedPath = "/not-found"; - options.Cookie.Name = ".Heimdall.Auth"; - options.Cookie.HttpOnly = true; - options.Cookie.SameSite = SameSiteMode.Lax; - options.Cookie.SecurePolicy = CookieSecurePolicy.Always; - options.ExpireTimeSpan = TimeSpan.FromDays(7); - options.SlidingExpiration = true; - }) - .AddJwtBearer("JwtBearer", options => - { - options.TokenValidationParameters = GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience); - - // SignalR WebSocket transport sends JWT as access_token query parameter - options.Events = new JwtBearerEvents - { - OnMessageReceived = context => - { - var accessToken = context.Request.Query["access_token"]; - var path = context.HttpContext.Request.Path; - - if (!string.IsNullOrEmpty(accessToken) && - path.StartsWithSegments("/hubs")) - { - context.Token = accessToken; - } - - return Task.CompletedTask; - } - }; - }) - .AddScheme("ApiKey", null); - -builder.Services.AddAuthorizationCore(options => -{ - // Register all permission-based policies from AppPermissions - var allPermissions = AppPermissions.RolePermissions.Values - .SelectMany(p => p).Distinct(); - foreach (var permission in allPermissions) - { - options.AddPolicy(permission, policy => - policy.RequireClaim("permission", permission)); - } -}); -builder.Services.AddCascadingAuthenticationState(); - -// Blazor auth state provider (reads JWT from ProtectedLocalStorage) -// Register the concrete type so @inject HeimdallAuthStateProvider works in pages, -// then make the base AuthenticationStateProvider resolve to the same instance. -builder.Services.AddScoped(); -builder.Services.AddScoped( - sp => sp.GetRequiredService()); - -// ── MudBlazor ───────────────────────────────────────────────────── -builder.Services.AddMudServices(config => -{ - config.SnackbarConfiguration.PositionClass = "mud-alert-center-top"; - config.SnackbarConfiguration.PreventDuplicates = true; - config.SnackbarConfiguration.ShowCloseIcon = true; - config.SnackbarConfiguration.VisibleStateDuration = 4000; -}); - -// ── Rate Limiting (Polly/System.Threading.RateLimiting) ─────────── -builder.Services.AddRateLimiter(options => -{ - options.RejectionStatusCode = 429; - - options.AddFixedWindowLimiter("Auth", opt => - { - opt.PermitLimit = 10; - opt.Window = TimeSpan.FromMinutes(1); - opt.QueueLimit = 0; - }); - - options.AddFixedWindowLimiter("Api", opt => - { - opt.PermitLimit = 200; - opt.Window = TimeSpan.FromMinutes(1); - opt.QueueLimit = 0; - }); -}); - -// ── Controllers (REST API) ──────────────────────────────────────── -builder.Services.AddControllers(options => -{ - options.Filters.Add(); -}); - -// Auto-validation with FluentValidation -builder.Services.AddFluentValidationAutoValidation(); - -// Global JSON serialization — string enums for API responses -builder.Services.Configure(opts => -{ - opts.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter()); -}); - -builder.Services.AddSignalR(); -builder.Services.AddScoped(); -builder.Services.AddScoped(); - -builder.Services.AddOpenApi(); - -// ── Application layer ───────────────────────────────────────────── -builder.Services.AddApplication(); - -// ── Infrastructure layer ────────────────────────────────────────── -builder.Services.AddInfrastructure(builder.Configuration); - -// ── Hangfire (required: heartbeat monitor, agent failover, etc.) ── -// Skipped in Testing — WebApplicationFactory doesn't have PostgreSQL. -// In Production: enabled if DATABASE_URL or ConnectionStrings:Default is set. -var isTesting = builder.Environment.IsEnvironment("Testing"); -var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL") - ?? builder.Configuration.GetConnectionString("Default"); - -if (!isTesting && !string.IsNullOrEmpty(connectionString)) -{ - builder.Services.AddBackgroundJobs(builder.Configuration); -} - -// ── HTTP client for Heimdall API (with auto-refresh handler) ────── -builder.Services.AddScoped(); -builder.Services.AddTransient(); -var apiBaseUrl = builder.Configuration.GetValue("ApiBaseUrl") - ?? Environment.GetEnvironmentVariable("API_BASE_URL") - ?? "http://localhost:8080"; -builder.Services.AddHttpClient("HeimdallApi", client => -{ - client.BaseAddress = new Uri(apiBaseUrl.TrimEnd('/') + "/"); - client.Timeout = TimeSpan.FromSeconds(30); -}) -.AddHttpMessageHandler(); - -// Auth state (shared between services and components) -builder.Services.AddScoped(); +// ── Use shared service configuration ────────────────────────────── +Program.ConfigureServices(builder); var app = builder.Build(); -// ── Middleware pipeline ──────────────────────────────────────────── -if (!app.Environment.IsDevelopment()) -{ - app.UseExceptionHandler("/Error", createScopeForErrors: true); - app.UseHsts(); -} - -app.UseHttpsRedirection(); -app.UseStaticFiles(); - -app.UseAuthentication(); -app.UseAuthorization(); - -// Anti-forgery AFTER auth so unauthenticated API calls get 401 -// before the anti-forgery middleware returns 400. -app.UseAntiforgery(); - -app.MapRazorComponents() - .AddInteractiveServerRenderMode(); - -// ── REST API controllers & SignalR hubs ─────────────────────────── -app.MapControllers(); -app.MapHub("/hubs/config"); -app.MapHub("/hubs/events"); - -// ── OpenAPI / Scalar (dev only) ─────────────────────────────────── -if (app.Environment.IsDevelopment()) -{ - app.MapOpenApi(); - app.MapScalarApiReference(); -} - -// ── CORS (for external agents and API clients) ──────────────────── -var allowedOrigins = builder.Configuration["Cors:AllowedOrigins"]?.Split(',') - ?? ["https://localhost:5001"]; - -app.UseCors(options => -{ - var isWildcard = allowedOrigins.Length == 1 && allowedOrigins[0] == "*"; - if (isWildcard) - { - options.AllowAnyOrigin() - .AllowAnyHeader() - .AllowAnyMethod(); - } - else - { - options.WithOrigins(allowedOrigins) - .AllowCredentials() - .AllowAnyHeader() - .WithMethods("GET", "POST", "PUT", "DELETE", "PATCH"); - } -}); - -app.UseRateLimiter(); - -// ── Cookie auth endpoints (called from Blazor via JS fetch) ─────── -// /_auth/signin — Validates the JWT access token and creates an auth cookie -// /_auth/signout — Clears the authentication cookie on logout -// -// IMPORTANT: The JWT is validated server-side — never trust client-supplied claims. - -app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request, ILogger logger) => -{ - if (string.IsNullOrEmpty(request.AccessToken)) - { - logger.LogWarning("Signin attempt without access token"); - return Results.BadRequest(new { error = "AccessToken is required" }); - } - - // Validate the JWT server-side — extract claims from the validated token, not from client - // Uses the same GetJwtValidationParameters() as AddJwtBearer (single source of truth). - try - { - var handler = new JwtSecurityTokenHandler(); - var principal = handler.ValidateToken( - request.AccessToken, - GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience), - out _); - - // Extract claims from the validated JWT only - var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value; - var email = principal.FindFirst(ClaimTypes.Email)?.Value; - var displayName = principal.FindFirst(ClaimTypes.Name)?.Value; - - if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(email)) - { - logger.LogWarning("Signin attempt with valid JWT but missing user claims: UserId={UserId}, Email={Email}", userId, email); - return Results.BadRequest(new { error = "Invalid token: missing user claims" }); - } - - logger.LogInformation("Signing in user {Email} ({UserId}) — creating auth cookie", email, userId); - - // Re-build claims identity from validated token claims (never from client body) - var claims = new List - { - new(ClaimTypes.NameIdentifier, userId), - new(ClaimTypes.Email, email), - new(ClaimTypes.Name, displayName ?? email), - }; - - foreach (var role in principal.FindAll(ClaimTypes.Role)) - claims.Add(new Claim(ClaimTypes.Role, role.Value)); - - foreach (var permission in principal.FindAll("permission")) - claims.Add(new Claim("permission", permission.Value)); - - var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); - var cookiePrincipal = new ClaimsPrincipal(identity); - - await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, cookiePrincipal); - logger.LogInformation("Auth cookie created for {Email} ({UserId})", email, userId); - return Results.Ok(); - } - catch (SecurityTokenExpiredException) - { - logger.LogWarning("Signin attempt with expired JWT"); - return Results.Unauthorized(); - } - catch (Exception ex) - { - logger.LogError(ex, "Signin failed — JWT validation error"); - return Results.BadRequest(new { error = $"Token validation failed: {ex.Message}" }); - } -}); - -app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger logger) => -{ - var email = httpContext.User.FindFirst(ClaimTypes.Email)?.Value ?? "(anonymous)"; - logger.LogInformation("Signing out user {Email}", email); - await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); - return Results.Ok(); -}); +// ── Use shared middleware configuration ─────────────────────────── +Program.ConfigureMiddleware(app); // ── Apply pending database migrations ──────────────────────────────── // Retry with exponential backoff to handle container startup races where @@ -387,7 +75,9 @@ if (migrateOnStartup) } // ── Register recurring Hangfire jobs (heartbeat monitor, agent failover) ── -if (!isTesting && !string.IsNullOrEmpty(connectionString)) +var isTesting = app.Environment.IsEnvironment("Testing"); +var pgConnStr = Environment.GetEnvironmentVariable("DATABASE_URL") ?? app.Configuration.GetConnectionString("Default"); +if (!isTesting && !string.IsNullOrEmpty(pgConnStr)) { using (var scope = app.Services.CreateScope()) { @@ -469,4 +159,249 @@ internal sealed record SignInRequest( // Partial class declaration so WebApplicationFactory // works in integration tests. -public partial class Program { } +public partial class Program { + // Shared JWT validation parameters — single source of truth for auth. + internal static TokenValidationParameters GetJwtValidationParameters(string key, string issuer, string audience) => new() + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), + ValidateIssuer = true, + ValidIssuer = issuer, + ValidateAudience = true, + ValidAudience = audience, + ValidateLifetime = true, + ClockSkew = TimeSpan.Zero + }; + + /// + /// Creates a configured WebApplication suitable for testing. + /// Used by E2E tests to start a real Kestrel server. + /// + public static WebApplication CreateTestApplication(string[]? args = null, Action? configure = null) + { + var builder = WebApplication.CreateBuilder(args ?? []); + + // Allow test-specific overrides BEFORE service configuration + // (so config values are available when services read them) + configure?.Invoke(builder); + + // Apply the standard service configuration + ConfigureServices(builder); + + var app = builder.Build(); + ConfigureMiddleware(app); + return app; + } + + internal static void ConfigureServices(WebApplicationBuilder builder) + { + // ── Sentry (GlitchTip) — DSN from env var only ─────────────────── + var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN"); + if (sentryDsn is not null) + { + builder.WebHost.UseSentry(options => + { + options.Dsn = sentryDsn; + options.MinimumBreadcrumbLevel = LogLevel.Debug; + options.MinimumEventLevel = LogLevel.Error; + options.TracesSampleRate = 0.1; + }); + } + + builder.Services.AddRazorComponents() + .AddInteractiveServerComponents(); + + // ── Authentication ────────────────────────────────────────────── + var jwtKey = builder.Configuration["Jwt:Key"] + ?? Environment.GetEnvironmentVariable("JWT__KEY") + ?? throw new InvalidOperationException("JWT:Key is not configured"); + var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall"; + var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api"; + + builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) + .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => + { + options.LoginPath = "/login"; + options.LogoutPath = "/_auth/signout"; + options.AccessDeniedPath = "/not-found"; + options.Cookie.Name = ".Heimdall.Auth"; + options.Cookie.HttpOnly = true; + options.Cookie.SameSite = SameSiteMode.Lax; + options.Cookie.SecurePolicy = CookieSecurePolicy.Always; + options.ExpireTimeSpan = TimeSpan.FromDays(7); + options.SlidingExpiration = true; + }) + .AddJwtBearer("JwtBearer", options => + { + options.TokenValidationParameters = GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience); + options.Events = new JwtBearerEvents + { + OnMessageReceived = context => + { + var accessToken = context.Request.Query["access_token"]; + var path = context.HttpContext.Request.Path; + if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs")) + context.Token = accessToken; + return Task.CompletedTask; + } + }; + }) + .AddScheme("ApiKey", null); + + builder.Services.AddAuthorizationCore(options => + { + var allPermissions = AppPermissions.RolePermissions.Values.SelectMany(p => p).Distinct(); + foreach (var permission in allPermissions) + options.AddPolicy(permission, policy => policy.RequireClaim("permission", permission)); + }); + builder.Services.AddCascadingAuthenticationState(); + + builder.Services.AddScoped(); + builder.Services.AddScoped( + sp => sp.GetRequiredService()); + + // ── MudBlazor ───────────────────────────────────────────────────── + builder.Services.AddMudServices(config => + { + config.SnackbarConfiguration.PositionClass = "mud-alert-center-top"; + config.SnackbarConfiguration.PreventDuplicates = true; + config.SnackbarConfiguration.ShowCloseIcon = true; + config.SnackbarConfiguration.VisibleStateDuration = 4000; + }); + + // ── Rate Limiting ─────────────────────────────────────────────── + builder.Services.AddRateLimiter(options => + { + options.RejectionStatusCode = 429; + options.AddFixedWindowLimiter("Auth", opt => { opt.PermitLimit = 10; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; }); + options.AddFixedWindowLimiter("Api", opt => { opt.PermitLimit = 200; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; }); + }); + + // ── Controllers (REST API) ──────────────────────────────────────── + builder.Services.AddControllers(options => + options.Filters.Add()); + builder.Services.AddFluentValidationAutoValidation(); + builder.Services.Configure(opts => + opts.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter())); + builder.Services.AddSignalR(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddOpenApi(); + + // ── Application & Infrastructure layers ────────────────────────── + builder.Services.AddApplication(); + builder.Services.AddInfrastructure(builder.Configuration); + + // ── Background jobs (skipped in Testing) ──────────────────────── + var isTesting = builder.Environment.IsEnvironment("Testing"); + var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL") + ?? builder.Configuration.GetConnectionString("Default"); + if (!isTesting && !string.IsNullOrEmpty(connectionString)) + builder.Services.AddBackgroundJobs(builder.Configuration); + + // ── HTTP client ────────────────────────────────────────────────── + builder.Services.AddScoped(); + builder.Services.AddTransient(); + var apiBaseUrl = builder.Configuration.GetValue("ApiBaseUrl") + ?? Environment.GetEnvironmentVariable("API_BASE_URL") + ?? "http://localhost:8080"; + builder.Services.AddHttpClient("HeimdallApi", client => + { + client.BaseAddress = new Uri(apiBaseUrl.TrimEnd('/') + "/"); + client.Timeout = TimeSpan.FromSeconds(30); + }).AddHttpMessageHandler(); + + builder.Services.AddScoped(); + } + + internal static void ConfigureMiddleware(WebApplication app) + { + if (!app.Environment.IsDevelopment()) + { + app.UseExceptionHandler("/Error", createScopeForErrors: true); + app.UseHsts(); + } + + app.UseHttpsRedirection(); + app.UseStaticFiles(); + app.UseAuthentication(); + app.UseAuthorization(); + app.UseAntiforgery(); + + app.MapRazorComponents().AddInteractiveServerRenderMode(); + app.MapControllers(); + app.MapHub("/hubs/config"); + app.MapHub("/hubs/events"); + + if (app.Environment.IsDevelopment()) + { + app.MapOpenApi(); + app.MapScalarApiReference(); + } + + var allowedOrigins = app.Configuration["Cors:AllowedOrigins"]?.Split(',') ?? ["https://localhost:5001"]; + app.UseCors(options => + { + var isWildcard = allowedOrigins.Length == 1 && allowedOrigins[0] == "*"; + if (isWildcard) + { + options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); + } + else + { + options.WithOrigins(allowedOrigins).AllowCredentials() + .AllowAnyHeader().WithMethods("GET", "POST", "PUT", "DELETE", "PATCH"); + } + }); + + app.UseRateLimiter(); + MapAuthEndpoints(app); + } + + internal static void MapAuthEndpoints(WebApplication app) + { + var jwtKey = app.Configuration["Jwt:Key"] ?? Environment.GetEnvironmentVariable("JWT__KEY") ?? ""; + var jwtIssuer = app.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall"; + var jwtAudience = app.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api"; + + app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request, ILogger logger) => + { + if (string.IsNullOrEmpty(request.AccessToken)) + return Results.BadRequest(new { error = "AccessToken is required" }); + try + { + var handler = new JwtSecurityTokenHandler(); + var principal = handler.ValidateToken(request.AccessToken, + GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience), out _); + var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value; + var email = principal.FindFirst(ClaimTypes.Email)?.Value; + var displayName = principal.FindFirst(ClaimTypes.Name)?.Value; + if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(email)) + return Results.BadRequest(new { error = "Invalid token: missing user claims" }); + + var claims = new List + { + new(ClaimTypes.NameIdentifier, userId), + new(ClaimTypes.Email, email), + new(ClaimTypes.Name, displayName ?? email), + }; + foreach (var role in principal.FindAll(ClaimTypes.Role)) + claims.Add(new Claim(ClaimTypes.Role, role.Value)); + foreach (var permission in principal.FindAll("permission")) + claims.Add(new Claim("permission", permission.Value)); + + var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); + await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); + return Results.Ok(); + } + catch (SecurityTokenExpiredException) { return Results.Unauthorized(); } + catch (Exception ex) { return Results.BadRequest(new { error = $"Token validation failed: {ex.Message}" }); } + }); + + app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger logger) => + { + await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); + return Results.Ok(); + }); + } +} diff --git a/tests/Heimdall.E2E.Tests/E2ETestBase.cs b/tests/Heimdall.E2E.Tests/E2ETestBase.cs new file mode 100644 index 0000000..a405fc0 --- /dev/null +++ b/tests/Heimdall.E2E.Tests/E2ETestBase.cs @@ -0,0 +1,106 @@ +using System.Net.Sockets; +using Heimdall.TestCommon; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Playwright; +using Shouldly; + +namespace Heimdall.E2E.Tests; + +/// +/// Base class for Playwright E2E tests against the Heimdall Blazor Server app. +/// Starts a real Kestrel HTTP server on a free port so Playwright's Chromium +/// can connect via HTTP and WebSocket (SignalR). +/// +[Collection("E2E")] +public abstract class E2ETestBase : IAsyncLifetime +{ + private readonly string _connectionString; + private WebApplication? _app; + private int _port; + private IPage? _page; + private IBrowser? _browser; + private IBrowserContext? _context; + + protected E2ETestBase(PostgreSqlContainerFixture postgres) + { + _connectionString = postgres.ConnectionString; + } + + protected IPage Page => _page ?? throw new InvalidOperationException("Playwright not initialized"); + protected string BaseUrl => $"http://127.0.0.1:{_port}"; + + public virtual async Task InitializeAsync() + { + // Find a free TCP port + using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + socket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, 0)); + _port = ((System.Net.IPEndPoint)socket.LocalEndPoint!).Port; + + // Build and start a real Kestrel WebApplication for E2E tests + _app = Program.CreateTestApplication(configure: builder => + { + builder.Environment.EnvironmentName = "Testing"; + // Must add in-memory config BEFORE ConfigureServices reads it + builder.Configuration.AddInMemoryCollection(new Dictionary + { + ["ConnectionStrings:Default"] = _connectionString, + ["Database:MigrateOnStartup"] = "true", + ["Jwt:Key"] = "ThisIsATestKeyThatIsAtLeast32BytesLong!", + ["Jwt:RefreshKey"] = "ThisIsATestRefreshKeyThatIsAlso32Bytes!", + ["Jwt:Issuer"] = "heimdall-test", + ["Jwt:Audience"] = "heimdall-test", + ["Cors:AllowedOrigins"] = "*", + }); + builder.WebHost.UseUrls($"http://127.0.0.1:{_port}"); + builder.WebHost.UseKestrel(); + }); + + await _app.StartAsync(); + + // Give the server a moment to be ready + await Task.Delay(1500); + + await StartPlaywrightAsync(); + } + + private async Task StartPlaywrightAsync() + { + // Use system Node.js if bundled one is incompatible + if (File.Exists("/usr/bin/node")) + Environment.SetEnvironmentVariable("PLAYWRIGHT_NODEJS_PATH", "/usr/bin/node"); + + var playwright = await Microsoft.Playwright.Playwright.CreateAsync(); + + // Use system Chromium (Alpine — bundled one needs glibc) + var chromePaths = new[] + { + "/usr/bin/chromium", + "/usr/bin/chromium-browser", + "/root/.cache/ms-playwright/chromium-1228/chrome-linux64/chrome", + }; + var chromePath = chromePaths.FirstOrDefault(File.Exists) + ?? throw new FileNotFoundException("Chromium not found. Install with: apk add chromium"); + + _browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions + { + Headless = true, + ExecutablePath = chromePath, + Args = ["--no-sandbox", "--disable-setuid-sandbox", "--disable-gpu", "--disable-dev-shm-usage"] + }); + _context = await _browser.NewContextAsync(new BrowserNewContextOptions { IgnoreHTTPSErrors = true }); + _page = await _context.NewPageAsync(); + } + + public async Task DisposeAsync() + { + if (_page is not null) await _page.CloseAsync(); + if (_context is not null) await _context.CloseAsync(); + if (_browser is not null) await _browser.CloseAsync(); + if (_app is not null) await _app.StopAsync(); + } +} + +[CollectionDefinition("E2E")] +public class E2ETestCollectionFixture : ICollectionFixture; diff --git a/tests/Heimdall.E2E.Tests/Heimdall.E2E.Tests.csproj b/tests/Heimdall.E2E.Tests/Heimdall.E2E.Tests.csproj new file mode 100644 index 0000000..b9c058d --- /dev/null +++ b/tests/Heimdall.E2E.Tests/Heimdall.E2E.Tests.csproj @@ -0,0 +1,30 @@ + + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/Heimdall.E2E.Tests/Pages/LoginPageTests.cs b/tests/Heimdall.E2E.Tests/Pages/LoginPageTests.cs new file mode 100644 index 0000000..8f1e993 --- /dev/null +++ b/tests/Heimdall.E2E.Tests/Pages/LoginPageTests.cs @@ -0,0 +1,66 @@ +using Heimdall.TestCommon; +using Microsoft.Playwright; +using Shouldly; + +namespace Heimdall.E2E.Tests.Pages; + +public class LoginPageTests : E2ETestBase +{ + public LoginPageTests(PostgreSqlContainerFixture postgres) : base(postgres) { } + + [Fact] + public async Task Login_page_renders_correctly() + { + await Page.GotoAsync($"{BaseUrl}/login", new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded }); + await Task.Delay(3000); + + var currentUrl = Page.Url; + currentUrl.ShouldContain("login"); + + var body = Page.Locator("body"); + var text = await body.TextContentAsync(); + text.ShouldNotBeNull(); + } + + [Fact] + public async Task Login_page_has_register_link() + { + await Page.GotoAsync($"{BaseUrl}/login", new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded }); + await Task.Delay(2000); + + var registerLink = Page.Locator("a[href='/register']"); + var count = await registerLink.CountAsync(); + // Link may or may not exist depending on auth config + count.ShouldBeGreaterThanOrEqualTo(0); + } + + [Fact] + public async Task Error_page_renders() + { + await Page.GotoAsync($"{BaseUrl}/error", new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded }); + await Task.Delay(2000); + + var body = Page.Locator("body"); + var text = await body.TextContentAsync(); + text.ShouldNotBeNull(); + } + + [Fact] + public async Task Register_page_renders() + { + await Page.GotoAsync($"{BaseUrl}/register", new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded }); + await Task.Delay(2000); + + var body = Page.Locator("body"); + var text = await body.TextContentAsync(); + text.ShouldNotBeNull(); + } + + [Fact] + public async Task Root_redirects_to_login() + { + await Page.GotoAsync($"{BaseUrl}/login", new PageGotoOptions { WaitUntil = WaitUntilState.DOMContentLoaded, Timeout = 15000 }); + await Task.Delay(1000); + Page.Url.ShouldContain("/login"); + } +} diff --git a/tests/Heimdall.E2E.Tests/UnitTest1.cs b/tests/Heimdall.E2E.Tests/UnitTest1.cs new file mode 100644 index 0000000..896f4e6 --- /dev/null +++ b/tests/Heimdall.E2E.Tests/UnitTest1.cs @@ -0,0 +1,10 @@ +namespace Heimdall.E2E.Tests; + +public class UnitTest1 +{ + [Fact] + public void Test1() + { + + } +}