Files

213 lines
9.0 KiB
C#

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 = "[email protected]";
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 WebApplicationFactory<Program> CreateApiBehindProxies(string proxyIp, string webIp) =>
new ApiFactory(database.GetConnectionString(), email, TokenSaves, proxyIp, webIp);
internal async Task<UserDto> RegisterAsync(HttpClient client)
{
var address = $"{Guid.NewGuid():N}@student.example.test";
var user = await ReadAsync<UserDto>(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 TakeConfirmationTokenAsync(address)), Cancellation), HttpStatusCode.NoContent);
return user;
}
internal async Task<AuthResponse> 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<string> TakeConfirmationTokenAsync(string address) => email.TakeTokenAsync(address, "/confirm-email");
internal Task<string> 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<AuthResponse> LoginAsync(HttpClient client, string address) =>
ReadAsync<AuthResponse>(client.PostAsJsonAsync("/api/v1/auth/login",
new LoginRequest(address, Password), Cancellation));
internal static async Task<T> ReadAsync<T>(Task<HttpResponseMessage> request, HttpStatusCode expected = HttpStatusCode.OK)
where T : class
{
using var response = await request;
Assert.Equal(expected, response.StatusCode);
return Assert.IsType<T>(await response.Content.ReadFromJsonAsync<T>(Cancellation));
}
internal static async Task ExpectAsync(Task<HttpResponseMessage> 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,
string proxyIp = "", string webIp = "")
: WebApplicationFactory<Program>
{
private readonly Dictionary<string, string?> 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"] = proxyIp,
["ReverseProxy:TrustedWebIp"] = webIp,
};
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<IEmailSender>();
services.AddSingleton<IEmailSender>(email);
services.AddDbContext<HelpdeskDbContext>((_, options) => options.AddInterceptors(tokenSaves));
});
}
private sealed class TestEmailSender : IEmailSender
{
private readonly ConcurrentDictionary<(string Address, string Path), TaskCompletionSource<string>> tokens = new();
internal ConcurrentDictionary<string, EmailDeliveryException> 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<string> 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<string> GetTokenSlot((string Address, string Path) key) =>
tokens.GetOrAdd(key, _ => new(TaskCreationOptions.RunContinuationsAsynchronously));
}
}