Merge pull request 'Improvements' (#30) from backend-unittests into main

Reviewed-on: #30
This commit was merged in pull request #30.
This commit is contained in:
GonnaHetzMe committed 2026-12-03 00:57:24 +01:00
commit 34f2d57bd3
35 files changed
+1347 -57

No files matched your search

+19 -3
View File
@@ -30,7 +30,7 @@ Potřeba je jen Docker Desktop.
docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
``` ```
3. Webová aplikace: <http://localhost:8081> · Swagger UI: <http://localhost:8080/swagger> · stav a verze schématu: <http://localhost:8080/health> 3. Webová aplikace: <http://localhost:8081> · Swagger UI po přihlášení administrátora: <http://localhost:8081/swagger> · stav a verze schématu: <http://localhost:8080/health>
Lokálně bez reverse proxy nastavte `PUBLIC_BASE_URL=http://localhost:8081`, aby odkazy pro ověření e-mailu a obnovu hesla vedly na web v Dockeru. Lokálně bez reverse proxy nastavte `PUBLIC_BASE_URL=http://localhost:8081`, aby odkazy pro ověření e-mailu a obnovu hesla vedly na web v Dockeru.
@@ -38,9 +38,9 @@ Při prvním startu se vytvoří účet administrátora, pokud vyplníte `ADMIN_
Pro nasazení nastavte v `deploy/.env` režim `Production`, veřejnou HTTPS adresu webu v `PUBLIC_BASE_URL` a skutečné univerzitní domény v `STUDENT_EMAIL_DOMAIN` a `TEACHER_EMAIL_DOMAIN`. Pro Email Profi vyplňte `SMTP_MAILBOX` celou adresou schránky a nastavte `SMTP_PASSWORD`. API odesílá přes `smtp.seznam.cz:465` s TLS. Pro nasazení nastavte v `deploy/.env` režim `Production`, veřejnou HTTPS adresu webu v `PUBLIC_BASE_URL` a skutečné univerzitní domény v `STUDENT_EMAIL_DOMAIN` a `TEACHER_EMAIL_DOMAIN`. Pro Email Profi vyplňte `SMTP_MAILBOX` celou adresou schránky a nastavte `SMTP_PASSWORD`. API odesílá přes `smtp.seznam.cz:465` s TLS.
Reverse proxy ukončuje HTTPS a předává požadavky přes HTTP na adresu `PROXY_UPSTREAM_BIND_ADDRESS`: `/api/*` a `/swagger` na port `API_HTTP_PORT` (výchozí `8080`), ostatní na web na port `WEB_HTTP_PORT` (výchozí `8081`). Výchozí adresa `127.0.0.1` odpovídá proxy běžící přímo na stejném hostiteli. Reverse proxy ukončuje HTTPS a předává požadavky přes HTTP na adresu `PROXY_UPSTREAM_BIND_ADDRESS`: `/api/*` na port `API_HTTP_PORT` (výchozí `8080`) a ostatní cesty včetně `/swagger` na web na port `WEB_HTTP_PORT` (výchozí `8081`). Výchozí adresa `127.0.0.1` odpovídá proxy běžící přímo na stejném hostiteli. Swagger UI ověřuje administrátorskou relaci webu. Funkce **Try it out** vyžaduje, aby stejná adresa přes proxy směrovala i `/api/*`, a chráněná volání autorizuje access tokenem.
Pro zpracování `X-Forwarded-For` a `X-Forwarded-Proto` nastavte `TRUSTED_REVERSE_PROXY_IP` na IP bezprostředního protějšku, kterou vidí API a web. Tato IP se může při průchodu Docker sítí lišit od adresy, na kterou je API vázáno. Serverová reverse proxy předává IP klienta v `X-Forwarded-For` a schéma v `X-Forwarded-Proto`. Nastavte `TRUSTED_REVERSE_PROXY_IP` na IP bezprostředního protějšku, kterou vidí API a web. Tato IP se může při průchodu Docker sítí lišit od adresy, na kterou je API vázáno. Compose automaticky nastaví privátní síť a důvěryhodnou adresu webu, přes kterou web předává IP klienta dál do API.
S nakonfigurovaným SMTP odesílá backend i e-mailové notifikace z databázové fronty. Pro mobilní push nastavte `FIREBASE_SERVICE_ACCOUNT_JSON` na jednořádkový JSON klíče servisního účtu Firebase. S nakonfigurovaným SMTP odesílá backend i e-mailové notifikace z databázové fronty. Pro mobilní push nastavte `FIREBASE_SERVICE_ACCOUNT_JSON` na jednořádkový JSON klíče servisního účtu Firebase.
@@ -64,6 +64,22 @@ Testy webové aplikace:
dotnet test --solution web/Helpdesk.Web.sln dotnet test --solution web/Helpdesk.Web.sln
``` ```
### Integrační testy backendu
Vyžadují .NET SDK 10 a spuštěný Docker. Testcontainers vytvoří dočasnou MariaDB 11.4 a testy spustí skutečné migrace.
```bash
dotnet run --project backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj
```
Pokrytí backendu integračními testy se ukládá jako Cobertura XML do `TestResults` ve výstupu testovacího projektu.
```bash
dotnet run --project backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj -- \
--coverage --coverage-output-format cobertura --coverage-output backend-coverage.cobertura.xml \
--coverage-settings "$PWD/backend/tests/Helpdesk.IntegrationTests/coverage.settings.xml"
```
## Verzování databáze ## Verzování databáze
Schéma se mění výhradně novými číslovanými skripty `db/migrations/V{NNN}__{popis}.sql`. Provedený skript se nikdy neupravuje. Migrace spouští DbUp (`Helpdesk.Migrator`) před startem API a eviduje je v tabulce `schema_version`. Schéma se mění výhradně novými číslovanými skripty `db/migrations/V{NNN}__{popis}.sql`. Provedený skript se nikdy neupravuje. Migrace spouští DbUp (`Helpdesk.Migrator`) před startem API a eviduje je v tabulce `schema_version`.
+4 -1
View File
@@ -15,14 +15,17 @@
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.14" /> <PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.14" /> <PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.14" /> <PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.14" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="10.3.1" /> <PackageVersion Include="Swashbuckle.AspNetCore.SwaggerGen" Version="10.3.1" />
<PackageVersion Include="BCrypt.Net-Next" Version="4.2.0" /> <PackageVersion Include="BCrypt.Net-Next" Version="4.2.0" />
<PackageVersion Include="MailKit" Version="5.0.0" /> <PackageVersion Include="MailKit" Version="5.0.0" />
<PackageVersion Include="FirebaseAdmin" Version="3.7.1" /> <PackageVersion Include="FirebaseAdmin" Version="3.7.1" />
<PackageVersion Include="FluentValidation" Version="12.2.0" /> <PackageVersion Include="FluentValidation" Version="12.2.0" />
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" /> <PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
<!-- testy --> <!-- testy -->
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" /> <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageVersion Include="Microsoft.Testing.Extensions.CodeCoverage" Version="18.12.0" />
<PackageVersion Include="Testcontainers.MariaDb" Version="4.16.0" />
<PackageVersion Include="xunit.v3" Version="4.0.2" /> <PackageVersion Include="xunit.v3" Version="4.0.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" /> <PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
</ItemGroup> </ItemGroup>
+14
View File
@@ -15,6 +15,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Migrator", "src\He
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.UnitTests", "tests\Helpdesk.UnitTests\Helpdesk.UnitTests.csproj", "{AB40F473-EB15-47C7-B179-A8EB066325EC}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.UnitTests", "tests\Helpdesk.UnitTests\Helpdesk.UnitTests.csproj", "{AB40F473-EB15-47C7-B179-A8EB066325EC}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.IntegrationTests", "tests\Helpdesk.IntegrationTests\Helpdesk.IntegrationTests.csproj", "{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -97,6 +99,18 @@ Global
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x64.Build.0 = Release|Any CPU {AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x64.Build.0 = Release|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.ActiveCfg = Release|Any CPU {AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.ActiveCfg = Release|Any CPU
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.Build.0 = Release|Any CPU {AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.Build.0 = Release|Any CPU
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x64.ActiveCfg = Debug|Any CPU
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x64.Build.0 = Debug|Any CPU
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x86.ActiveCfg = Debug|Any CPU
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x86.Build.0 = Debug|Any CPU
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|Any CPU.Build.0 = Release|Any CPU
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x64.ActiveCfg = Release|Any CPU
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x64.Build.0 = Release|Any CPU
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x86.ActiveCfg = Release|Any CPU
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
+1 -1
View File
@@ -13,7 +13,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
<PackageReference Include="Swashbuckle.AspNetCore" /> <PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" />
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -9,7 +9,7 @@ public static class SwaggerSetup
{ {
private const string SchemeId = "Bearer"; private const string SchemeId = "Bearer";
/// <summary>Swagger UI na <c>/swagger</c> včetně přihlášení access tokenem (NFR-04).</summary> /// <summary>Generování OpenAPI dokumentu pro administrátorské Swagger UI (NFR-04).</summary>
public static IServiceCollection AddHelpdeskSwagger(this IServiceCollection services) public static IServiceCollection AddHelpdeskSwagger(this IServiceCollection services)
{ {
services.AddEndpointsApiExplorer(); services.AddEndpointsApiExplorer();
+20 -17
View File
@@ -30,18 +30,21 @@ builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<AppExceptionHandler>(); builder.Services.AddExceptionHandler<AppExceptionHandler>();
builder.Services.AddHelpdeskSwagger(); builder.Services.AddHelpdeskSwagger();
var trustedProxy = builder.Configuration["ReverseProxy:TrustedIp"]; var trustedProxies = new[] { "ReverseProxy:TrustedIp", "ReverseProxy:TrustedWebIp" }
if (!string.IsNullOrWhiteSpace(trustedProxy)) .Where(key => !string.IsNullOrWhiteSpace(builder.Configuration[key]))
{ .Select(key => IPAddress.TryParse(builder.Configuration[key], out var address) ? address
if (!IPAddress.TryParse(trustedProxy, out var proxyAddress)) : throw new InvalidOperationException($"Nastavte platnou IP adresu v {key}."))
throw new InvalidOperationException("Nastavte platnou IP adresu důvěryhodné reverse proxy."); .ToArray();
if (trustedProxies.Length > 0)
{
builder.Services.Configure<ForwardedHeadersOptions>(options => builder.Services.Configure<ForwardedHeadersOptions>(options =>
{ {
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownIPNetworks.Clear(); options.KnownIPNetworks.Clear();
options.KnownProxies.Clear(); options.KnownProxies.Clear();
options.KnownProxies.Add(proxyAddress); foreach (var address in trustedProxies)
options.KnownProxies.Add(address);
}); });
} }
@@ -49,9 +52,14 @@ if (!string.IsNullOrWhiteSpace(trustedProxy))
builder.Services.AddRateLimiter(options => builder.Services.AddRateLimiter(options =>
{ {
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter( options.AddPolicy(RateLimitPolicies.Auth, http =>
http.Connection.RemoteIpAddress?.ToString() ?? "unknown", {
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) })); var address = http.Connection.RemoteIpAddress;
if (address is { IsIPv4MappedToIPv6: true })
address = address.MapToIPv4();
return RateLimitPartition.GetFixedWindowLimiter(address?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) });
});
options.AddPolicy(RateLimitPolicies.IssueWrites, http => RateLimitPartition.GetSlidingWindowLimiter( options.AddPolicy(RateLimitPolicies.IssueWrites, http => RateLimitPartition.GetSlidingWindowLimiter(
http.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown", http.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown",
_ => new SlidingWindowRateLimiterOptions _ => new SlidingWindowRateLimiterOptions
@@ -64,23 +72,18 @@ builder.Services.AddRateLimiter(options =>
var app = builder.Build(); var app = builder.Build();
if (!string.IsNullOrWhiteSpace(trustedProxy)) if (trustedProxies.Length > 0)
app.UseForwardedHeaders(); app.UseForwardedHeaders();
app.UseExceptionHandler(); app.UseExceptionHandler();
app.UseStatusCodePages(); app.UseStatusCodePages();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Helpdesk API v1");
options.DocumentTitle = "Helpdesk API";
});
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.UseRateLimiter(); app.UseRateLimiter();
app.MapSwagger(ApiRoutes.V1 + "/admin/openapi/{documentName}.json")
.RequireAuthorization(policy => policy.RequireRole(Roles.Admin));
app.MapControllers(); app.MapControllers();
app.Run(); app.Run();
@@ -30,7 +30,7 @@ public interface IAppDbContext
DbSet<PushDevice> PushDevices { get; } DbSet<PushDevice> PushDevices { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default); Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct); Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct);
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct); Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct); Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct);
} }
@@ -95,17 +95,23 @@ public sealed class AuthService(
var token = await tokens.ValidateAsync(request.RefreshToken, TokenType.Refresh) var token = await tokens.ValidateAsync(request.RefreshToken, TokenType.Refresh)
?? throw new UnauthorizedException("Neplatný refresh token."); ?? throw new UnauthorizedException("Neplatný refresh token.");
if (!await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct)) // Původní token zůstane zamčený, dokud není nový pár uložený.
await using (var transaction = await db.BeginWriteAsync(ct))
{ {
await revocation.RevokeAllAsync(token.UserId, RevokeReason.ReuseDetected, ct); if (await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu."); {
var user = await db.Users.SingleOrDefaultAsync(u => u.Id == token.UserId, ct);
if (user is null || !user.IsActive)
throw new UnauthorizedException("Účet neexistuje nebo je deaktivován.");
var response = await IssueTokenPairAsync(user, ct);
await transaction.CommitAsync(ct);
return response;
}
} }
var user = await db.Users.SingleOrDefaultAsync(u => u.Id == token.UserId, ct); await revocation.RevokeAllAsync(token.UserId, RevokeReason.ReuseDetected, ct);
if (user is null || !user.IsActive) throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
throw new UnauthorizedException("Účet neexistuje nebo je deaktivován.");
return await IssueTokenPairAsync(user, ct);
} }
/// <summary>Odhlášení jednoho zařízení – zneplatní aktuální access token a k němu předaný refresh token.</summary> /// <summary>Odhlášení jednoho zařízení – zneplatní aktuální access token a k němu předaný refresh token.</summary>
@@ -53,7 +53,7 @@ public sealed partial class IssueService(
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority); issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName); AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName);
await notificationWriter.ForIssueAsync(issue, actor.Id, [assignee.Id], NotificationType.IssueAssigned, "Závada byla přiřazena", ct); await notificationWriter.ForIssueAsync(issue, actor.Id, [assignee.Id], NotificationType.IssueAssigned, "Závada byla přiřazena", ct);
if (from == IssueStatus.Received && issue.ReporterId != assignee.Id) if (from != issue.Status && issue.ReporterId != assignee.Id)
await notificationWriter.ForIssueAsync(issue, actor.Id, [issue.ReporterId], NotificationType.IssueStatusChanged, "Závada byla přiřazena", ct); await notificationWriter.ForIssueAsync(issue, actor.Id, [issue.ReporterId], NotificationType.IssueStatusChanged, "Závada byla přiřazena", ct);
await SaveAsync(ct); await SaveAsync(ct);
@@ -30,7 +30,7 @@ public sealed partial class ProposalService(
{ {
await GetActorRoleAsync(ct); await GetActorRoleAsync(ct);
var (title, description) = ValidateDetails(request); var (title, description) = ValidateDetails(request);
await using (var transaction = await db.BeginProposalWriteAsync(ct)) await using (var transaction = await db.BeginWriteAsync(ct))
{ {
var proposal = await LockProposalAsync(id, ct); var proposal = await LockProposalAsync(id, ct);
if (!proposal.IsAuthor(currentUser.Id)) if (!proposal.IsAuthor(currentUser.Id))
@@ -63,7 +63,7 @@ public sealed partial class ProposalService(
if (note is not null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes) if (note is not null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes)
throw new BadRequestException("Vyjádření je příliš dlouhé."); throw new BadRequestException("Vyjádření je příliš dlouhé.");
await using (var transaction = await db.BeginProposalWriteAsync(ct)) await using (var transaction = await db.BeginWriteAsync(ct))
{ {
var proposal = await LockProposalAsync(id, ct); var proposal = await LockProposalAsync(id, ct);
var previous = proposal.Status; var previous = proposal.Status;
@@ -94,7 +94,7 @@ public sealed partial class ProposalService(
{ {
await GetActorRoleAsync(ct); await GetActorRoleAsync(ct);
var actorId = currentUser.Id; var actorId = currentUser.Id;
await using var transaction = await db.BeginProposalWriteAsync(ct); await using var transaction = await db.BeginWriteAsync(ct);
var proposal = await LockProposalAsync(id, ct); var proposal = await LockProposalAsync(id, ct);
if (proposal.IsAuthor(actorId)) if (proposal.IsAuthor(actorId))
throw new ForbiddenException("Autor nemůže hlasovat o vlastním návrhu."); throw new ForbiddenException("Autor nemůže hlasovat o vlastním návrhu.");
@@ -54,7 +54,7 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
} }
} }
public Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct) => public Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct) =>
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct); Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
public async Task<Proposal?> LockProposalAsync(int id, CancellationToken ct) public async Task<Proposal?> LockProposalAsync(int id, CancellationToken ct)
@@ -0,0 +1,98 @@
using System.Net;
using System.Net.Http.Json;
using System.Text;
using Helpdesk.Application.Auth;
using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Common;
using Helpdesk.Application.Users;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class AdministrationTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
[Theory]
[InlineData("/api/v1/issue-categories")]
[InlineData("/api/v1/proposal-categories")]
public async Task AdministratorsCanManageCategories(string route)
{
using var anonymous = fixture.CreateClient();
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
var user = await fixture.RegisterAsync(anonymous);
using var member = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
var request = new SaveCategoryRequest("Testovací kategorie", "Popis");
await ExpectAsync(member.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Forbidden);
var category = await ReadAsync<CategoryDto>(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Created);
await ExpectAsync(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Conflict);
var path = $"{route}/{category.Id}";
var edited = await ReadAsync<CategoryDto>(admin.PutAsJsonAsync(path, request with { Name = "Upravená kategorie" }, Cancellation));
Assert.Equal("Upravená kategorie", edited.Name);
await ExpectAsync(admin.DeleteAsync(path, Cancellation), HttpStatusCode.NoContent);
var active = await ReadAsync<CategoryDto[]>(member.GetAsync(route + "?includeInactive=true", Cancellation));
var all = await ReadAsync<CategoryDto[]>(admin.GetAsync(route + "?includeInactive=true", Cancellation));
Assert.DoesNotContain(active, item => item.Id == category.Id);
Assert.False(Assert.Single(all, item => item.Id == category.Id).IsActive);
}
[Fact]
public async Task BuildingCodesAreUniqueAndInactiveBuildingsStayAvailableToTheAdministrator()
{
using var anonymous = fixture.CreateClient();
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
const string route = "/api/v1/buildings";
var request = new SaveBuildingRequest("TEST", "Testovací budova", null);
var building = await ReadAsync<BuildingDto>(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Created);
await ExpectAsync(admin.PostAsJsonAsync(route, request with { Code = " TEST " }, Cancellation), HttpStatusCode.Conflict);
var path = $"{route}/{building.Id}";
var edited = await ReadAsync<BuildingDto>(admin.PutAsJsonAsync(path, request with { Address = "Náměstí 1" }, Cancellation));
Assert.Equal("Náměstí 1", edited.Address);
await ExpectAsync(admin.DeleteAsync(path, Cancellation), HttpStatusCode.NoContent);
var active = await ReadAsync<BuildingDto[]>(admin.GetAsync(route, Cancellation));
var all = await ReadAsync<BuildingDto[]>(admin.GetAsync(route + "?includeInactive=true", Cancellation));
Assert.DoesNotContain(active, item => item.Id == building.Id);
Assert.False(Assert.Single(all, item => item.Id == building.Id).IsActive);
}
[Fact]
public async Task ProfileDataRoundTripsAndDeactivationRevokesTheSession()
{
using var anonymous = fixture.CreateClient();
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
var user = await fixture.RegisterAsync(anonymous);
using var member = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
const string profile = "/api/v1/users/me";
const string phone = "+420 123 456 789";
var request = new UpdateProfileRequest("Jana", "Nováková", phone, false);
var validation = await ReadAsync<ValidationProblemDetails>(member.PutAsJsonAsync(profile,
request with { Phone = "invalid" }, Cancellation), HttpStatusCode.BadRequest);
Assert.Contains("phone", validation.Errors.Keys);
var updated = await ReadAsync<UserDto>(member.PutAsJsonAsync(profile, request, Cancellation));
Assert.Equal(updated, await ReadAsync<UserDto>(member.GetAsync(profile, Cancellation)));
Assert.Equal((request.FirstName, request.LastName, phone, false),
(updated.FirstName, updated.LastName, updated.Phone, updated.EmailNotificationsEnabled));
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var encrypted = await db.Database.SqlQuery<byte[]>($"SELECT phone_encrypted AS Value FROM app_user WHERE id = {user.Id}")
.SingleAsync(Cancellation);
Assert.NotEmpty(encrypted);
Assert.False(Encoding.UTF8.GetBytes(phone).SequenceEqual(encrypted));
var search = $"/api/v1/admin/users?q={Uri.EscapeDataString(user.Email)}&role=STUDENT&pageSize=1";
await ExpectAsync(member.GetAsync(search, Cancellation), HttpStatusCode.Forbidden);
var page = await ReadAsync<PagedResult<AdminUserDto>>(admin.GetAsync(search, Cancellation));
Assert.Equal(user.Id, Assert.Single(page.Items).Id);
var activation = $"/api/v1/admin/users/{user.Id}/active";
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(false), Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(member.GetAsync(profile, Cancellation), HttpStatusCode.Unauthorized);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, Password), Cancellation),
HttpStatusCode.Forbidden);
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(true), Cancellation), HttpStatusCode.NoContent);
Assert.Equal(user.Id, (await LoginAsync(anonymous, user.Email)).User.Id);
}
}
@@ -0,0 +1,95 @@
using System.Globalization;
using System.IO.Compression;
using System.Net;
using System.Net.Http.Json;
using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Issues;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class AttachmentTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
[Fact]
public async Task AttachmentsRespectFormatAndAccessAndFailedBatchesAreNotSaved()
{
using var anonymous = fixture.CreateClient();
var authorUser = await fixture.RegisterAsync(anonymous);
var otherUser = await fixture.RegisterAsync(anonymous);
using var author = fixture.CreateClient((await LoginAsync(anonymous, authorUser.Email)).AccessToken);
using var other = fixture.CreateClient((await LoginAsync(anonymous, otherUser.Email)).AccessToken);
var categories = await ReadAsync<CategoryDto[]>(author.GetAsync("/api/v1/issue-categories", Cancellation));
var png = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6t1sAAAAASUVORK5CYII=");
using var createForm = new MultipartFormDataContent();
createForm.Add(new StringContent("Rozbitý zámek"), "title");
createForm.Add(new StringContent("Dveře nelze odemknout."), "description");
createForm.Add(new StringContent(categories[0].Id.ToString(CultureInfo.InvariantCulture)), "categoryId");
AddFile(createForm, "zamek.png", png);
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var store = scope.ServiceProvider.GetRequiredService<IAttachmentStore>();
try
{
var issue = await ReadAsync<IssueDetail>(author.PostAsync("/api/v1/issues", createForm, Cancellation), HttpStatusCode.Created);
var pngAttachment = Assert.Single(issue.Attachments);
var download = $"/api/v1/attachments/{pngAttachment.Id}";
using var fetched = await author.GetAsync(download, Cancellation);
Assert.Equal(HttpStatusCode.OK, fetched.StatusCode);
Assert.Equal("image/png", fetched.Content.Headers.ContentType?.MediaType);
Assert.Equal("nosniff", Assert.Single(fetched.Headers.GetValues("X-Content-Type-Options")));
Assert.Equal(png, await fetched.Content.ReadAsByteArrayAsync(Cancellation));
await ExpectAsync(other.GetAsync(download, Cancellation), HttpStatusCode.Forbidden);
var path = $"/api/v1/issues/{issue.Id}/attachments";
using var mixed = new MultipartFormDataContent();
AddFile(mixed, "spravny.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
AddFile(mixed, "podvrzeny.png", "obsah nemá formát PNG"u8.ToArray());
await ExpectAsync(author.PostAsync(path, mixed, Cancellation), HttpStatusCode.BadRequest);
using var wrongField = new MultipartFormDataContent();
wrongField.Add(new ByteArrayContent(png), "image", "zamek.png");
await ExpectAsync(author.PostAsync(path, wrongField, Cancellation), HttpStatusCode.BadRequest);
var afterFailure = await ReadAsync<IssueDetail>(author.GetAsync($"/api/v1/issues/{issue.Id}", Cancellation));
Assert.Equal(issue.RowVersion, afterFailure.RowVersion);
Assert.Equal(pngAttachment.Id, Assert.Single(afterFailure.Attachments).Id);
using var files = new MultipartFormDataContent();
AddFile(files, "protokol.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
AddFile(files, "fotka.jpg", [0xff, 0xd8, 0xff, 0xd9]);
AddFile(files, "fotka.heic", [0, 0, 0, 20, .. "ftypmif1"u8, 0, 0, 0, 0, .. "heic"u8]);
AddFile(files, "protokol.docx", Docx());
var added = await ReadAsync<AttachmentDto[]>(author.PostAsync(path, files, Cancellation));
Assert.Equal(["application/pdf", "image/jpeg", "image/heic",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"], added.Select(item => item.ContentType));
var key = await db.Attachments.Where(item => item.Id == pngAttachment.Id).Select(item => item.StoredFileName).SingleAsync(Cancellation);
store.Delete(key);
await ExpectAsync(author.GetAsync(download, Cancellation), HttpStatusCode.NotFound);
}
finally
{
foreach (var key in await db.Attachments.Select(item => item.StoredFileName).ToListAsync(CancellationToken.None))
store.Delete(key);
}
}
private static void AddFile(MultipartFormDataContent form, string name, byte[] bytes) =>
form.Add(new ByteArrayContent(bytes), "files", name);
private static byte[] Docx()
{
using var stream = new MemoryStream();
using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
{
using (var contentTypes = zip.CreateEntry("[Content_Types].xml").Open())
contentTypes.Write("<Types/>"u8);
using (var document = zip.CreateEntry("word/document.xml").Open())
document.Write("<document/>"u8);
}
return stream.ToArray();
}
}
@@ -0,0 +1,98 @@
using System.Net;
using System.Net.Http.Json;
using Helpdesk.Application.Auth;
using Helpdesk.Domain.Auth;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.JsonWebTokens;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
[Fact]
public async Task ChangingPasswordThroughAnEmailLinkRevokesTheOldSession()
{
using var anonymous = fixture.CreateClient();
var user = await fixture.RegisterAsync(anonymous);
using var oldSession = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/forgot-password",
new ForgotPasswordRequest(user.Email), Cancellation), HttpStatusCode.NoContent);
const string newPassword = "New-integration-password";
var reset = new ResetPasswordRequest(await fixture.TakeResetTokenAsync(user.Email), newPassword);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.BadRequest);
await ExpectAsync(oldSession.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login",
new LoginRequest(user.Email, Password), Cancellation), HttpStatusCode.Unauthorized);
var session = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
new LoginRequest(user.Email, newPassword), Cancellation));
Assert.Equal(user.Id, session.User.Id);
}
[Fact]
public async Task LogoutRevokesOnlyTheCurrentSession()
{
using var anonymous = fixture.CreateClient();
var user = await fixture.RegisterAsync(anonymous);
var session = await LoginAsync(anonymous, user.Email);
var otherSession = await LoginAsync(anonymous, user.Email);
using var client = fixture.CreateClient(session.AccessToken);
using var otherClient = fixture.CreateClient(otherSession.AccessToken);
var refresh = new RefreshTokenRequest(session.RefreshToken);
await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/logout", refresh, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(client.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.OK);
var accessId = new JsonWebToken(session.AccessToken).Id;
var refreshId = new JsonWebToken(session.RefreshToken).Id;
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
Assert.Equal(2, await db.AuthTokens.CountAsync(token =>
token.UserId == user.Id && (token.Jti == accessId || token.Jti == refreshId) &&
token.RevokeReason == RevokeReason.Logout, Cancellation));
}
[Fact]
public async Task ConcurrentRefreshRevokesTheNewPairAndOtherSessions()
{
using var anonymous = fixture.CreateClient();
var user = await fixture.RegisterAsync(anonymous);
var session = await LoginAsync(anonymous, user.Email);
var otherSession = await LoginAsync(anonymous, user.Email);
var refresh = new RefreshTokenRequest(session.RefreshToken);
var pause = fixture.TokenSaves.PauseNextSave();
Task<HttpResponseMessage> first;
Task<HttpResponseMessage> duplicate;
try
{
first = anonymous.PostAsJsonAsync("/api/v1/auth/refresh", refresh, Cancellation);
await pause.Entered.Task.WaitAsync(TimeSpan.FromSeconds(15), Cancellation);
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
Assert.Equal(2, await db.AuthTokens.CountAsync(token =>
token.UserId == user.Id && token.TokenType == TokenType.Refresh && token.RevokedAt == null, Cancellation));
duplicate = anonymous.PostAsJsonAsync("/api/v1/auth/refresh", refresh, Cancellation);
}
finally
{
pause.Release();
}
var renewed = await ReadAsync<AuthResponse>(first);
await ExpectAsync(duplicate, HttpStatusCode.Unauthorized);
await using var after = fixture.Services.CreateAsyncScope();
var tokens = after.ServiceProvider.GetRequiredService<HelpdeskDbContext>().AuthTokens;
Assert.False(await tokens.AnyAsync(token => token.UserId == user.Id && token.RevokedAt == null, Cancellation));
using var renewedClient = fixture.CreateClient(renewed.AccessToken);
using var otherClient = fixture.CreateClient(otherSession.AccessToken);
await ExpectAsync(renewedClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
}
}
@@ -0,0 +1,210 @@
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 email.TakeTokenAsync(address, "/confirm-email")), 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> 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));
}
}
@@ -0,0 +1,87 @@
using System.Net;
using System.Text.Json;
using Helpdesk.Api.Controllers;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MySqlConnector;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class DatabaseTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
[Fact]
public async Task MigratorAppliesEveryScriptAndEfCanReadTheSchema()
{
using var client = fixture.CreateClient();
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var expected = Directory.EnumerateFiles(MigrationsPath, "V*__*.sql")
.Select(Path.GetFileName).Order(StringComparer.Ordinal).ToArray();
var applied = await db.Database
.SqlQueryRaw<string>("SELECT scriptname AS Value FROM schema_version ORDER BY schemaversionid")
.ToListAsync(Cancellation);
Assert.Equal(expected, applied);
var health = await ReadAsync<HealthResponse>(client.GetAsync("/health", Cancellation));
Assert.Equal(new HealthResponse("Healthy", expected[^1]), health);
await db.Users.AsNoTracking().ToListAsync(Cancellation);
await db.AuthTokens.AsNoTracking().ToListAsync(Cancellation);
await db.Buildings.AsNoTracking().ToListAsync(Cancellation);
await db.IssueCategories.AsNoTracking().ToListAsync(Cancellation);
await db.ProposalCategories.AsNoTracking().ToListAsync(Cancellation);
await db.Issues.AsNoTracking().ToListAsync(Cancellation);
await db.IssueEvents.AsNoTracking().ToListAsync(Cancellation);
await db.IssueTimings.ToListAsync(Cancellation);
await db.Attachments.AsNoTracking().ToListAsync(Cancellation);
await db.Proposals.AsNoTracking().ToListAsync(Cancellation);
await db.ProposalEvents.AsNoTracking().ToListAsync(Cancellation);
await db.ProposalVotes.AsNoTracking().ToListAsync(Cancellation);
await db.ProposalScores.ToListAsync(Cancellation);
await db.Notifications.AsNoTracking().ToListAsync(Cancellation);
await db.NotificationDeliveries.AsNoTracking().ToListAsync(Cancellation);
await db.PushDevices.AsNoTracking().ToListAsync(Cancellation);
}
[Fact]
public async Task OnlyAdministratorsCanReadTheOpenApiDocument()
{
using var client = fixture.CreateClient();
const string path = "/api/v1/admin/openapi/v1.json";
await ExpectAsync(client.GetAsync(path, Cancellation), HttpStatusCode.Unauthorized);
var student = await fixture.RegisterAsync(client);
using var studentClient = fixture.CreateClient((await LoginAsync(client, student.Email)).AccessToken);
await ExpectAsync(studentClient.GetAsync(path, Cancellation), HttpStatusCode.Forbidden);
using var admin = fixture.CreateClient((await LoginAsync(client, AdminEmail)).AccessToken);
await ExpectAsync(admin.GetAsync("/swagger/index.html", Cancellation), HttpStatusCode.NotFound);
await ExpectAsync(admin.GetAsync("/swagger/v1/swagger.json", Cancellation), HttpStatusCode.NotFound);
using var document = await ReadAsync<JsonDocument>(admin.GetAsync(path, Cancellation));
var paths = document.RootElement.GetProperty("paths");
var create = paths.GetProperty("/api/v1/issues").GetProperty("post").GetProperty("requestBody").GetProperty("content");
Assert.True(create.TryGetProperty("application/json", out _));
var createSchema = create.GetProperty("multipart/form-data").GetProperty("schema");
Assert.Contains(createSchema.GetProperty("required").EnumerateArray(), field => field.GetString() == "categoryId");
var uploadSchema = paths.GetProperty("/api/v1/issues/{id}/attachments").GetProperty("post")
.GetProperty("requestBody").GetProperty("content").GetProperty("multipart/form-data").GetProperty("schema");
Assert.Equal("files", Assert.Single(uploadSchema.GetProperty("required").EnumerateArray()).GetString());
var files = uploadSchema.GetProperty("properties").GetProperty("files");
Assert.Equal(5, files.GetProperty("maxItems").GetInt32());
Assert.Equal("binary", files.GetProperty("items").GetProperty("format").GetString());
}
[Fact]
public async Task DatabaseRejectsAnAssignedIssueWithoutAnAssignee()
{
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var reporterId = await db.Users.Where(user => user.Email == AdminEmail).Select(user => user.Id).SingleAsync(Cancellation);
var categoryId = await db.IssueCategories.MinAsync(category => category.Id, Cancellation);
var error = await Assert.ThrowsAsync<MySqlException>(() => db.Database.ExecuteSqlInterpolatedAsync($"""
INSERT INTO issue (title, description, category_id, reporter_id, status)
VALUES ('Test', 'Test', {categoryId}, {reporterId}, 'ASSIGNED')
""", Cancellation));
Assert.Contains("ck_issue_assignee", error.Message);
}
}
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<OutputType>Exe</OutputType>
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Helpdesk.Api\Helpdesk.Api.csproj" />
<ProjectReference Include="..\..\src\Helpdesk.Migrator\Helpdesk.Migrator.csproj" />
<None Include="..\..\..\db\migrations\V*__*.sql" Link="migrations\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
<PackageReference Include="Microsoft.Testing.Extensions.CodeCoverage" PrivateAssets="all" />
<PackageReference Include="MySqlConnector" />
<PackageReference Include="Testcontainers.MariaDb" />
<PackageReference Include="xunit.v3" />
<Using Include="Xunit" />
</ItemGroup>
</Project>
@@ -0,0 +1,137 @@
using System.Net;
using System.Net.Http.Json;
using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Common;
using Helpdesk.Application.Issues;
using Helpdesk.Application.Notifications;
using Helpdesk.Application.Statistics;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
[Fact]
public async Task ReporterAndAssigneesCanResolveAnIssueAndManagementCanReportOnIt()
{
using var anonymous = fixture.CreateClient();
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
var author = await fixture.RegisterAsync(anonymous);
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, author.Email)).AccessToken);
var management = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
var firstAssignee = await fixture.RegisterStaffAsync(anonymous, admin, "FACILITY_MANAGER");
var secondAssignee = await fixture.RegisterStaffAsync(anonymous, admin, "FACILITY_MANAGER");
using var manager = fixture.CreateClient(management.AccessToken);
using var firstSolver = fixture.CreateClient(firstAssignee.AccessToken);
using var secondSolver = fixture.CreateClient(secondAssignee.AccessToken);
var categories = await ReadAsync<CategoryDto[]>(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
var buildings = await ReadAsync<BuildingDto[]>(reporter.GetAsync("/api/v1/buildings", Cancellation));
var request = new CreateIssueRequest("Nefunkční projektor", "Projektor se nezapne.", categories[0].Id, buildings[0].Id, "A101");
var issue = await PostIssueAsync(reporter, "/api/v1/issues", request, HttpStatusCode.Created);
var path = $"/api/v1/issues/{issue.Id}";
Assert.Equal("RECEIVED", issue.Status);
await ExpectAsync(anonymous.GetAsync(path, Cancellation), HttpStatusCode.Unauthorized);
issue = await ReadAsync<IssueDetail>(reporter.PutAsJsonAsync(path,
new EditIssueRequest(issue.Title, "Projektor nereaguje ani po restartu.", issue.CategoryId,
issue.BuildingId, issue.LocationDetail, issue.RowVersion), Cancellation));
Assert.Equal("Projektor nereaguje ani po restartu.", issue.Description);
var assign = new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion);
await ExpectAsync(reporter.PostAsJsonAsync(path + "/assign", assign, Cancellation), HttpStatusCode.Forbidden);
issue = await PostIssueAsync(manager, path + "/assign", assign);
await ExpectAsync(firstSolver.PostAsJsonAsync(path + "/start",
new IssueVersionRequest(assign.RowVersion), Cancellation), HttpStatusCode.Conflict);
var reporterNotifications = await InboxAsync(reporter, issue.Id);
Assert.Equal("ISSUE_STATUS_CHANGED", Assert.Single(reporterNotifications).Type);
issue = await PostIssueAsync(manager, path + "/assign", new AssignIssueRequest(secondAssignee.User.Id, null, issue.RowVersion));
Assert.Equal("ISSUE_ASSIGNED", Assert.Single(await InboxAsync(secondSolver, issue.Id)).Type);
Assert.Equal(reporterNotifications, await InboxAsync(reporter, issue.Id));
issue = await PostIssueAsync(secondSolver, path + "/start", new IssueVersionRequest(issue.RowVersion));
Assert.Equal("IN_PROGRESS", issue.Status);
reporterNotifications = await InboxAsync(reporter, issue.Id);
issue = await PostIssueAsync(manager, path + "/assign", new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion));
Assert.Equal("ASSIGNED", issue.Status);
var reassignment = Assert.Single((await InboxAsync(reporter, issue.Id)).Except(reporterNotifications));
Assert.Equal("ISSUE_STATUS_CHANGED", reassignment.Type);
Assert.Equal(2, (await InboxAsync(firstSolver, issue.Id)).Count(notification => notification.Type == "ISSUE_ASSIGNED"));
issue = await PostIssueAsync(firstSolver, path + "/start", new IssueVersionRequest(issue.RowVersion));
const string commentText = "Porucha stále trvá.";
var comment = await ReadAsync<IssueEventDto>(reporter.PostAsJsonAsync(path + "/comments",
new CommentRequest(commentText), Cancellation));
issue = await ReadAsync<IssueDetail>(firstSolver.GetAsync(path, Cancellation));
issue = await PostIssueAsync(firstSolver, path + "/submit-for-verification", new VerifyIssueRequest(issue.RowVersion, null));
Assert.Equal("PENDING_VERIFICATION", issue.Status);
issue = await PostIssueAsync(reporter, path + "/reopen", new IssueReasonRequest(issue.RowVersion, "Porucha se vrátila."));
Assert.Equal("IN_PROGRESS", issue.Status);
Assert.Contains(await InboxAsync(firstSolver, issue.Id), notification => notification.Type == "ISSUE_REOPENED");
issue = await PostIssueAsync(firstSolver, path + "/submit-for-verification", new VerifyIssueRequest(issue.RowVersion, "Ověřeno."));
issue = await PostIssueAsync(reporter, path + "/confirm", new IssueVersionRequest(issue.RowVersion));
Assert.Equal("RESOLVED", issue.Status);
var events = await ReadAsync<IssueEventDto[]>(reporter.GetAsync(path + "/events", Cancellation));
Assert.Equal(commentText, Assert.Single(events, entry => entry.Id == comment.Id).Note);
Assert.Equal("RESOLVED", events[^1].ToStatus);
var openIssue = await PostIssueAsync(reporter, "/api/v1/issues",
request with { Title = "Porucha osvětlení" }, HttpStatusCode.Created);
await VerifyReadsAsync(reporter, manager, issue, openIssue);
var rejected = await PostIssueAsync(manager, $"/api/v1/issues/{openIssue.Id}/reject",
new IssueReasonRequest(openIssue.RowVersion, "Duplicitní hlášení."));
Assert.Equal("REJECTED", rejected.Status);
}
private static async Task VerifyReadsAsync(HttpClient reporter, HttpClient manager, IssueDetail resolved, IssueDetail open)
{
var query = $"/api/v1/issues?categoryId={resolved.CategoryId}&buildingId={resolved.BuildingId}&pageSize=1";
var first = await ReadAsync<PagedResult<IssueSummary>>(manager.GetAsync(query + "&page=1", Cancellation));
var second = await ReadAsync<PagedResult<IssueSummary>>(manager.GetAsync(query + "&page=2", Cancellation));
var filtered = await ReadAsync<PagedResult<IssueSummary>>(manager.GetAsync(query + "&status=RESOLVED", Cancellation));
Assert.Equal(2, first.TotalCount);
Assert.Equal(open.Id, Assert.Single(first.Items).Id);
Assert.Equal(resolved.Id, Assert.Single(second.Items).Id);
Assert.Equal(1, filtered.TotalCount);
Assert.Equal(resolved.Id, Assert.Single(filtered.Items).Id);
const string overview = "/api/v1/statistics/overview";
await ExpectAsync(reporter.GetAsync(overview, Cancellation), HttpStatusCode.Forbidden);
var from = Uri.EscapeDataString(resolved.CreatedAt.AddMinutes(-1).ToString("O"));
var to = Uri.EscapeDataString(open.CreatedAt.AddMinutes(1).ToString("O"));
var period = $"?from={from}&to={to}";
var statistics = await ReadAsync<StatisticsOverview>(manager.GetAsync(overview + period, Cancellation));
Assert.Equal(2, statistics.TotalIssues);
Assert.Equal(1, statistics.IssuesByStatus["RESOLVED"]);
Assert.Equal(1, statistics.IssuesByStatus["RECEIVED"]);
Assert.NotNull(statistics.AverageHoursToAssignment);
Assert.NotNull(statistics.AverageHoursToClosure);
var byCategory = Assert.Single(await ReadAsync<IssueCategoryStatistics[]>(
manager.GetAsync("/api/v1/statistics/issues/by-category" + period, Cancellation)));
Assert.Equal((resolved.CategoryId, 2), (byCategory.CategoryId, byCategory.IssueCount));
Assert.NotNull(byCategory.AverageHoursToResolution);
var byBuilding = Assert.Single(await ReadAsync<IssueBuildingStatistics[]>(
manager.GetAsync("/api/v1/statistics/issues/by-building" + period, Cancellation)));
Assert.Equal((resolved.BuildingId, 2), (byBuilding.BuildingId, byBuilding.IssueCount));
var byAssignee = Assert.Single(await ReadAsync<IssueAssigneeStatistics[]>(
manager.GetAsync("/api/v1/statistics/issues/by-assignee" + period, Cancellation)));
Assert.Equal((resolved.AssigneeId, 1, 0), ((int?)byAssignee.AssigneeId, byAssignee.ResolvedIssues, byAssignee.OpenIssues));
var available = await ReadAsync<AssignableUserDto[]>(manager.GetAsync("/api/v1/users/assignable", Cancellation));
Assert.Contains(available, user => user.Id == resolved.AssigneeId && user.OpenIssues == 0);
var trend = await ReadAsync<IssueTrendPoint[]>(manager.GetAsync("/api/v1/statistics/issues/trend" + period, Cancellation));
Assert.Equal(2, trend.Sum(point => point.CreatedIssues));
Assert.Equal(1, trend.Sum(point => point.ClosedIssues));
var after = await ReadAsync<StatisticsOverview>(manager.GetAsync(overview + $"?from={to}", Cancellation));
Assert.Equal(0, after.TotalIssues);
}
private static Task<IssueDetail> PostIssueAsync<T>(
HttpClient client, string path, T request, HttpStatusCode expected = HttpStatusCode.OK) =>
ReadAsync<IssueDetail>(client.PostAsJsonAsync(path, request, Cancellation), expected);
private static async Task<NotificationDto[]> InboxAsync(HttpClient client, int issueId)
{
var notifications = await ReadAsync<PagedResult<NotificationDto>>(client.GetAsync("/api/v1/notifications", Cancellation));
return notifications.Items.Where(notification => notification.IssueId == issueId).ToArray();
}
}
@@ -0,0 +1,112 @@
using System.Net;
using System.Net.Http.Json;
using Helpdesk.Api.Controllers;
using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Common;
using Helpdesk.Application.Issues;
using Helpdesk.Application.Notifications;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class NotificationTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
[Fact]
public async Task FailedEmailCanBeRetriedAndOnlyTheRecipientCanMarkNotificationsRead()
{
using var anonymous = fixture.CreateClient();
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
var user = await fixture.RegisterAsync(anonymous);
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
using var manager = fixture.CreateClient(managerSession.AccessToken);
var categories = await ReadAsync<CategoryDto[]>(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
var request = new CreateIssueRequest("Porucha v učebně", "Závadu je potřeba prověřit.", categories[0].Id, null, null);
const string inbox = "/api/v1/notifications";
const string deliveries = "/api/v1/admin/notification-deliveries";
fixture.FailNextEmail(managerSession.User.Email, "TEST_RECIPIENT_REJECTED", retryable: false);
var issue = await ReadAsync<IssueDetail>(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created);
var notifications = await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation));
var notification = Assert.Single(notifications.Items);
Assert.Equal((issue.Id, "ISSUE_CREATED"), (notification.IssueId, notification.Type));
await ExpectAsync(reporter.PostAsync($"{inbox}/{notification.Id}/read", null, Cancellation), HttpStatusCode.NotFound);
await ExpectAsync(reporter.GetAsync(deliveries, Cancellation), HttpStatusCode.Forbidden);
await ExpectAsync(admin.GetAsync(deliveries + "?status=invalid", Cancellation), HttpStatusCode.BadRequest);
var failed = await WaitForDeliveryAsync(admin, notification.Id, "FAILED");
Assert.Equal((1, "TEST_RECIPIENT_REJECTED"), (failed.AttemptCount, failed.LastError));
Assert.Null(failed.NextAttemptAt);
var retry = $"{deliveries}/{failed.Id}/retry";
await ExpectAsync(admin.PostAsync(retry, null, Cancellation), HttpStatusCode.NoContent);
var sent = await WaitForDeliveryAsync(admin, notification.Id, "SENT");
Assert.Equal(1, sent.AttemptCount);
Assert.NotNull(sent.SentAt);
Assert.Null(sent.LastError);
await ExpectAsync(admin.PostAsync(retry, null, Cancellation), HttpStatusCode.Conflict);
await ExpectAsync(admin.PostAsync($"{deliveries}/{int.MaxValue}/retry", null, Cancellation), HttpStatusCode.NotFound);
var read = $"{inbox}/{notification.Id}/read";
await ExpectAsync(manager.PostAsync(read, null, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(manager.PostAsync(read, null, Cancellation), HttpStatusCode.NoContent);
Assert.Equal(0, (await ReadAsync<UnreadCountDto>(manager.GetAsync(inbox + "/unread-count", Cancellation))).Count);
fixture.FailNextEmail(managerSession.User.Email, "TEST_TEMPORARY_FAILURE", retryable: true);
var secondIssue = await ReadAsync<IssueDetail>(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created);
notifications = await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation));
notification = Assert.Single(notifications.Items);
Assert.Equal(secondIssue.Id, notification.IssueId);
var pending = await WaitForDeliveryAsync(admin, notification.Id, "PENDING", attempts: 1);
Assert.Equal("TEST_TEMPORARY_FAILURE", pending.LastError);
Assert.True(pending.NextAttemptAt > DateTime.UtcNow);
await ExpectAsync(manager.PostAsync(inbox + "/read-all", null, Cancellation), HttpStatusCode.NoContent);
Assert.Empty((await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation))).Items);
}
[Fact]
public async Task DeviceRegistrationPreservesCaseAndTransfersOwnership()
{
using var anonymous = fixture.CreateClient();
var firstUser = await fixture.RegisterAsync(anonymous);
var secondUser = await fixture.RegisterAsync(anonymous);
using var first = fixture.CreateClient((await LoginAsync(anonymous, firstUser.Email)).AccessToken);
using var second = fixture.CreateClient((await LoginAsync(anonymous, secondUser.Email)).AccessToken);
const string route = "/api/v1/devices";
var token = new RegisterDeviceRequest("CaseSensitiveDevice");
var otherCase = new RegisterDeviceRequest("casesensitivedevice");
await ExpectAsync(first.PostAsJsonAsync(route, new RegisterDeviceRequest("invalid token"), Cancellation), HttpStatusCode.BadRequest);
await ExpectAsync(first.PostAsJsonAsync(route, token, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(first.PostAsJsonAsync(route, otherCase, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(second.PostAsJsonAsync(route, token, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(first.DeleteAsync($"{route}/{token.Token}", Cancellation), HttpStatusCode.NoContent);
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var devices = await db.PushDevices.AsNoTracking().ToListAsync(Cancellation);
Assert.Equal(secondUser.Id, Assert.Single(devices, item => item.FcmToken == token.Token).UserId);
Assert.Equal(firstUser.Id, Assert.Single(devices, item => item.FcmToken == otherCase.Token).UserId);
await ExpectAsync(second.DeleteAsync($"{route}/{token.Token}", Cancellation), HttpStatusCode.NoContent);
Assert.Equal(otherCase.Token, await db.PushDevices.Select(item => item.FcmToken).SingleAsync(Cancellation));
}
private static async Task<NotificationDeliveryDto> WaitForDeliveryAsync(HttpClient client, int notificationId, string status, int attempts = 1)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(Cancellation);
timeout.CancelAfter(TimeSpan.FromSeconds(15));
var path = $"/api/v1/admin/notification-deliveries?status={status}";
while (!timeout.IsCancellationRequested)
{
var page = await ReadAsync<PagedResult<NotificationDeliveryDto>>(client.GetAsync(path, timeout.Token));
var delivery = page.Items.SingleOrDefault(item =>
item.NotificationId == notificationId && item.Channel == "EMAIL" && item.AttemptCount == attempts);
if (delivery is not null)
return delivery;
await Task.Delay(TimeSpan.FromMilliseconds(100), timeout.Token);
}
throw new TimeoutException($"Notification {notificationId} did not reach {status}.");
}
}
@@ -0,0 +1,97 @@
using System.Net;
using System.Net.Http.Json;
using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Common;
using Helpdesk.Application.Notifications;
using Helpdesk.Application.Proposals;
using Helpdesk.Application.Statistics;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class ProposalWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
private const string Proposals = "/api/v1/proposals";
[Fact]
public async Task VotesAndDecisionsAreReflectedInTheProposalAndItsHistory()
{
using var anonymous = fixture.CreateClient();
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
var authorUser = await fixture.RegisterAsync(anonymous);
using var author = fixture.CreateClient((await LoginAsync(anonymous, authorUser.Email)).AccessToken);
var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
using var manager = fixture.CreateClient(managerSession.AccessToken);
var categories = await ReadAsync<CategoryDto[]>(author.GetAsync("/api/v1/proposal-categories", Cancellation));
var request = new SaveProposalRequest("Prodloužení studovny", "Rozšířit večerní otevírací dobu.", categories[0].Id);
await ExpectAsync(author.PostAsJsonAsync(Proposals, request with { Title = " " }, Cancellation), HttpStatusCode.BadRequest);
await ExpectAsync(author.PostAsJsonAsync(Proposals, request with { CategoryId = int.MaxValue }, Cancellation), HttpStatusCode.BadRequest);
var proposal = await ReadAsync<ProposalDetail>(author.PostAsJsonAsync(Proposals, request, Cancellation), HttpStatusCode.Created);
Assert.Equal("SUBMITTED", proposal.Status);
var path = $"{Proposals}/{proposal.Id}";
var edit = request with { CategoryId = categories[1].Id, Description = "Otevřít do 22 hodin." };
await ExpectAsync(manager.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.Forbidden);
proposal = await ReadAsync<ProposalDetail>(author.PutAsJsonAsync(path, edit, Cancellation));
Assert.Equal((edit.CategoryId, edit.Description, "UPDATED"), (proposal.CategoryId, proposal.Description, proposal.Events[^1].EventType));
var other = await ReadAsync<ProposalDetail>(author.PostAsJsonAsync(Proposals, edit with
{
Title = "Vybavení studovny",
}, Cancellation), HttpStatusCode.Created);
await VerifyVotesAsync(author, manager, path);
var from = Uri.EscapeDataString(proposal.CreatedAt.AddMinutes(-1).ToString("O"));
var to = Uri.EscapeDataString(other.CreatedAt.AddMinutes(1).ToString("O"));
var filter = $"{Proposals}?status=SUBMITTED&categoryId={edit.CategoryId}&authorId={authorUser.Id}&q=studovny&from={from}&to={to}";
var first = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter + "&sort=score&pageSize=1", Cancellation));
var second = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter + "&sort=score&pageSize=1&page=2", Cancellation));
Assert.Equal(2, first.TotalCount);
Assert.Equal(proposal.Id, Assert.Single(first.Items).Id);
Assert.Equal(other.Id, Assert.Single(second.Items).Id);
var newest = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter, Cancellation));
Assert.Equal(other.Id, newest.Items[0].Id);
var outside = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync($"{Proposals}?from={to}", Cancellation));
Assert.Empty(outside.Items);
await ExpectAsync(author.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("ACCEPTED", null), Cancellation),
HttpStatusCode.Forbidden);
await ExpectAsync(manager.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("REJECTED", " "), Cancellation),
HttpStatusCode.BadRequest);
await ExpectAsync(manager.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("IMPLEMENTED", null), Cancellation),
HttpStatusCode.Conflict);
var review = await ReadAsync<ProposalDetail>(manager.PostAsJsonAsync(path + "/status",
new ChangeProposalStatusRequest("UNDER_REVIEW", null), Cancellation));
Assert.Equal("UNDER_REVIEW", review.Status);
var accepted = await ReadAsync<ProposalDetail>(manager.PostAsJsonAsync(path + "/status",
new ChangeProposalStatusRequest("ACCEPTED", " Schváleno. "), Cancellation));
Assert.Equal(("ACCEPTED", "Schváleno."), (accepted.Status, accepted.Events[^1].Note));
await ExpectAsync(author.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.Conflict);
await ExpectAsync(manager.DeleteAsync(path + "/vote", Cancellation), HttpStatusCode.Conflict);
var inbox = await ReadAsync<PagedResult<NotificationDto>>(author.GetAsync("/api/v1/notifications", Cancellation));
Assert.Equal(2, inbox.Items.Count(item => item.ProposalId == proposal.Id && item.Type == "PROPOSAL_STATUS_CHANGED"));
var top = Assert.Single(await ReadAsync<TopProposal[]>(
manager.GetAsync($"/api/v1/statistics/proposals/top?limit=1&from={from}&to={to}", Cancellation)));
Assert.Equal((proposal.Id, 1L), (top.Id, top.Score));
}
private static async Task VerifyVotesAsync(HttpClient author, HttpClient voter, string path)
{
var vote = path + "/vote";
await ExpectAsync(author.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.Forbidden);
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(0), Cancellation), HttpStatusCode.BadRequest);
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.NoContent);
var detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
Assert.Equal((1L, 0L, 1L, (int?)1), (detail.VotesFor, detail.VotesAgainst, detail.Score, detail.MyVote));
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(-1), Cancellation), HttpStatusCode.NoContent);
detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
Assert.Equal((0L, 1L, -1L, (int?)-1), (detail.VotesFor, detail.VotesAgainst, detail.Score, detail.MyVote));
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(-1), Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(voter.DeleteAsync(vote, Cancellation), HttpStatusCode.NoContent);
detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
Assert.Equal(0L, detail.Score);
Assert.Null(detail.MyVote);
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.NoContent);
}
}
@@ -0,0 +1,41 @@
using System.Net;
using Microsoft.AspNetCore.TestHost;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class ProxyRateLimitTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
[Fact]
public async Task TrustedProxiesShareTheLimitForEachClientAndSeparateDifferentClients()
{
const string externalProxy = "192.0.2.10";
const string web = "192.0.2.11";
const string firstClient = "198.51.100.10";
const string secondClient = "198.51.100.11";
await using var api = fixture.CreateApiBehindProxies(externalProxy, web);
for (var attempt = 0; attempt < 20; attempt++)
Assert.Equal(401, await LoginAsync(api.Server, web, firstClient));
Assert.Equal(429, await LoginAsync(api.Server, externalProxy, firstClient));
Assert.Equal(401, await LoginAsync(api.Server, web, secondClient));
Assert.Equal(429, await LoginAsync(api.Server, $"::ffff:{firstClient}", secondClient));
}
private static async Task<int> LoginAsync(TestServer server, string peer, string client)
{
using var body = new MemoryStream("""{"email":"absent@example.test","password":"test-password"}"""u8.ToArray());
var response = await server.SendAsync(context =>
{
context.Connection.RemoteIpAddress = IPAddress.Parse(peer);
context.Request.Method = "POST";
context.Request.Path = "/api/v1/auth/login";
context.Request.ContentType = "application/json";
context.Request.ContentLength = body.Length;
context.Request.Body = body;
context.Request.Headers["X-Forwarded-For"] = client;
}, Cancellation);
return response.Response.StatusCode;
}
}
@@ -0,0 +1,40 @@
using Helpdesk.Domain.Auth;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace Helpdesk.IntegrationTests;
internal sealed class TokenSaveGate : SaveChangesInterceptor
{
private Pause? next;
internal Pause PauseNextSave()
{
var pause = new Pause();
if (Interlocked.CompareExchange(ref next, pause, null) is not null)
throw new InvalidOperationException("A save is already scheduled to pause.");
return pause;
}
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
if (Volatile.Read(ref next) is not null &&
eventData.Context!.ChangeTracker.Entries<AuthToken>()
.Any(entry => entry.State == EntityState.Added && entry.Entity.TokenType == TokenType.Refresh) &&
Interlocked.Exchange(ref next, null) is { } pause)
{
pause.Entered.TrySetResult();
await pause.Released.Task.WaitAsync(cancellationToken);
}
return result;
}
internal sealed class Pause
{
internal TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal TaskCompletionSource Released { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal void Release() => Released.TrySetResult();
}
}
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<CodeCoverage>
<EnableStaticManagedInstrumentation>True</EnableStaticManagedInstrumentation>
<EnableDynamicManagedInstrumentation>False</EnableDynamicManagedInstrumentation>
<CollectFromChildProcesses>True</CollectFromChildProcesses>
<ModulePaths>
<Include>
<ModulePath>(^|[\\/])Helpdesk\.(Api|Application|Domain|Infrastructure|Migrator)\.dll$</ModulePath>
</Include>
</ModulePaths>
<Sources>
<Exclude>
<Source>[\\/]obj[\\/]</Source>
</Exclude>
</Sources>
</CodeCoverage>
</Configuration>
+18 -5
View File
@@ -1,6 +1,6 @@
# Vývojové spuštění: docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build # Vývojové spuštění: docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
# Reverse proxy ukončuje HTTPS a připojuje se k webu a API přes HTTP # Reverse proxy ukončuje HTTPS a připojuje se k webu a API přes HTTP
# (/ → web, /api/* a /swagger → api). # (/ včetně /swagger → web, /api/* → api).
name: helpdesk name: helpdesk
@@ -53,6 +53,7 @@ services:
Smtp__Password: ${SMTP_PASSWORD:-} Smtp__Password: ${SMTP_PASSWORD:-}
Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-} Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-}
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-} ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
ReverseProxy__TrustedWebIp: ${WEB_API_WEB_IP:-172.30.242.6}
ADMIN_EMAIL: ${ADMIN_EMAIL:-} ADMIN_EMAIL: ${ADMIN_EMAIL:-}
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
volumes: volumes:
@@ -62,7 +63,11 @@ services:
condition: service_completed_successfully condition: service_completed_successfully
ports: ports:
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${API_HTTP_PORT:-8080}:8080" - "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${API_HTTP_PORT:-8080}:8080"
networks: [frontend, backend] networks:
frontend:
backend:
web-api:
aliases: [api-web]
web: web:
build: build:
@@ -70,8 +75,7 @@ services:
dockerfile: web/Dockerfile dockerfile: web/Dockerfile
environment: environment:
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Development} ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Development}
# Web volá API uvnitř Docker sítě; do databáze přístup nemá (je jen v síti frontend). Api__BaseUrl: http://api-web:8080/
Api__BaseUrl: http://api:8080/
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-} ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
volumes: volumes:
# Klíče pro šifrování cookie – bez nich by restart kontejneru odhlásil všechny uživatele. # Klíče pro šifrování cookie – bez nich by restart kontejneru odhlásil všechny uživatele.
@@ -80,12 +84,21 @@ services:
- api - api
ports: ports:
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${WEB_HTTP_PORT:-8081}:8080" - "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${WEB_HTTP_PORT:-8081}:8080"
networks: [frontend] networks:
frontend:
web-api:
ipv4_address: ${WEB_API_WEB_IP:-172.30.242.6}
networks: networks:
frontend: frontend:
backend: backend:
internal: true internal: true
web-api:
# Při kolizi s existující sítí lze společně přepsat WEB_API_SUBNET a WEB_API_WEB_IP.
internal: true
ipam:
config:
- subnet: ${WEB_API_SUBNET:-172.30.242.0/29}
volumes: volumes:
db-data: db-data:
+12 -12
View File
@@ -153,7 +153,7 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
| NFR-01 | Bezpečnost | Komunikace výhradně přes HTTPS; hesla hashovaná; JWT s krátkou platností; citlivé údaje šifrované (kap. 10). | | NFR-01 | Bezpečnost | Komunikace výhradně přes HTTPS; hesla hashovaná; JWT s krátkou platností; citlivé údaje šifrované (kap. 10). |
| NFR-02 | Konzistence | Pravidla životního cyklu a oprávnění jsou pouze na serveru; klienti je jen zobrazují. | | NFR-02 | Konzistence | Pravidla životního cyklu a oprávnění jsou pouze na serveru; klienti je jen zobrazují. |
| NFR-03 | Souběžnost | Změny stavu závady chráněny optimistickým zamykáním (`row_version`) – dvě souběžné změny nevedou k nekonzistentnímu stavu. | | NFR-03 | Souběžnost | Změny stavu závady chráněny optimistickým zamykáním (`row_version`) – dvě souběžné změny nevedou k nekonzistentnímu stavu. |
| NFR-04 | Dokumentace API | Swagger UI (OpenAPI) dostupné na `/swagger`, včetně autorizace tokenem. | | NFR-04 | Dokumentace API | Swagger UI na `/swagger` pro administrátory přihlášené na webu. Volání API ze Swaggeru se autorizují access tokenem. |
| NFR-05 | Výkon | Seznamy stránkované (výchozí 20 záznamů), indexy pro všechny filtry v přehledu. | | NFR-05 | Výkon | Seznamy stránkované (výchozí 20 záznamů), indexy pro všechny filtry v přehledu. |
| NFR-06 | Použitelnost | Responzivní web (desktop i mobil), mobilní aplikace Android 8.0+ (API 26). Rozhraní v češtině. | | NFR-06 | Použitelnost | Responzivní web (desktop i mobil), mobilní aplikace Android 8.0+ (API 26). Rozhraní v češtině. |
| NFR-07 | Nasaditelnost | Celý systém spustitelný příkazem `docker compose up`. | | NFR-07 | Nasaditelnost | Celý systém spustitelný příkazem `docker compose up`. |
@@ -249,7 +249,7 @@ stateDiagram-v2
|---|---|---|---|---|---| |---|---|---|---|---|---|
| T1 | — → **Přijata** | každý přihlášený (stává se hlásičem) | název, popis, kategorie | událost `CREATED` | vedení: `ISSUE_CREATED` | | T1 | — → **Přijata** | každý přihlášený (stává se hlásičem) | název, popis, kategorie | událost `CREATED` | vedení: `ISSUE_CREATED` |
| T2 | Přijata → **Přiřazena** | vedení | řešitel (role správce budov / vedení) | `assignee_id`, událost `ASSIGNED` | řešitel: `ISSUE_ASSIGNED`; hlásič: změna stavu | | T2 | Přijata → **Přiřazena** | vedení | řešitel (role správce budov / vedení) | `assignee_id`, událost `ASSIGNED` | řešitel: `ISSUE_ASSIGNED`; hlásič: změna stavu |
| T3 | Přiřazena / V řešení → **Přiřazena** (přeřazení) | vedení | nový řešitel | změna `assignee_id`, událost `ASSIGNED` | nový řešitel: `ISSUE_ASSIGNED` | | T3 | Přiřazena / V řešení → **Přiřazena** (přeřazení) | vedení | nový řešitel | změna `assignee_id`, událost `ASSIGNED` | `ISSUE_ASSIGNED` novému řešiteli, `ISSUE_STATUS_CHANGED` hlásiči při změně stavu, pokud hlásič není novým řešitelem |
| T4 | Přiřazena → **V řešení** | přiřazený řešitel | — | událost `STATUS_CHANGED` | hlásič | | T4 | Přiřazena → **V řešení** | přiřazený řešitel | — | událost `STATUS_CHANGED` | hlásič |
| T5 | V řešení → **Čeká na ověření** | přiřazený řešitel | volitelná poznámka | událost `STATUS_CHANGED` | hlásič | | T5 | V řešení → **Čeká na ověření** | přiřazený řešitel | volitelná poznámka | událost `STATUS_CHANGED` | hlásič |
| T6 | Čeká na ověření → **Vyřešena** | hlásič | — | událost `STATUS_CHANGED` (= čas uzavření) | řešitel | | T6 | Čeká na ověření → **Vyřešena** | hlásič | — | událost `STATUS_CHANGED` (= čas uzavření) | řešitel |
@@ -407,8 +407,8 @@ flowchart TB
subgraph Docker["Docker Compose"] subgraph Docker["Docker Compose"]
PROXY[Reverzní proxy nginx<br/>HTTPS / TLS] PROXY[Reverzní proxy nginx<br/>HTTPS / TLS]
WEB[Webová aplikace<br/>ASP.NET Core MVC] WEB[Webová aplikace<br/>ASP.NET Core MVC<br/>+ Swagger UI]
API[Backend REST API<br/>ASP.NET Core Web API<br/>+ Swagger] API[Backend REST API<br/>ASP.NET Core Web API<br/>+ OpenAPI]
DB[(MariaDB 11)] DB[(MariaDB 11)]
FILES[[Volume: přílohy]] FILES[[Volume: přílohy]]
end end
@@ -419,7 +419,7 @@ flowchart TB
BROWSER -- HTTPS --> PROXY BROWSER -- HTTPS --> PROXY
MOB -- "HTTPS, JWT" --> PROXY MOB -- "HTTPS, JWT" --> PROXY
PROXY --> WEB PROXY --> WEB
PROXY -- "/api/*, /swagger" --> API PROXY -- "/api/*" --> API
WEB -- "REST, JWT" --> API WEB -- "REST, JWT" --> API
API --> DB API --> DB
API --> FILES API --> FILES
@@ -615,7 +615,7 @@ SET revoked_at = UTC_TIMESTAMP(6), revoke_reason = 'USED'
WHERE jti = ? AND token_type = 'REFRESH' AND revoked_at IS NULL; WHERE jti = ? AND token_type = 'REFRESH' AND revoked_at IS NULL;
``` ```
- **Změněn 1 řádek** → token se používá poprvé, server vydá nový pár tokenů. - **Změněn 1 řádek** → token se používá poprvé, server uloží nový pár tokenů ve stejné databázové transakci.
- **Změněno 0 řádků** → token už byl použitý nebo zneplatněný. U refresh tokenu to znamená, že ho zneužil někdo jiný. Server zneplatní všechny tokeny uživatele (`REUSE_DETECTED`) a vrátí 401. - **Změněno 0 řádků** → token už byl použitý nebo zneplatněný. U refresh tokenu to znamená, že ho zneužil někdo jiný. Server zneplatní všechny tokeny uživatele (`REUSE_DETECTED`) a vrátí 401.
Ze dvou současných požadavků se stejným tokenem vždy uspěje jen jeden. Klienti (mobil i web) proto musí obnovu tokenů provádět vždy jen jednou současně. Jinak by souběžné obnovy vyhodnotil server jako krádež. Ze dvou současných požadavků se stejným tokenem vždy uspěje jen jeden. Klienti (mobil i web) proto musí obnovu tokenů provádět vždy jen jednou současně. Jinak by souběžné obnovy vyhodnotil server jako krádež.
@@ -647,7 +647,7 @@ Aplikační API má základní cestu **`/api/v1`**. Připojte tento prefix před
Číslo v URL je hlavní verze API. Zpětně kompatibilní rozšíření patří do stávající verze. Při nekompatibilní změně vznikne nová cesta (např. `/api/v2`) a samostatný OpenAPI dokument. Během přechodu klientů poběží obě verze souběžně. Před ukončením podpory starší verze se oznámí termín a zdokumentuje přechod. Číslo v URL je hlavní verze API. Zpětně kompatibilní rozšíření patří do stávající verze. Při nekompatibilní změně vznikne nová cesta (např. `/api/v2`) a samostatný OpenAPI dokument. Během přechodu klientů poběží obě verze souběžně. Před ukončením podpory starší verze se oznámí termín a zdokumentuje přechod.
Swagger UI je na `/swagger` a OpenAPI dokument pro v1 na `/swagger/v1/swagger.json`. Provozní kontrola API je na `GET /health`. Swagger UI je na webu na `/swagger`. UI i jeho OpenAPI dokument na `/swagger/v1/swagger.json` vyžadují administrátorskou relaci. Web načítá dokument z `GET /api/v1/admin/openapi/v1.json` s access tokenem administrátora. Provozní kontrola API je na `GET /health`.
### Autentizace a účet ### Autentizace a účet
| Metoda | Endpoint | Role | Popis | | Metoda | Endpoint | Role | Popis |
@@ -1129,7 +1129,7 @@ flowchart LR
BROWSER -- "HTTPS 443" --> PROXY BROWSER -- "HTTPS 443" --> PROXY
MOBILE -- "HTTPS 443 /api/v1/*" --> PROXY MOBILE -- "HTTPS 443 /api/v1/*" --> PROXY
PROXY -- "HTTP 8080 /" --> WEB PROXY -- "HTTP 8080 /" --> WEB
PROXY -- "HTTP 8080 /api/*, /swagger" --> API PROXY -- "HTTP 8080 /api/*" --> API
WEB -- "HTTP 8080 REST + JWT" --> API WEB -- "HTTP 8080 REST + JWT" --> API
API -- "TCP 3306" --> DB API -- "TCP 3306" --> DB
MIG -- "TCP 3306" --> DB MIG -- "TCP 3306" --> DB
@@ -1157,8 +1157,8 @@ flowchart LR
|---|---|---|---|---| |---|---|---|---|---|
| prohlížeč | proxy | HTTPS 443 (HTTP 80 → přesměrování) | internet | webová aplikace | | prohlížeč | proxy | HTTPS 443 (HTTP 80 → přesměrování) | internet | webová aplikace |
| mobil | proxy | HTTPS 443 | internet | REST API | | mobil | proxy | HTTPS 443 | internet | REST API |
| proxy | web | HTTP 8080 | frontend | stránky (`/`) | | proxy | web | HTTP 8080 | frontend | stránky (`/`), administrátorské Swagger UI (`/swagger`) |
| proxy | api | HTTP 8080 | frontend | `/api/*`, `/swagger` | | proxy | api | HTTP 8080 | frontend | `/api/*` |
| web | api | HTTP 8080 (`http://api:8080/api/v1/`) | frontend | volání API s JWT přihlášeného uživatele | | web | api | HTTP 8080 (`http://api:8080/api/v1/`) | frontend | volání API s JWT přihlášeného uživatele |
| api | db | TCP 3306 | backend | data – DB účet `helpdesk_app` | | api | db | TCP 3306 | backend | data – DB účet `helpdesk_app` |
| migrator | db | TCP 3306 | backend | migrace – DB účet `helpdesk_migrator` | | migrator | db | TCP 3306 | backend | migrace – DB účet `helpdesk_migrator` |
@@ -1171,8 +1171,8 @@ flowchart LR
| Služba | Image | Sítě | Porty | Úložiště | Poznámka | | Služba | Image | Sítě | Porty | Úložiště | Poznámka |
|---|---|---|---|---|---| |---|---|---|---|---|---|
| `proxy` | `nginx` | frontend | **80, 443 publikované** | certifikáty | TLS (vývoj: `mkcert`, produkce: Let's Encrypt), HSTS, limit velikosti požadavku 51 MiB (5 příloh × 10 MiB a režie multipart) | | `proxy` | `nginx` | frontend | **80, 443 publikované** | certifikáty | TLS (vývoj: `mkcert`, produkce: Let's Encrypt), HSTS, limit velikosti požadavku 51 MiB (5 příloh × 10 MiB a režie multipart) |
| `web` | vlastní (`dotnet/aspnet`) | frontend | interně 8080 | `web-keys` | klíče ASP.NET Core Data Protection pro šifrované cookie (bez persistence by restart odhlásil všechny uživatele) | | `web` | vlastní (`dotnet/aspnet`) | frontend | interně 8080 | `web-keys` | administrátorské Swagger UI na `/swagger`, klíče Data Protection pro šifrované cookie |
| `api` | vlastní (`dotnet/aspnet`) | frontend, backend | interně 8080 | `uploads` | Swagger na `/swagger`, `GET /health`, vytvoření admin účtu z env | | `api` | vlastní (`dotnet/aspnet`) | frontend, backend | interně 8080 | `uploads` | OpenAPI pro administrátory, `GET /health`, vytvoření admin účtu z env |
| `migrator` | vlastní (`dotnet/runtime`) | backend | — | — | aplikuje nové migrace z `db/migrations` a skončí | | `migrator` | vlastní (`dotnet/runtime`) | backend | — | — | aplikuje nové migrace z `db/migrations` a skončí |
| `db` | `mariadb:11.4` | backend | interně 3306 | `db-data` | při prvním startu vytvoří DB účty skriptem z `deploy/db-init/` | | `db` | `mariadb:11.4` | backend | interně 3306 | `db-data` | při prvním startu vytvoří DB účty skriptem z `deploy/db-init/` |
| `mailpit` | `axllent/mailpit` | frontend | 8025 (jen vývoj) | — | zachytává e-maily, v produkci se nespouští | | `mailpit` | `axllent/mailpit` | frontend | 8025 (jen vývoj) | — | zachytává e-maily, v produkci se nespouští |
+3 -1
View File
@@ -3,7 +3,9 @@
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally> <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<!-- Webová aplikace vystačí se sdíleným frameworkem ASP.NET Core; balíčky jsou jen pro testy. --> <PackageVersion Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.3.1" />
<!-- Testy -->
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" /> <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageVersion Include="xunit.v3" Version="4.0.2" /> <PackageVersion Include="xunit.v3" Version="4.0.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" /> <PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
@@ -0,0 +1,33 @@
using System.Net;
using Helpdesk.Web.Api;
using Microsoft.AspNetCore.Http;
namespace Helpdesk.Web.Tests;
public sealed class ForwardedClientIpHandlerTests
{
[Fact]
public async Task UsesTheCurrentConnectionAddressInsteadOfTheIncomingHeader()
{
const string header = "X-Forwarded-For";
var context = new DefaultHttpContext();
context.Connection.RemoteIpAddress = IPAddress.Parse("198.51.100.10");
context.Request.Headers[header] = "203.0.113.11";
var accessor = new HttpContextAccessor { HttpContext = context };
using var client = new HttpMessageInvoker(new ForwardedClientIpHandler(accessor) { InnerHandler = new Responder() });
using var request = new HttpRequestMessage(HttpMethod.Post, "http://api-web:8080/api/v1/auth/login");
using var response = await client.SendAsync(request, TestContext.Current.CancellationToken);
Assert.Equal("198.51.100.10", Assert.Single(request.Headers.GetValues(header)));
accessor.HttpContext = null;
using var next = new HttpRequestMessage(HttpMethod.Post, request.RequestUri);
using var nextResponse = await client.SendAsync(next, TestContext.Current.CancellationToken);
Assert.False(next.Headers.Contains(header));
}
private sealed class Responder : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
}
}
@@ -11,6 +11,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
<PackageReference Include="Microsoft.NET.Test.Sdk" /> <PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" /> <PackageReference Include="xunit.v3" />
<PackageReference Include="xunit.runner.visualstudio" /> <PackageReference Include="xunit.runner.visualstudio" />
@@ -0,0 +1,89 @@
using System.Net;
using System.Text;
using Helpdesk.Web.Api;
using Helpdesk.Web.Auth;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Helpdesk.Web.Tests;
public sealed class SwaggerAccessTests
{
[Fact]
public async Task SwaggerAndItsAssetsRequireAnAdministratorSession()
{
await using var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient))
.ConfigurePrimaryHttpMessageHandler(() => new OpenApiBackend())));
using var client = application.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
BaseAddress = new Uri("https://localhost"),
});
var ct = TestContext.Current.CancellationToken;
string[] paths = ["/swagger", "/swagger/index.html", "/swagger/index.js", "/swagger/swagger-ui.css", "/swagger/v1/swagger.json"];
foreach (var path in paths)
{
using var response = await client.GetAsync(path, ct);
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("/login", response.Headers.Location?.AbsolutePath);
}
SignIn(application.Services, client, UserRoles.Student);
foreach (var path in paths)
{
using var response = await client.GetAsync(path, ct);
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("/error/403", response.Headers.Location?.AbsolutePath);
}
SignIn(application.Services, client, UserRoles.Admin);
using var entry = await client.GetAsync("/swagger", ct);
Assert.Equal(HttpStatusCode.MovedPermanently, entry.StatusCode);
using var index = await client.GetAsync("/swagger/index.html", ct);
Assert.Equal(HttpStatusCode.OK, index.StatusCode);
Assert.Contains("Helpdesk API", await index.Content.ReadAsStringAsync(ct));
Assert.True(index.Headers.CacheControl?.NoStore == true);
using var script = await client.GetAsync("/swagger/index.js", ct);
Assert.Equal(HttpStatusCode.OK, script.StatusCode);
Assert.Contains("v1/swagger.json", await script.Content.ReadAsStringAsync(ct));
using var css = await client.GetAsync("/swagger/swagger-ui.css", ct);
Assert.Equal(HttpStatusCode.OK, css.StatusCode);
using var document = await client.GetAsync("/swagger/v1/swagger.json", ct);
Assert.Equal(HttpStatusCode.OK, document.StatusCode);
Assert.Contains("\"openapi\"", await document.Content.ReadAsStringAsync(ct));
Assert.True(document.Headers.CacheControl?.NoStore == true);
}
private static void SignIn(IServiceProvider services, HttpClient client, string role)
{
var scheme = CookieAuthenticationDefaults.AuthenticationScheme;
var options = services.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get(scheme);
var now = DateTimeOffset.UtcNow;
var properties = new AuthenticationProperties { IssuedUtc = now, ExpiresUtc = now.AddHours(1) };
AuthCookie.StoreTokens(properties, new TokenSet("test-access", now.AddMinutes(15), "test-refresh", now.AddDays(1)));
var user = new UserDto(1, "[email protected]", "Test", "User", null, role, true);
var ticket = new AuthenticationTicket(AuthCookie.CreatePrincipal(user), properties, scheme);
client.DefaultRequestHeaders.Remove("Cookie");
client.DefaultRequestHeaders.Add("Cookie", $"{AuthCookie.Name}={options.TicketDataFormat.Protect(ticket)}");
}
private sealed class OpenApiBackend : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Assert.Equal("/api/v1/admin/openapi/v1.json", request.RequestUri?.AbsolutePath);
Assert.Equal("Bearer", request.Headers.Authorization?.Scheme);
Assert.Equal("test-access", request.Headers.Authorization?.Parameter);
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("""{"openapi":"3.0.4"}""", Encoding.UTF8, "application/json"),
});
}
}
}
@@ -0,0 +1,15 @@
using Microsoft.AspNetCore.HttpOverrides;
namespace Helpdesk.Web.Api;
internal sealed class ForwardedClientIpHandler(IHttpContextAccessor accessor) : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var header = ForwardedHeadersDefaults.XForwardedForHeaderName;
request.Headers.Remove(header);
if (accessor.HttpContext?.Connection.RemoteIpAddress is { } address)
request.Headers.Add(header, address.ToString());
return base.SendAsync(request, cancellationToken);
}
}
@@ -5,6 +5,13 @@ namespace Helpdesk.Web.Api;
/// <summary>Endpointy API pro přihlášeného uživatele; access token přidává <see cref="BearerTokenHandler"/>.</summary> /// <summary>Endpointy API pro přihlášeného uživatele; access token přidává <see cref="BearerTokenHandler"/>.</summary>
public sealed class HelpdeskApiClient(HttpClient http) public sealed class HelpdeskApiClient(HttpClient http)
{ {
public async Task<string> GetOpenApiAsync(CancellationToken ct)
{
using var response = await http.GetAsync("api/v1/admin/openapi/v1.json", ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
return await response.Content.ReadAsStringAsync(ct);
}
public async Task<UserDto> GetMeAsync(CancellationToken ct) public async Task<UserDto> GetMeAsync(CancellationToken ct)
{ {
using var response = await http.GetAsync("api/v1/users/me", ct); using var response = await http.GetAsync("api/v1/users/me", ct);
@@ -0,0 +1,15 @@
using Helpdesk.Web.Api;
using Helpdesk.Web.Auth;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Helpdesk.Web.Controllers;
[Authorize(Roles = UserRoles.Admin)]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class SwaggerController(HelpdeskApiClient api) : Controller
{
[HttpGet("/swagger/v1/swagger.json")]
public async Task<IActionResult> Document(CancellationToken ct) =>
Content(await api.GetOpenApiAsync(ct), "application/json");
}
+1
View File
@@ -2,6 +2,7 @@
<ItemGroup> <ItemGroup>
<InternalsVisibleTo Include="Helpdesk.Web.Tests" /> <InternalsVisibleTo Include="Helpdesk.Web.Tests" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+13 -2
View File
@@ -37,8 +37,12 @@ static void ConfigureApiClient(IServiceProvider services, HttpClient http)
builder.Services.AddHttpContextAccessor(); builder.Services.AddHttpContextAccessor();
builder.Services.AddTransient<BearerTokenHandler>(); builder.Services.AddTransient<BearerTokenHandler>();
builder.Services.AddHttpClient<AuthApiClient>(ConfigureApiClient); builder.Services.AddTransient<ForwardedClientIpHandler>();
builder.Services.AddHttpClient<HelpdeskApiClient>(ConfigureApiClient).AddHttpMessageHandler<BearerTokenHandler>(); builder.Services.AddHttpClient<AuthApiClient>(ConfigureApiClient)
.AddHttpMessageHandler<ForwardedClientIpHandler>();
builder.Services.AddHttpClient<HelpdeskApiClient>(ConfigureApiClient)
.AddHttpMessageHandler<ForwardedClientIpHandler>()
.AddHttpMessageHandler<BearerTokenHandler>();
// Přihlášení: tokeny API v šifrované HttpOnly cookie, obnova access tokenu při ověření cookie. // Přihlášení: tokeny API v šifrované HttpOnly cookie, obnova access tokenu při ověření cookie.
builder.Services.AddSingleton(TimeProvider.System); builder.Services.AddSingleton(TimeProvider.System);
@@ -111,6 +115,13 @@ app.UseRouting();
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.MapSwaggerUI("swagger", options =>
{
options.SwaggerEndpoint("v1/swagger.json", "Helpdesk API v1");
options.DocumentTitle = "Helpdesk API";
options.CacheLifetime = null;
}).RequireAuthorization(policy => policy.RequireRole(UserRoles.Admin));
app.MapStaticAssets(); app.MapStaticAssets();
app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}").WithStaticAssets(); app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}").WithStaticAssets();
@@ -9,6 +9,10 @@
<ul class="dropdown-menu dropdown-menu-end"> <ul class="dropdown-menu dropdown-menu-end">
<li><span class="dropdown-item-text small text-body-secondary">@User.FindFirst(ClaimTypes.Email)?.Value</span></li> <li><span class="dropdown-item-text small text-body-secondary">@User.FindFirst(ClaimTypes.Email)?.Value</span></li>
<li><a class="dropdown-item" asp-controller="Profile" asp-action="Index">Můj profil</a></li> <li><a class="dropdown-item" asp-controller="Profile" asp-action="Index">Můj profil</a></li>
@if (User.IsInRole(UserRoles.Admin))
{
<li><a class="dropdown-item" href="~/swagger">Swagger API</a></li>
}
<li><hr class="dropdown-divider" /></li> <li><hr class="dropdown-divider" /></li>
<li> <li>
<form method="post" asp-controller="Account" asp-action="Logout"> <form method="post" asp-controller="Account" asp-action="Logout">