Heimdall Gitea / Detect CI scope (pull_request) Successful in 4s
Heimdall Gitea / Build and tests (pull_request) Successful in 20m32s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan server image (pull_request) Successful in 8m36s
Heimdall Gitea / Build and scan agent image (pull_request) Successful in 11m34s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Successful in 2s
238 lines
9.1 KiB
C#
238 lines
9.1 KiB
C#
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");
|
|
// 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");
|
|
}
|
|
|
|
/* ─── 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>
|
|
/// The removed anonymous account creation endpoint stays unavailable.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task AnonymousRegistrationRoute_IsRemoved()
|
|
{
|
|
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.NotFound);
|
|
}
|
|
|
|
/* ─── Full auth flow test ──────────────────────────────────── */
|
|
|
|
/// <summary>
|
|
/// End-to-end: bootstrap admin → get JWT → access protected API.
|
|
/// This validates the complete auth pipeline works end-to-end.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task RegisterAdmin_ThenLogin_ReturnsJwt_AndAccessesProtectedApi()
|
|
{
|
|
var email = $"e2e-{Guid.NewGuid()}@heimdall.test";
|
|
var password = "E2eTestPwd123!";
|
|
var client = Factory.CreateClient();
|
|
|
|
// Step 1: Bootstrap the first admin.
|
|
var bootEmail = "boot-admin@heimdall.test";
|
|
var bootResponse = await client.PostAsJsonAsync("/api/auth/bootstrap-admin", new
|
|
{
|
|
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();
|
|
|
|
// Enable the admin-registration feature flag
|
|
client.DefaultRequestHeaders.Authorization =
|
|
new AuthenticationHeaderValue("Bearer", bootToken);
|
|
var flagResponse = await client.PostAsJsonAsync("/api/settings", new
|
|
{
|
|
key = "auth.admin-registration.enabled",
|
|
value = "true",
|
|
valueType = "bool",
|
|
category = "Auth",
|
|
description = "Enable admin registration via API"
|
|
});
|
|
flagResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
|
|
// Step 2: Register a new admin via RegisterAdmin
|
|
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<JsonElement>(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 3: Use the new admin 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 4: Refresh the token
|
|
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>
|
|
/// Bootstrap the initial user and verify the endpoint returns an AuthResponse.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task BootstrapAdmin_ReturnsValidAuthResponse()
|
|
{
|
|
var email = $"user-{Guid.NewGuid()}@heimdall.test";
|
|
var password = "UserRegPwd123!";
|
|
var client = Factory.CreateClient();
|
|
|
|
var response = await client.PostAsJsonAsync("/api/auth/bootstrap-admin", new
|
|
{
|
|
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();
|
|
}
|
|
}
|