2026-07-24 19:39:47 +00:00
using System.Net ;
using System.Net.Http.Headers ;
using System.Net.Http.Json ;
using System.Text.Json ;
using Heimdall.Infrastructure.Data ;
using Heimdall.Infrastructure.Data.Interceptors ;
using Heimdall.IntegrationTests.Factories ;
using Microsoft.AspNetCore.Mvc.Testing ;
using Microsoft.EntityFrameworkCore ;
using Shouldly ;
namespace Heimdall.IntegrationTests.Controllers ;
/// <summary>
/// Integration tests for authentication flow.
/// These tests verify the full pipeline: redirect behavior, login page rendering,
/// API authentication, and the complete register→login→access flow.
/// Would have caught the /Account/Login redirect bug (missing ConfigureApplicationCookie order).
/// </summary>
[Collection("Postgres")]
public class AuthFlowTests : IAsyncLifetime
{
private readonly string _connectionString ;
private readonly Lazy < HeimdallWebApplicationFactory > _factoryLazy ;
private HeimdallWebApplicationFactory Factory => _factoryLazy . Value ;
private static readonly JsonSerializerOptions Json = new ()
{
PropertyNameCaseInsensitive = true
};
public AuthFlowTests ( PostgreSqlContainerFixture postgres )
{
_connectionString = postgres . ConnectionString ;
_factoryLazy = new Lazy < HeimdallWebApplicationFactory >(
() => new HeimdallWebApplicationFactory ( postgres . ConnectionString ));
}
public async Task InitializeAsync ()
{
// Trigger factory creation to run migrations
_ = Factory ;
await ResetDatabaseAsync ();
}
public async Task DisposeAsync ()
{
if ( _factoryLazy . IsValueCreated )
await _factoryLazy . Value . DisposeAsync ();
}
private async Task ResetDatabaseAsync ()
{
var opts = new DbContextOptionsBuilder < AppDbContext >()
. UseNpgsql ( _connectionString )
. Options ;
await using var db = new AppDbContext ( opts , new AuditInterceptor ());
var tables = await db . Database . SqlQuery < string >(
$"""SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' AND table_name != '__EFMigrationsHistory'""" )
. ToListAsync ();
if ( tables . Count > 0 )
{
var joined = string . Join ( ", " , tables . Select ( t => "\"" + t + "\"" ));
#pragma warning disable EF1002 , EF1003
await db . Database . ExecuteSqlRawAsync ( "TRUNCATE TABLE " + joined + " CASCADE" );
#pragma warning restore EF1002 , EF1003
}
}
/* ─── Blazor redirect tests ────────────────────────────────── */
/// <summary>
/// BLOCKING: Unauthenticated access to root must redirect to /login.
/// This test would have caught the /Account/Login → 404 redirect bug.
/// </summary>
[Fact]
public async Task Get_Root_WithoutAuth_RedirectsToLogin ()
{
var client = Factory . CreateClient ( new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var response = await client . GetAsync ( "/" );
response . StatusCode . ShouldBe ( HttpStatusCode . Redirect );
var location = response . Headers . Location ?. ToString () ?? "" ;
location . ShouldContain ( "/login" );
}
/// <summary>
/// Verifies that the login page is accessible and returns OK.
/// </summary>
[Fact]
public async Task Get_LoginPage_ReturnsOk ()
{
var client = Factory . CreateClient ();
var response = await client . GetAsync ( "/login" );
response . StatusCode . ShouldBe ( HttpStatusCode . OK );
var body = await response . Content . ReadAsStringAsync ();
body . ShouldContain ( "Heimdall" );
2026-08-11 12:35:45 +02:00
// Prerender is disabled (InteractiveServerRenderMode prerender:false),
// so the static shell is served and the Login component content only
// appears after the SignalR circuit connects. Assert the Blazor shell.
body . ShouldContain ( "_framework/blazor.web.js" );
2026-07-24 19:39:47 +00:00
}
/* ─── API auth tests ───────────────────────────────────────── */
/// <summary>
/// Protected API endpoint must reject unauthenticated requests with 401.
/// </summary>
[Fact]
public async Task Get_ProtectedApi_WithoutAuth_ReturnsUnauthorized ()
{
var client = Factory . CreateClient ();
var response = await client . GetAsync ( "/api/stats" );
response . StatusCode . ShouldBe ( HttpStatusCode . Unauthorized );
}
/// <summary>
2026-10-27 22:19:52 +01:00
/// The removed anonymous account creation endpoint stays unavailable.
2026-07-24 19:39:47 +00:00
/// </summary>
[Fact]
2026-10-27 22:19:52 +01:00
public async Task AnonymousRegistrationRoute_IsRemoved ()
2026-07-24 19:39:47 +00:00
{
var client = Factory . CreateClient ();
var response = await client . PostAsJsonAsync ( "/api/auth/register" , new
{
email = $"weak-{Guid.NewGuid()}@heimdall.test" ,
password = "short" ,
displayName = "Weak Password User"
});
2026-10-27 22:19:52 +01:00
response . StatusCode . ShouldBe ( HttpStatusCode . NotFound );
2026-07-24 19:39:47 +00:00
}
/* ─── Full auth flow test ──────────────────────────────────── */
/// <summary>
2026-10-27 22:19:52 +01:00
/// End-to-end: bootstrap admin → get JWT → access protected API.
2026-07-24 19:39:47 +00:00
/// This validates the complete auth pipeline works end-to-end.
/// </summary>
[Fact]
2026-11-04 13:33:30 +01:00
public async Task FirstAdminBootstraps_AndCreatesFurtherAdminsThroughUserManagement ()
2026-07-24 19:39:47 +00:00
{
var email = $"e2e-{Guid.NewGuid()}@heimdall.test" ;
var password = "E2eTestPwd123!" ;
var client = Factory . CreateClient ();
2026-10-27 22:19:52 +01:00
// Step 1: Bootstrap the first admin.
2026-07-28 14:57:28 +00:00
var bootEmail = "boot-admin@heimdall.test" ;
2026-10-27 22:19:52 +01:00
var bootResponse = await client . PostAsJsonAsync ( "/api/auth/bootstrap-admin" , new
2026-07-28 14:57:28 +00:00
{
email = bootEmail ,
password = "BootAdminPwd123!" ,
displayName = "Bootstrap Admin"
});
bootResponse . StatusCode . ShouldBe ( HttpStatusCode . OK );
var bootContent = await bootResponse . Content . ReadFromJsonAsync < JsonElement >( Json );
var bootToken = bootContent . GetProperty ( "accessToken" ). GetString ();
bootToken . ShouldNotBeNullOrEmpty ();
2026-11-04 13:33:30 +01:00
// Further accounts, including additional administrators, use the same
// user-management path that the authenticated UI calls.
2026-07-28 14:57:28 +00:00
client . DefaultRequestHeaders . Authorization =
new AuthenticationHeaderValue ( "Bearer" , bootToken );
2026-11-04 13:33:30 +01:00
var createResponse = await client . PostAsJsonAsync ( "/api/users" , new
2026-07-28 14:57:28 +00:00
{
2026-11-04 13:33:30 +01:00
email ,
password ,
displayName = "E2E Test Admin" ,
roles = new [] { "Admin" }
2026-07-28 14:57:28 +00:00
});
2026-11-04 13:33:30 +01:00
createResponse . StatusCode . ShouldBe ( HttpStatusCode . OK );
2026-07-28 14:57:28 +00:00
2026-11-04 13:33:30 +01:00
var legacyAdminRegistration = await client . PostAsJsonAsync ( "/api/auth/register-admin" , new
2026-07-24 19:39:47 +00:00
{
email ,
password ,
displayName = "E2E Test Admin"
});
2026-11-04 13:33:30 +01:00
legacyAdminRegistration . StatusCode . ShouldBe ( HttpStatusCode . NotFound );
2026-07-24 19:39:47 +00:00
2026-11-04 13:33:30 +01:00
// New accounts are not implicitly signed in by account-management actions.
var loginResponse = await client . PostAsJsonAsync ( "/api/auth/login" , new { email , password });
loginResponse . StatusCode . ShouldBe ( HttpStatusCode . OK );
var loginContent = await loginResponse . Content . ReadFromJsonAsync < JsonElement >( Json );
var accessToken = loginContent . GetProperty ( "accessToken" ). GetString ();
var refreshToken = loginContent . GetProperty ( "refreshToken" ). GetString ();
accessToken . ShouldNotBeNullOrEmpty ();
refreshToken . ShouldNotBeNullOrEmpty ();
2026-07-24 19:39:47 +00:00
2026-07-28 14:57:28 +00:00
// Step 3: Use the new admin token to access a protected API endpoint
2026-07-24 19:39:47 +00:00
client . DefaultRequestHeaders . Authorization =
new AuthenticationHeaderValue ( "Bearer" , accessToken );
var statsResponse = await client . GetAsync ( "/api/stats" );
statsResponse . StatusCode . ShouldBe ( HttpStatusCode . OK , "authenticated request must succeed" );
2026-07-28 14:57:28 +00:00
// Step 4: Refresh the token
2026-07-24 19:39:47 +00:00
var refreshResponse = await client . PostAsJsonAsync ( "/api/auth/refresh" , new
{
refreshToken
});
refreshResponse . StatusCode . ShouldBe ( HttpStatusCode . OK );
var refreshContent = await refreshResponse . Content . ReadFromJsonAsync < JsonElement >( Json );
var newAccessToken = refreshContent . GetProperty ( "accessToken" ). GetString ();
newAccessToken . ShouldNotBeNullOrEmpty ( "refresh must return a new access token" );
}
/// <summary>
2026-10-27 22:19:52 +01:00
/// Bootstrap the initial user and verify the endpoint returns an AuthResponse.
2026-07-24 19:39:47 +00:00
/// </summary>
[Fact]
2026-10-27 22:19:52 +01:00
public async Task BootstrapAdmin_ReturnsValidAuthResponse ()
2026-07-24 19:39:47 +00:00
{
var email = $"user-{Guid.NewGuid()}@heimdall.test" ;
var password = "UserRegPwd123!" ;
var client = Factory . CreateClient ();
2026-10-27 22:19:52 +01:00
var response = await client . PostAsJsonAsync ( "/api/auth/bootstrap-admin" , new
2026-07-24 19:39:47 +00:00
{
email ,
password ,
displayName = "Registered User"
});
response . StatusCode . ShouldBe ( HttpStatusCode . OK );
var content = await response . Content . ReadFromJsonAsync < JsonElement >( Json );
content . TryGetProperty ( "accessToken" , out _ ). ShouldBeTrue ();
content . TryGetProperty ( "refreshToken" , out _ ). ShouldBeTrue ();
}
}