using System.Collections.Concurrent; using System.Diagnostics; using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Security.Cryptography; using Helpdesk.Application.Abstractions; using Helpdesk.Application.Auth; using Helpdesk.Application.Common; using Helpdesk.Application.Users; using Helpdesk.Infrastructure.Persistence; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.WebUtilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Testcontainers.MariaDb; namespace Helpdesk.IntegrationTests; public sealed class BackendFixture : IAsyncLifetime { internal const string AdminEmail = "admin@example.test"; internal const string Password = "Integration-test-password"; internal static string MigrationsPath => Path.Combine(AppContext.BaseDirectory, "migrations"); internal static CancellationToken Cancellation => TestContext.Current.CancellationToken; private readonly MariaDbContainer database = new MariaDbBuilder("mariadb:11.4") .WithDatabase("helpdesk") .WithPassword(Convert.ToHexString(RandomNumberGenerator.GetBytes(24))) .WithCommand("--character-set-server=utf8mb4") .Build(); private readonly TestEmailSender email = new(); private ApiFactory? factory; internal TokenSaveGate TokenSaves { get; } = new(); internal IServiceProvider Services => factory!.Services; public async ValueTask InitializeAsync() { await database.StartAsync(Cancellation); await RunMigratorAsync(database.GetConnectionString()); factory = new ApiFactory(database.GetConnectionString(), email, TokenSaves); } public async ValueTask DisposeAsync() { try { if (factory is not null) await factory.DisposeAsync(); } finally { await database.DisposeAsync(); } } internal HttpClient CreateClient(string? accessToken = null) { var client = factory!.CreateClient(); if (accessToken is not null) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); return client; } internal async Task RegisterAsync(HttpClient client) { var address = $"{Guid.NewGuid():N}@student.example.test"; var user = await ReadAsync(client.PostAsJsonAsync("/api/v1/auth/register", new RegisterRequest(address, Password, "Test", "User"), Cancellation), HttpStatusCode.Created); await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email", new EmailTokenRequest(await email.TakeTokenAsync(address, "/confirm-email")), Cancellation), HttpStatusCode.NoContent); return user; } internal async Task RegisterStaffAsync(HttpClient anonymous, HttpClient admin, string role) { var user = await RegisterAsync(anonymous); await ExpectAsync(admin.PutAsJsonAsync($"/api/v1/admin/users/{user.Id}/role", new ChangeRoleRequest(role), Cancellation), HttpStatusCode.NoContent); return await LoginAsync(anonymous, user.Email); } internal Task TakeResetTokenAsync(string address) => email.TakeTokenAsync(address, "/reset-password"); internal void FailNextEmail(string address, string reason, bool retryable) => email.Failures[address] = new EmailDeliveryException(reason, retryable); internal static Task LoginAsync(HttpClient client, string address) => ReadAsync(client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(address, Password), Cancellation)); internal static async Task ReadAsync(Task request, HttpStatusCode expected = HttpStatusCode.OK) where T : class { using var response = await request; Assert.Equal(expected, response.StatusCode); return Assert.IsType(await response.Content.ReadFromJsonAsync(Cancellation)); } internal static async Task ExpectAsync(Task request, HttpStatusCode expected) { using var response = await request; Assert.Equal(expected, response.StatusCode); } private static async Task RunMigratorAsync(string connectionString) { var startInfo = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet") { RedirectStandardOutput = true, RedirectStandardError = true, }; startInfo.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "Helpdesk.Migrator.dll")); startInfo.Environment["ConnectionStrings__Migrator"] = connectionString; startInfo.Environment["MIGRATIONS_PATH"] = MigrationsPath; using var process = Process.Start(startInfo) ?? throw new InvalidOperationException("Could not start the migrator."); var output = process.StandardOutput.ReadToEndAsync(Cancellation); var errors = process.StandardError.ReadToEndAsync(Cancellation); try { await process.WaitForExitAsync(Cancellation); Assert.True(process.ExitCode == 0, $"Migrator failed with exit code {process.ExitCode}.\n{await output}\n{await errors}"); } finally { if (!process.HasExited) { process.Kill(); await process.WaitForExitAsync(); } } } private sealed class ApiFactory(string connectionString, TestEmailSender email, TokenSaveGate tokenSaves) : WebApplicationFactory { private readonly Dictionary settings = new() { ["ConnectionStrings:Helpdesk"] = connectionString, ["Jwt:SigningKey"] = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)), ["Encryption:Key"] = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)), ["Registration:StudentEmailDomains:0"] = "student.example.test", ["Registration:WebBaseUrl"] = "https://helpdesk.example.test", ["ADMIN_EMAIL"] = AdminEmail, ["ADMIN_PASSWORD"] = Password, ["Firebase:ServiceAccountJson"] = "", ["Smtp:Mailbox"] = "", ["Smtp:Password"] = "", ["ReverseProxy:TrustedIp"] = "", }; protected override IHost CreateHost(IHostBuilder builder) { // Program čte konfiguraci před Build(), proto musí hodnoty dostat už při startu. builder.UseEnvironment(Environments.Development) .ConfigureHostConfiguration(config => config.AddInMemoryCollection(settings)); return base.CreateHost(builder); } protected override void ConfigureWebHost(IWebHostBuilder builder) => builder.ConfigureTestServices(services => { services.RemoveAll(); services.AddSingleton(email); services.AddDbContext((_, options) => options.AddInterceptors(tokenSaves)); }); } private sealed class TestEmailSender : IEmailSender { private readonly ConcurrentDictionary<(string Address, string Path), TaskCompletionSource> tokens = new(); internal ConcurrentDictionary Failures { get; } = new(); public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default) { if (Failures.TryRemove(to, out var failure)) throw failure; if (Uri.TryCreate(body[(body.LastIndexOf('\n') + 1)..], UriKind.Absolute, out var link) && link.AbsolutePath is "/confirm-email" or "/reset-password") { var token = QueryHelpers.ParseQuery(link.Query)["token"].ToString(); GetTokenSlot((to, link.AbsolutePath)).TrySetResult(token); } return Task.CompletedTask; } internal async Task TakeTokenAsync(string address, string path) { var key = (address, path); var token = await GetTokenSlot(key).Task.WaitAsync(TimeSpan.FromSeconds(10), Cancellation); tokens.TryRemove(key, out _); return token; } private TaskCompletionSource GetTokenSlot((string Address, string Path) key) => tokens.GetOrAdd(key, _ => new(TaskCreationOptions.RunContinuationsAsynchronously)); } }