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;
///
/// 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).
///
[Collection("Postgres")]
public class AuthFlowTests : IAsyncLifetime
{
private readonly string _connectionString;
private readonly Lazy _factoryLazy;
private HeimdallWebApplicationFactory Factory => _factoryLazy.Value;
private static readonly JsonSerializerOptions Json = new()
{
PropertyNameCaseInsensitive = true
};
public AuthFlowTests(PostgreSqlContainerFixture postgres)
{
_connectionString = postgres.ConnectionString;
_factoryLazy = new Lazy(
() => 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()
.UseNpgsql(_connectionString)
.Options;
await using var db = new AppDbContext(opts, new AuditInterceptor());
var tables = await db.Database.SqlQuery(
$"""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 ────────────────────────────────── */
///
/// BLOCKING: Unauthenticated access to root must redirect to /login.
/// This test would have caught the /Account/Login → 404 redirect bug.
///
[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");
}
///
/// Verifies that the login page is accessible and returns OK.
///
[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");
body.ShouldContain("Se connecter");
}
/* ─── API auth tests ───────────────────────────────────────── */
///
/// Protected API endpoint must reject unauthenticated requests with 401.
///
[Fact]
public async Task Get_ProtectedApi_WithoutAuth_ReturnsUnauthorized()
{
var client = Factory.CreateClient();
var response = await client.GetAsync("/api/stats");
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
///
/// Register endpoint must return 400 for invalid password (too short/minimal requirements).
///
[Fact]
public async Task Register_WithWeakPassword_ReturnsBadRequest()
{
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"
});
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
}
/* ─── Full auth flow test ──────────────────────────────────── */
///
/// End-to-end: register admin via test endpoint → get JWT → access protected API.
/// This validates the complete auth pipeline works end-to-end.
///
[Fact]
public async Task RegisterAdmin_ThenLogin_ReturnsJwt_AndAccessesProtectedApi()
{
var email = $"e2e-{Guid.NewGuid()}@heimdall.test";
var password = "E2eTestPwd123!";
var client = Factory.CreateClient();
// Step 1: Register admin user via test-only endpoint
var registerResponse = await client.PostAsJsonAsync("/api/auth/register-admin", new
{
email,
password,
displayName = "E2E Test Admin"
});
registerResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var registerContent = await registerResponse.Content.ReadFromJsonAsync(Json);
var accessToken = registerContent.GetProperty("accessToken").GetString();
var refreshToken = registerContent.GetProperty("refreshToken").GetString();
accessToken.ShouldNotBeNullOrEmpty("register-admin must return an access token");
refreshToken.ShouldNotBeNullOrEmpty("register-admin must return a refresh token");
// Step 2: Use the token to access a protected API endpoint
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
var statsResponse = await client.GetAsync("/api/stats");
statsResponse.StatusCode.ShouldBe(HttpStatusCode.OK, "authenticated request must succeed");
// Step 3: Refresh the token
var refreshResponse = await client.PostAsJsonAsync("/api/auth/refresh", new
{
refreshToken
});
refreshResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
var refreshContent = await refreshResponse.Content.ReadFromJsonAsync(Json);
var newAccessToken = refreshContent.GetProperty("accessToken").GetString();
newAccessToken.ShouldNotBeNullOrEmpty("refresh must return a new access token");
}
///
/// Register a user and verify the endpoint returns a valid AuthResponse.
///
[Fact]
public async Task Register_ReturnsValidAuthResponse()
{
var email = $"user-{Guid.NewGuid()}@heimdall.test";
var password = "UserRegPwd123!";
var client = Factory.CreateClient();
var response = await client.PostAsJsonAsync("/api/auth/register", new
{
email,
password,
displayName = "Registered User"
});
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var content = await response.Content.ReadFromJsonAsync(Json);
content.TryGetProperty("accessToken", out _).ShouldBeTrue();
content.TryGetProperty("refreshToken", out _).ShouldBeTrue();
}
}