diff --git a/README.md b/README.md index ffd9884..93470e2 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ Potřeba je jen Docker Desktop. docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build ``` -3. Webová aplikace: · Swagger UI: · stav a verze schématu: +3. Webová aplikace: · Swagger UI po přihlášení administrátora: · stav a verze schématu: 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. -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. @@ -64,6 +64,22 @@ Testy webové aplikace: 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 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`. diff --git a/backend/Directory.Packages.props b/backend/Directory.Packages.props index f0f39c6..9bbaa65 100644 --- a/backend/Directory.Packages.props +++ b/backend/Directory.Packages.props @@ -15,14 +15,17 @@ - + + + + diff --git a/backend/Helpdesk.sln b/backend/Helpdesk.sln index 61e2772..21919ef 100644 --- a/backend/Helpdesk.sln +++ b/backend/Helpdesk.sln @@ -15,6 +15,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Migrator", "src\He EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.UnitTests", "tests\Helpdesk.UnitTests\Helpdesk.UnitTests.csproj", "{AB40F473-EB15-47C7-B179-A8EB066325EC}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.IntegrationTests", "tests\Helpdesk.IntegrationTests\Helpdesk.IntegrationTests.csproj", "{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution 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|x86.ActiveCfg = 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 GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/backend/src/Helpdesk.Api/Controllers/ProposalsController.cs b/backend/src/Helpdesk.Api/Controllers/ProposalsController.cs index 77a36ed..8b7b01a 100644 --- a/backend/src/Helpdesk.Api/Controllers/ProposalsController.cs +++ b/backend/src/Helpdesk.Api/Controllers/ProposalsController.cs @@ -62,7 +62,7 @@ public sealed class ProposalsController(ProposalService proposals) : ControllerB } [HttpPost("{id:int}/status")] - [Authorize(Roles = Roles.Management)] + [Authorize(Roles = Roles.ManagementOrAdmin)] [RequestSizeLimit(1024 * 1024)] public Task ChangeStatus(int id, ChangeProposalStatusRequest request, CancellationToken ct) => proposals.ChangeStatusAsync(id, request, ct); diff --git a/backend/src/Helpdesk.Api/Controllers/StatisticsController.cs b/backend/src/Helpdesk.Api/Controllers/StatisticsController.cs index c1df983..8eb2915 100644 --- a/backend/src/Helpdesk.Api/Controllers/StatisticsController.cs +++ b/backend/src/Helpdesk.Api/Controllers/StatisticsController.cs @@ -6,9 +6,9 @@ using Microsoft.AspNetCore.Mvc; namespace Helpdesk.Api.Controllers; -/// Statistiky pro vedení školy. Období v UTC zahrnuje začátek a vylučuje konec. +/// Statistiky pro vedení školy a administrátory. Období v UTC zahrnuje začátek a vylučuje konec. [ApiController] -[Authorize(Roles = Roles.Management)] +[Authorize(Roles = Roles.ManagementOrAdmin)] [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] [Route(ApiRoutes.V1 + "/statistics")] [ProducesResponseType(StatusCodes.Status400BadRequest)] diff --git a/backend/src/Helpdesk.Api/Controllers/UsersController.cs b/backend/src/Helpdesk.Api/Controllers/UsersController.cs index f41d2ad..b0dadb3 100644 --- a/backend/src/Helpdesk.Api/Controllers/UsersController.cs +++ b/backend/src/Helpdesk.Api/Controllers/UsersController.cs @@ -26,7 +26,7 @@ public sealed class UsersController(UserService users, ICurrentUser currentUser, /// Aktivní řešitelé s počtem otevřených závad. [HttpGet("assignable")] - [Authorize(Roles = Roles.Management)] + [Authorize(Roles = Roles.ManagementOrAdmin)] [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] [ProducesResponseType(StatusCodes.Status403Forbidden)] public Task> GetAssignable(CancellationToken ct) => issues.GetAssignableAsync(ct); diff --git a/backend/src/Helpdesk.Api/Helpdesk.Api.csproj b/backend/src/Helpdesk.Api/Helpdesk.Api.csproj index e6d126a..5f9e403 100644 --- a/backend/src/Helpdesk.Api/Helpdesk.Api.csproj +++ b/backend/src/Helpdesk.Api/Helpdesk.Api.csproj @@ -13,7 +13,7 @@ - + diff --git a/backend/src/Helpdesk.Api/Infrastructure/Roles.cs b/backend/src/Helpdesk.Api/Infrastructure/Roles.cs index 788c1b9..b6d5280 100644 --- a/backend/src/Helpdesk.Api/Infrastructure/Roles.cs +++ b/backend/src/Helpdesk.Api/Infrastructure/Roles.cs @@ -8,4 +8,5 @@ public static class Roles public const string FacilityManager = "FACILITY_MANAGER"; public const string Management = "MANAGEMENT"; public const string Admin = "ADMIN"; + public const string ManagementOrAdmin = Management + "," + Admin; } diff --git a/backend/src/Helpdesk.Api/Infrastructure/SwaggerSetup.cs b/backend/src/Helpdesk.Api/Infrastructure/SwaggerSetup.cs index 56c8bcb..f8991d3 100644 --- a/backend/src/Helpdesk.Api/Infrastructure/SwaggerSetup.cs +++ b/backend/src/Helpdesk.Api/Infrastructure/SwaggerSetup.cs @@ -9,7 +9,7 @@ public static class SwaggerSetup { private const string SchemeId = "Bearer"; - /// Swagger UI na /swagger včetně přihlášení access tokenem (NFR-04). + /// Generování OpenAPI dokumentu pro administrátorské Swagger UI (NFR-04). public static IServiceCollection AddHelpdeskSwagger(this IServiceCollection services) { services.AddEndpointsApiExplorer(); diff --git a/backend/src/Helpdesk.Api/Program.cs b/backend/src/Helpdesk.Api/Program.cs index ef09b00..96ebe63 100644 --- a/backend/src/Helpdesk.Api/Program.cs +++ b/backend/src/Helpdesk.Api/Program.cs @@ -30,18 +30,21 @@ builder.Services.AddProblemDetails(); builder.Services.AddExceptionHandler(); builder.Services.AddHelpdeskSwagger(); -var trustedProxy = builder.Configuration["ReverseProxy:TrustedIp"]; -if (!string.IsNullOrWhiteSpace(trustedProxy)) -{ - if (!IPAddress.TryParse(trustedProxy, out var proxyAddress)) - throw new InvalidOperationException("Nastavte platnou IP adresu důvěryhodné reverse proxy."); +var trustedProxies = new[] { "ReverseProxy:TrustedIp", "ReverseProxy:TrustedWebIp" } + .Where(key => !string.IsNullOrWhiteSpace(builder.Configuration[key])) + .Select(key => IPAddress.TryParse(builder.Configuration[key], out var address) ? address + : throw new InvalidOperationException($"Nastavte platnou IP adresu v {key}.")) + .ToArray(); +if (trustedProxies.Length > 0) +{ builder.Services.Configure(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; options.KnownIPNetworks.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 => { options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; - options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter( - http.Connection.RemoteIpAddress?.ToString() ?? "unknown", - _ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) })); + options.AddPolicy(RateLimitPolicies.Auth, http => + { + 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( http.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown", _ => new SlidingWindowRateLimiterOptions @@ -64,23 +72,18 @@ builder.Services.AddRateLimiter(options => var app = builder.Build(); -if (!string.IsNullOrWhiteSpace(trustedProxy)) +if (trustedProxies.Length > 0) app.UseForwardedHeaders(); app.UseExceptionHandler(); app.UseStatusCodePages(); -app.UseSwagger(); -app.UseSwaggerUI(options => -{ - options.SwaggerEndpoint("/swagger/v1/swagger.json", "Helpdesk API v1"); - options.DocumentTitle = "Helpdesk API"; -}); - app.UseAuthentication(); app.UseAuthorization(); app.UseRateLimiter(); +app.MapSwagger(ApiRoutes.V1 + "/admin/openapi/{documentName}.json") + .RequireAuthorization(policy => policy.RequireRole(Roles.Admin)); app.MapControllers(); app.Run(); diff --git a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs index aa3f044..a6d364e 100644 --- a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs +++ b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs @@ -30,7 +30,7 @@ public interface IAppDbContext DbSet PushDevices { get; } Task SaveChangesAsync(CancellationToken cancellationToken = default); - Task BeginProposalWriteAsync(CancellationToken ct); + Task BeginWriteAsync(CancellationToken ct); Task LockProposalAsync(int id, CancellationToken ct); Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct); } diff --git a/backend/src/Helpdesk.Application/Auth/AuthService.cs b/backend/src/Helpdesk.Application/Auth/AuthService.cs index 86c31fb..35c8233 100644 --- a/backend/src/Helpdesk.Application/Auth/AuthService.cs +++ b/backend/src/Helpdesk.Application/Auth/AuthService.cs @@ -95,17 +95,23 @@ public sealed class AuthService( var token = await tokens.ValidateAsync(request.RefreshToken, TokenType.Refresh) ?? 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); - throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu."); + if (await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct)) + { + 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); - if (user is null || !user.IsActive) - throw new UnauthorizedException("Účet neexistuje nebo je deaktivován."); - - return await IssueTokenPairAsync(user, ct); + await revocation.RevokeAllAsync(token.UserId, RevokeReason.ReuseDetected, ct); + throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu."); } /// Odhlášení jednoho zařízení – zneplatní aktuální access token a k němu předaný refresh token. diff --git a/backend/src/Helpdesk.Application/Issues/IssueService.Reads.cs b/backend/src/Helpdesk.Application/Issues/IssueService.Reads.cs index 45b07ce..4b2d04a 100644 --- a/backend/src/Helpdesk.Application/Issues/IssueService.Reads.cs +++ b/backend/src/Helpdesk.Application/Issues/IssueService.Reads.cs @@ -80,10 +80,11 @@ public sealed partial class IssueService public async Task> GetAssignableAsync(CancellationToken ct) { var actor = await GetActorAsync(ct); - if (actor.Role != UserRole.Management) - throw new ForbiddenException("Přehled řešitelů je určen vedení."); + if (!Issue.CanAssign(actor.Role)) + throw new ForbiddenException("Přehled řešitelů je určen vedení a administrátorům."); - var users = await db.Users.Where(u => u.IsActive && (u.Role == UserRole.Management || u.Role == UserRole.FacilityManager)) + var users = await db.Users.Where(u => u.IsActive && + (u.Role == UserRole.Management || u.Role == UserRole.FacilityManager || u.Role == UserRole.Admin)) .OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id) .Select(u => new { diff --git a/backend/src/Helpdesk.Application/Issues/IssueService.cs b/backend/src/Helpdesk.Application/Issues/IssueService.cs index 8752382..e698694 100644 --- a/backend/src/Helpdesk.Application/Issues/IssueService.cs +++ b/backend/src/Helpdesk.Application/Issues/IssueService.cs @@ -44,7 +44,7 @@ public sealed partial class IssueService( CheckVersion(issue, request.RowVersion); var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct); if (assignee is null || !Issue.CanBeAssigned(assignee.Role)) - throw new BadRequestException("Vyberte aktivního správce budov nebo člena vedení."); + throw new BadRequestException("Vyberte aktivního správce budov, člena vedení nebo administrátora."); if (issue.AssigneeId == assignee.Id) throw new ConflictException("Závada je již přiřazena tomuto řešiteli."); @@ -53,7 +53,7 @@ public sealed partial class IssueService( issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority); 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); - 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 SaveAsync(ct); diff --git a/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs b/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs index 1f14be6..3c9394d 100644 --- a/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs +++ b/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs @@ -15,7 +15,8 @@ public sealed class NotificationWriter(IAppDbContext db, TimeProvider clock) { var reporterId = issue.ReporterId; var eligibleUsers = db.Users.Where(u => - u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management); + u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management || + u.Role == UserRole.Admin); return QueueAsync(eligibleUsers, actorId, recipientIds, id => new Notification(issue, id, type, title, issue.Title), ct); } diff --git a/backend/src/Helpdesk.Application/Proposals/ProposalService.cs b/backend/src/Helpdesk.Application/Proposals/ProposalService.cs index 233ee95..038daad 100644 --- a/backend/src/Helpdesk.Application/Proposals/ProposalService.cs +++ b/backend/src/Helpdesk.Application/Proposals/ProposalService.cs @@ -28,20 +28,20 @@ public sealed partial class ProposalService( public async Task EditAsync(int id, SaveProposalRequest request, CancellationToken ct) { - await GetActorRoleAsync(ct); + var role = await GetActorRoleAsync(ct); 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); - if (!proposal.IsAuthor(currentUser.Id)) - throw new ForbiddenException("Návrh může upravit jen jeho autor."); + if (!proposal.CanEditAs(currentUser.Id, role)) + throw new ForbiddenException("Návrh může upravit jeho autor nebo administrátor."); if (!proposal.IsEditable) throw new ConflictException("Návrh lze upravit jen ve stavu Podán."); if (proposal.CategoryId != request.CategoryId) await RequireActiveCategoryAsync(request.CategoryId, ct); - proposal.Edit(currentUser.Id, title, description, request.CategoryId); + proposal.Edit(currentUser.Id, role, title, description, request.CategoryId); AddEvent(proposal, ProposalEventType.Updated); await db.SaveChangesAsync(ct); await transaction.CommitAsync(ct); @@ -53,8 +53,8 @@ public sealed partial class ProposalService( public async Task ChangeStatusAsync(int id, ChangeProposalStatusRequest request, CancellationToken ct) { var role = await GetActorRoleAsync(ct); - if (role != UserRole.Management) - throw new ForbiddenException("Stav návrhu může změnit jen vedení školy."); + if (!Proposal.CanReview(role)) + throw new ForbiddenException("Stav návrhu může změnit vedení školy nebo administrátor."); var target = ParseStatus(request.Status); var note = string.IsNullOrWhiteSpace(request.Note) ? null : request.Note.Trim(); @@ -63,7 +63,7 @@ public sealed partial class ProposalService( if (note is not null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes) 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 previous = proposal.Status; @@ -94,7 +94,7 @@ public sealed partial class ProposalService( { await GetActorRoleAsync(ct); 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); if (proposal.IsAuthor(actorId)) throw new ForbiddenException("Autor nemůže hlasovat o vlastním návrhu."); diff --git a/backend/src/Helpdesk.Domain/Issues/Issue.cs b/backend/src/Helpdesk.Domain/Issues/Issue.cs index a201330..474bd8a 100644 --- a/backend/src/Helpdesk.Domain/Issues/Issue.cs +++ b/backend/src/Helpdesk.Domain/Issues/Issue.cs @@ -31,9 +31,11 @@ public sealed class Issue : IHasCreatedAt public int RowVersion { get; private set; } public DateTime CreatedAt { get; set; } - public static bool CanReadAll(UserRole role) => role is UserRole.FacilityManager or UserRole.Management; + public static bool CanReadAll(UserRole role) => role == UserRole.FacilityManager || CanAssign(role); - public static bool CanBeAssigned(UserRole role) => role is UserRole.FacilityManager or UserRole.Management; + public static bool CanAssign(UserRole role) => role is UserRole.Management or UserRole.Admin; + + public static bool CanBeAssigned(UserRole role) => role is UserRole.FacilityManager or UserRole.Management or UserRole.Admin; public bool CanRead(int userId, UserRole role) => CanReadAll(role) || ReporterId == userId; @@ -42,14 +44,15 @@ public sealed class Issue : IHasCreatedAt var reporter = ReporterId == actorId; var assignee = AssigneeId == actorId && CanBeAssigned(role); var management = role == UserRole.Management; + var admin = role == UserRole.Admin; var authorized = action switch { - IssueAction.Edit or IssueAction.Confirm or IssueAction.Reopen => reporter, - IssueAction.Assign => management, - IssueAction.StartWork or IssueAction.SubmitForVerification => assignee, - IssueAction.Reject => assignee || (management && AssigneeId is null), - IssueAction.Comment or IssueAction.AddAttachments => reporter || assignee, + IssueAction.Edit or IssueAction.Confirm or IssueAction.Reopen => admin || reporter, + IssueAction.Assign => CanAssign(role), + IssueAction.StartWork or IssueAction.SubmitForVerification => admin || assignee, + IssueAction.Reject => admin || assignee || (management && AssigneeId is null), + IssueAction.Comment or IssueAction.AddAttachments => admin || reporter || assignee, _ => false, }; @@ -64,8 +67,8 @@ public sealed class Issue : IHasCreatedAt IssueAction.SubmitForVerification => Status == IssueStatus.InProgress, IssueAction.Confirm or IssueAction.Reopen => Status == IssueStatus.PendingVerification, IssueAction.Reject => Status == IssueStatus.Received - ? management - : assignee && Status is (IssueStatus.Assigned or IssueStatus.InProgress), + ? admin || management + : (admin || assignee) && Status is (IssueStatus.Assigned or IssueStatus.InProgress), IssueAction.Comment or IssueAction.AddAttachments => Status is not (IssueStatus.Resolved or IssueStatus.Rejected), _ => false, }; diff --git a/backend/src/Helpdesk.Domain/Proposals/Proposal.cs b/backend/src/Helpdesk.Domain/Proposals/Proposal.cs index 1c17a07..f07146a 100644 --- a/backend/src/Helpdesk.Domain/Proposals/Proposal.cs +++ b/backend/src/Helpdesk.Domain/Proposals/Proposal.cs @@ -26,9 +26,11 @@ public sealed class Proposal : IHasCreatedAt public bool IsAuthor(int userId) => AuthorId == userId; public bool IsEditable => Status == ProposalStatus.Submitted; public bool IsVotingOpen => Status is ProposalStatus.Submitted or ProposalStatus.UnderReview; - public bool CanEdit(int userId) => IsAuthor(userId) && IsEditable; + public bool CanEditAs(int userId, UserRole role) => role == UserRole.Admin || IsAuthor(userId); public bool CanVote(int userId) => !IsAuthor(userId) && IsVotingOpen; + public static bool CanReview(UserRole role) => role is UserRole.Management or UserRole.Admin; + public bool CanTransitionTo(ProposalStatus target) => Status switch { ProposalStatus.Submitted => target is ProposalStatus.UnderReview or ProposalStatus.Accepted or ProposalStatus.Rejected, @@ -37,9 +39,9 @@ public sealed class Proposal : IHasCreatedAt _ => false, }; - public void Edit(int actorId, string title, string description, int categoryId) + public void Edit(int actorId, UserRole role, string title, string description, int categoryId) { - if (!CanEdit(actorId)) + if (!CanEditAs(actorId, role) || !IsEditable) throw new InvalidOperationException("Návrh nelze upravit."); SetDetails(title, description, categoryId); @@ -47,7 +49,7 @@ public sealed class Proposal : IHasCreatedAt public void ChangeStatus(ProposalStatus target, UserRole role, string? note) { - if (role != UserRole.Management || !CanTransitionTo(target)) + if (!CanReview(role) || !CanTransitionTo(target)) throw new InvalidOperationException("Stav návrhu nelze změnit."); if (target == ProposalStatus.Rejected && string.IsNullOrWhiteSpace(note)) throw new ArgumentException("Zamítnutí vyžaduje vyjádření.", nameof(note)); diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs index 4edcdbd..aab3006 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs @@ -54,7 +54,7 @@ public sealed class HelpdeskDbContext(DbContextOptions option } } - public Task BeginProposalWriteAsync(CancellationToken ct) => + public Task BeginWriteAsync(CancellationToken ct) => Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct); public async Task LockProposalAsync(int id, CancellationToken ct) diff --git a/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs b/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs new file mode 100644 index 0000000..e47d05d --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs @@ -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 +{ + [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(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(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(member.GetAsync(route + "?includeInactive=true", Cancellation)); + var all = await ReadAsync(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(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(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(admin.GetAsync(route, Cancellation)); + var all = await ReadAsync(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(member.PutAsJsonAsync(profile, + request with { Phone = "invalid" }, Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("phone", validation.Errors.Keys); + var updated = await ReadAsync(member.PutAsJsonAsync(profile, request, Cancellation)); + Assert.Equal(updated, await ReadAsync(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(); + var encrypted = await db.Database.SqlQuery($"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>(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); + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/AttachmentTests.cs b/backend/tests/Helpdesk.IntegrationTests/AttachmentTests.cs new file mode 100644 index 0000000..c6358f6 --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/AttachmentTests.cs @@ -0,0 +1,96 @@ +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 +{ + [Fact] + public async Task AttachmentsRespectFormatAndAccessAndFailedBatchesAreNotSaved() + { + using var anonymous = fixture.CreateClient(); + using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken); + 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(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(); + var store = scope.ServiceProvider.GetRequiredService(); + try + { + var issue = await ReadAsync(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(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(admin.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(""u8); + using (var document = zip.CreateEntry("word/document.xml").Open()) + document.Write(""u8); + } + return stream.ToArray(); + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs b/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs new file mode 100644 index 0000000..4937a4f --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs @@ -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 +{ + [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(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(); + 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 first; + Task 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(); + 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(first); + await ExpectAsync(duplicate, HttpStatusCode.Unauthorized); + await using var after = fixture.Services.CreateAsyncScope(); + var tokens = after.ServiceProvider.GetRequiredService().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); + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs b/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs new file mode 100644 index 0000000..c664cc8 --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs @@ -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 = "admin@example.test"; + internal const string Password = "Integration-test-password"; + internal static string MigrationsPath => Path.Combine(AppContext.BaseDirectory, "migrations"); + internal static CancellationToken Cancellation => TestContext.Current.CancellationToken; + + private readonly MariaDbContainer database = new MariaDbBuilder("mariadb:11.4") + .WithDatabase("helpdesk") + .WithPassword(Convert.ToHexString(RandomNumberGenerator.GetBytes(24))) + .WithCommand("--character-set-server=utf8mb4") + .Build(); + private readonly TestEmailSender email = new(); + private ApiFactory? factory; + + internal TokenSaveGate TokenSaves { get; } = new(); + internal IServiceProvider Services => factory!.Services; + + public async ValueTask InitializeAsync() + { + await database.StartAsync(Cancellation); + await RunMigratorAsync(database.GetConnectionString()); + factory = new ApiFactory(database.GetConnectionString(), email, TokenSaves); + } + + public async ValueTask DisposeAsync() + { + try + { + if (factory is not null) + await factory.DisposeAsync(); + } + finally + { + await database.DisposeAsync(); + } + } + + internal HttpClient CreateClient(string? accessToken = null) + { + var client = factory!.CreateClient(); + if (accessToken is not null) + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); + return client; + } + + internal WebApplicationFactory CreateApiBehindProxies(string proxyIp, string webIp) => + new ApiFactory(database.GetConnectionString(), email, TokenSaves, proxyIp, webIp); + + internal async Task RegisterAsync(HttpClient client) + { + var address = $"{Guid.NewGuid():N}@student.example.test"; + var user = await ReadAsync(client.PostAsJsonAsync("/api/v1/auth/register", + new RegisterRequest(address, Password, "Test", "User"), Cancellation), HttpStatusCode.Created); + await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email", + new EmailTokenRequest(await email.TakeTokenAsync(address, "/confirm-email")), Cancellation), HttpStatusCode.NoContent); + return user; + } + + internal async Task RegisterStaffAsync(HttpClient anonymous, HttpClient admin, string role) + { + var user = await RegisterAsync(anonymous); + await ExpectAsync(admin.PutAsJsonAsync($"/api/v1/admin/users/{user.Id}/role", + new ChangeRoleRequest(role), Cancellation), HttpStatusCode.NoContent); + return await LoginAsync(anonymous, user.Email); + } + + internal Task TakeResetTokenAsync(string address) => email.TakeTokenAsync(address, "/reset-password"); + + internal void FailNextEmail(string address, string reason, bool retryable) => + email.Failures[address] = new EmailDeliveryException(reason, retryable); + + internal static Task LoginAsync(HttpClient client, string address) => + ReadAsync(client.PostAsJsonAsync("/api/v1/auth/login", + new LoginRequest(address, Password), Cancellation)); + + internal static async Task ReadAsync(Task request, HttpStatusCode expected = HttpStatusCode.OK) + where T : class + { + using var response = await request; + Assert.Equal(expected, response.StatusCode); + return Assert.IsType(await response.Content.ReadFromJsonAsync(Cancellation)); + } + + internal static async Task ExpectAsync(Task request, HttpStatusCode expected) + { + using var response = await request; + Assert.Equal(expected, response.StatusCode); + } + + private static async Task RunMigratorAsync(string connectionString) + { + var startInfo = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + startInfo.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "Helpdesk.Migrator.dll")); + startInfo.Environment["ConnectionStrings__Migrator"] = connectionString; + startInfo.Environment["MIGRATIONS_PATH"] = MigrationsPath; + using var process = Process.Start(startInfo) ?? throw new InvalidOperationException("Could not start the migrator."); + var output = process.StandardOutput.ReadToEndAsync(Cancellation); + var errors = process.StandardError.ReadToEndAsync(Cancellation); + try + { + await process.WaitForExitAsync(Cancellation); + Assert.True(process.ExitCode == 0, $"Migrator failed with exit code {process.ExitCode}.\n{await output}\n{await errors}"); + } + finally + { + if (!process.HasExited) + { + process.Kill(); + await process.WaitForExitAsync(); + } + } + } + + private sealed class ApiFactory(string connectionString, TestEmailSender email, TokenSaveGate tokenSaves, + string proxyIp = "", string webIp = "") + : WebApplicationFactory + { + private readonly Dictionary settings = new() + { + ["ConnectionStrings:Helpdesk"] = connectionString, + ["Jwt:SigningKey"] = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)), + ["Encryption:Key"] = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)), + ["Registration:StudentEmailDomains:0"] = "student.example.test", + ["Registration:WebBaseUrl"] = "https://helpdesk.example.test", + ["ADMIN_EMAIL"] = AdminEmail, + ["ADMIN_PASSWORD"] = Password, + ["Firebase:ServiceAccountJson"] = "", + ["Smtp:Mailbox"] = "", + ["Smtp:Password"] = "", + ["ReverseProxy:TrustedIp"] = 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(); + services.AddSingleton(email); + services.AddDbContext((_, options) => options.AddInterceptors(tokenSaves)); + }); + } + + private sealed class TestEmailSender : IEmailSender + { + private readonly ConcurrentDictionary<(string Address, string Path), TaskCompletionSource> tokens = new(); + internal ConcurrentDictionary Failures { get; } = new(); + + public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default) + { + if (Failures.TryRemove(to, out var failure)) + throw failure; + + if (Uri.TryCreate(body[(body.LastIndexOf('\n') + 1)..], UriKind.Absolute, out var link) && + link.AbsolutePath is "/confirm-email" or "/reset-password") + { + var token = QueryHelpers.ParseQuery(link.Query)["token"].ToString(); + GetTokenSlot((to, link.AbsolutePath)).TrySetResult(token); + } + return Task.CompletedTask; + } + + internal async Task TakeTokenAsync(string address, string path) + { + var key = (address, path); + var token = await GetTokenSlot(key).Task.WaitAsync(TimeSpan.FromSeconds(10), Cancellation); + tokens.TryRemove(key, out _); + return token; + } + + private TaskCompletionSource GetTokenSlot((string Address, string Path) key) => + tokens.GetOrAdd(key, _ => new(TaskCreationOptions.RunContinuationsAsynchronously)); + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs b/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs new file mode 100644 index 0000000..22acd29 --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs @@ -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 +{ + [Fact] + public async Task MigratorAppliesEveryScriptAndEfCanReadTheSchema() + { + using var client = fixture.CreateClient(); + await using var scope = fixture.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var expected = Directory.EnumerateFiles(MigrationsPath, "V*__*.sql") + .Select(Path.GetFileName).Order(StringComparer.Ordinal).ToArray(); + var applied = await db.Database + .SqlQueryRaw("SELECT scriptname AS Value FROM schema_version ORDER BY schemaversionid") + .ToListAsync(Cancellation); + Assert.Equal(expected, applied); + var health = await ReadAsync(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(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(); + 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(() => 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); + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj b/backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj new file mode 100644 index 0000000..e72dc5a --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj @@ -0,0 +1,24 @@ + + + + false + Exe + true + + + + + + + + + + + + + + + + + + diff --git a/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs b/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs new file mode 100644 index 0000000..fd79a14 --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs @@ -0,0 +1,161 @@ +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 +{ + [Fact] + public async Task ReporterAndAssigneesCanResolveAnIssueAndManagementCanReportOnIt() + { + using var anonymous = fixture.CreateClient(); + var administrator = await LoginAsync(anonymous, AdminEmail); + using var admin = fixture.CreateClient(administrator.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(reporter.GetAsync("/api/v1/issue-categories", Cancellation)); + var buildings = await ReadAsync(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(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); + issue = await ReadAsync(admin.PutAsJsonAsync(path, + new EditIssueRequest(issue.Title, issue.Description, issue.CategoryId, + issue.BuildingId, "A102", issue.RowVersion), Cancellation)); + Assert.Equal(("A102", author.Id), (issue.LocationDetail, issue.ReporterId)); + var assign = new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion); + await ExpectAsync(reporter.PostAsJsonAsync(path + "/assign", assign, Cancellation), HttpStatusCode.Forbidden); + issue = await PostIssueAsync(admin, path + "/assign", assign); + Assert.Equal(firstAssignee.User.Id, issue.AssigneeId); + Assert.Contains("ASSIGN", (await ReadAsync(admin.GetAsync(path, Cancellation))).AllowedActions); + var adminIssues = await ReadAsync>(admin.GetAsync("/api/v1/issues", Cancellation)); + Assert.Contains(adminIssues.Items, item => item.Id == issue.Id); + var assignable = await ReadAsync(admin.GetAsync("/api/v1/users/assignable", Cancellation)); + Assert.Contains(assignable, user => user.Id == firstAssignee.User.Id); + Assert.Contains(assignable, user => user.Id == administrator.User.Id); + 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(admin, path + "/start", new IssueVersionRequest(issue.RowVersion)); + Assert.Equal("IN_PROGRESS", issue.Status); + reporterNotifications = await InboxAsync(reporter, issue.Id); + issue = await PostIssueAsync(admin, 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(admin.PostAsJsonAsync(path + "/comments", + new CommentRequest(commentText), Cancellation)); + Assert.Equal(administrator.User.Id, comment.ActorId); + issue = await ReadAsync(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(admin, 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(admin, path + "/submit-for-verification", new VerifyIssueRequest(issue.RowVersion, "Ověřeno.")); + issue = await PostIssueAsync(admin, path + "/confirm", new IssueVersionRequest(issue.RowVersion)); + Assert.Equal("RESOLVED", issue.Status); + var events = await ReadAsync(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); + + var officeIssue = await PostIssueAsync(reporter, "/api/v1/issues", + request with { Title = "Porucha v kanceláři" }, HttpStatusCode.Created); + var officePath = $"/api/v1/issues/{officeIssue.Id}"; + officeIssue = await PostIssueAsync(manager, officePath + "/assign", + new AssignIssueRequest(administrator.User.Id, null, officeIssue.RowVersion)); + Assert.Equal(administrator.User.Id, officeIssue.AssigneeId); + Assert.Equal("ISSUE_ASSIGNED", Assert.Single(await InboxAsync(admin, officeIssue.Id)).Type); + var rejectedByAdmin = await PostIssueAsync(admin, officePath + "/reject", + new IssueReasonRequest(officeIssue.RowVersion, "Hlášení je duplicitní.")); + Assert.Equal("REJECTED", rejectedByAdmin.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>(manager.GetAsync(query + "&page=1", Cancellation)); + var second = await ReadAsync>(manager.GetAsync(query + "&page=2", Cancellation)); + var filtered = await ReadAsync>(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(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( + 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( + 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( + 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(manager.GetAsync("/api/v1/users/assignable", Cancellation)); + Assert.Contains(available, user => user.Id == resolved.AssigneeId && user.OpenIssues == 0); + var trend = await ReadAsync(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(manager.GetAsync(overview + $"?from={to}", Cancellation)); + Assert.Equal(0, after.TotalIssues); + } + + private static Task PostIssueAsync( + HttpClient client, string path, T request, HttpStatusCode expected = HttpStatusCode.OK) => + ReadAsync(client.PostAsJsonAsync(path, request, Cancellation), expected); + + private static async Task InboxAsync(HttpClient client, int issueId) + { + var notifications = await ReadAsync>(client.GetAsync("/api/v1/notifications", Cancellation)); + return notifications.Items.Where(notification => notification.IssueId == issueId).ToArray(); + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/NotificationTests.cs b/backend/tests/Helpdesk.IntegrationTests/NotificationTests.cs new file mode 100644 index 0000000..e671f5e --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/NotificationTests.cs @@ -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 +{ + [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(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(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created); + var notifications = await ReadAsync>(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(manager.GetAsync(inbox + "/unread-count", Cancellation))).Count); + + fixture.FailNextEmail(managerSession.User.Email, "TEST_TEMPORARY_FAILURE", retryable: true); + var secondIssue = await ReadAsync(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created); + notifications = await ReadAsync>(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>(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(); + 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 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>(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}."); + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/ProposalWorkflowTests.cs b/backend/tests/Helpdesk.IntegrationTests/ProposalWorkflowTests.cs new file mode 100644 index 0000000..7cf8a64 --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/ProposalWorkflowTests.cs @@ -0,0 +1,102 @@ +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 +{ + private const string Proposals = "/api/v1/proposals"; + + [Fact] + public async Task VotesAndDecisionsAreReflectedInTheProposalAndItsHistory() + { + using var anonymous = fixture.CreateClient(); + var administrator = await LoginAsync(anonymous, AdminEmail); + using var admin = fixture.CreateClient(administrator.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(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(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(author.PutAsJsonAsync(path, edit, Cancellation)); + Assert.Equal((edit.CategoryId, edit.Description, "UPDATED"), (proposal.CategoryId, proposal.Description, proposal.Events[^1].EventType)); + var adminEdit = edit with { Description = "Otevřít do 22 hodin ve všední dny." }; + proposal = await ReadAsync(admin.PutAsJsonAsync(path, adminEdit, Cancellation)); + Assert.Equal((adminEdit.Description, authorUser.Id, administrator.User.Id), + (proposal.Description, proposal.AuthorId, proposal.Events[^1].ActorId)); + var other = await ReadAsync(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>(manager.GetAsync(filter + "&sort=score&pageSize=1", Cancellation)); + var second = await ReadAsync>(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>(manager.GetAsync(filter, Cancellation)); + Assert.Equal(other.Id, newest.Items[0].Id); + var outside = await ReadAsync>(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(admin.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("IMPLEMENTED", null), Cancellation), + HttpStatusCode.Conflict); + var review = await ReadAsync(admin.PostAsJsonAsync(path + "/status", + new ChangeProposalStatusRequest("UNDER_REVIEW", null), Cancellation)); + Assert.Equal("UNDER_REVIEW", review.Status); + var accepted = await ReadAsync(manager.PostAsJsonAsync(path + "/status", + new ChangeProposalStatusRequest("ACCEPTED", " Schváleno. "), Cancellation)); + Assert.Equal(("ACCEPTED", "Schváleno."), (accepted.Status, accepted.Events[^1].Note)); + await ExpectAsync(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.Conflict); + await ExpectAsync(manager.DeleteAsync(path + "/vote", Cancellation), HttpStatusCode.Conflict); + + var inbox = await ReadAsync>(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( + admin.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(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(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(voter.GetAsync(path, Cancellation)); + Assert.Equal(0L, detail.Score); + Assert.Null(detail.MyVote); + await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.NoContent); + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/ProxyRateLimitTests.cs b/backend/tests/Helpdesk.IntegrationTests/ProxyRateLimitTests.cs new file mode 100644 index 0000000..84d5292 --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/ProxyRateLimitTests.cs @@ -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 +{ + [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 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; + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/TokenSaveGate.cs b/backend/tests/Helpdesk.IntegrationTests/TokenSaveGate.cs new file mode 100644 index 0000000..abed69c --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/TokenSaveGate.cs @@ -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> SavingChangesAsync( + DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) + { + if (Volatile.Read(ref next) is not null && + eventData.Context!.ChangeTracker.Entries() + .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(); + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/coverage.settings.xml b/backend/tests/Helpdesk.IntegrationTests/coverage.settings.xml new file mode 100644 index 0000000..3b8cf7d --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/coverage.settings.xml @@ -0,0 +1,18 @@ + + + + True + False + True + + + (^|[\\/])Helpdesk\.(Api|Application|Domain|Infrastructure|Migrator)\.dll$ + + + + + [\\/]obj[\\/] + + + + diff --git a/backend/tests/Helpdesk.UnitTests/IssueTests.cs b/backend/tests/Helpdesk.UnitTests/IssueTests.cs index d77c36a..c3137a6 100644 --- a/backend/tests/Helpdesk.UnitTests/IssueTests.cs +++ b/backend/tests/Helpdesk.UnitTests/IssueTests.cs @@ -21,15 +21,18 @@ public sealed class IssueTests } [Theory] - [InlineData(IssueStatus.Received)] - [InlineData(IssueStatus.Assigned)] - [InlineData(IssueStatus.InProgress)] - public void ManagementCanAssignOrReassign(IssueStatus from) + [InlineData(IssueStatus.Received, UserRole.Management)] + [InlineData(IssueStatus.Assigned, UserRole.Management)] + [InlineData(IssueStatus.InProgress, UserRole.Management)] + [InlineData(IssueStatus.Received, UserRole.Admin)] + [InlineData(IssueStatus.Assigned, UserRole.Admin)] + [InlineData(IssueStatus.InProgress, UserRole.Admin)] + public void ManagementAndAdminCanAssignOrReassign(IssueStatus from, UserRole role) { var issue = At(from); var version = issue.RowVersion; - Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Assign, Manager, UserRole.Management)); - issue.Assign(Manager, UserRole.Management, Replacement, UserRole.Management, IssuePriority.High); + Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Assign, Manager, role)); + issue.Assign(Manager, role, Replacement, UserRole.Management, IssuePriority.High); Assert.Equal(IssueStatus.Assigned, issue.Status); Assert.Equal(Replacement, issue.AssigneeId); Assert.Equal(IssuePriority.High, issue.Priority); @@ -38,12 +41,17 @@ public sealed class IssueTests [Theory] [InlineData(IssueStatus.Assigned, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueStatus.InProgress)] + [InlineData(IssueStatus.Assigned, IssueAction.StartWork, Replacement, UserRole.Admin, IssueStatus.InProgress)] [InlineData(IssueStatus.InProgress, IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, IssueStatus.PendingVerification)] + [InlineData(IssueStatus.InProgress, IssueAction.SubmitForVerification, Replacement, UserRole.Admin, IssueStatus.PendingVerification)] [InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Reporter, UserRole.Admin, IssueStatus.Resolved)] - [InlineData(IssueStatus.PendingVerification, IssueAction.Reopen, Reporter, UserRole.Admin, IssueStatus.InProgress)] + [InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Replacement, UserRole.Admin, IssueStatus.Resolved)] + [InlineData(IssueStatus.PendingVerification, IssueAction.Reopen, Replacement, UserRole.Admin, IssueStatus.InProgress)] [InlineData(IssueStatus.Assigned, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)] [InlineData(IssueStatus.InProgress, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)] [InlineData(IssueStatus.Received, IssueAction.Reject, Manager, UserRole.Management, IssueStatus.Rejected)] + [InlineData(IssueStatus.Received, IssueAction.Reject, Replacement, UserRole.Admin, IssueStatus.Rejected)] + [InlineData(IssueStatus.InProgress, IssueAction.Reject, Replacement, UserRole.Admin, IssueStatus.Rejected)] public void AllowedTransitionsIncrementVersion( IssueStatus from, IssueAction action, int actorId, UserRole role, IssueStatus target) { @@ -63,6 +71,7 @@ public sealed class IssueTests [InlineData(IssueStatus.InProgress, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)] [InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Assignee, UserRole.FacilityManager, IssueActionAvailability.Forbidden)] [InlineData(IssueStatus.PendingVerification, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)] + [InlineData(IssueStatus.PendingVerification, IssueAction.Reject, Replacement, UserRole.Admin, IssueActionAvailability.InvalidState)] [InlineData(IssueStatus.Resolved, IssueAction.Reopen, Reporter, UserRole.Admin, IssueActionAvailability.InvalidState)] [InlineData(IssueStatus.Rejected, IssueAction.Reject, Manager, UserRole.Management, IssueActionAvailability.InvalidState)] public void DisallowedTransitionsMatchAvailability( @@ -102,10 +111,12 @@ public sealed class IssueTests { var issue = At(IssueStatus.Assigned); Assert.True(issue.CanRead(Reporter, UserRole.Admin)); - Assert.False(issue.CanRead(Replacement, UserRole.Admin)); + Assert.True(issue.CanRead(Replacement, UserRole.Admin)); + Assert.False(issue.CanRead(Replacement, UserRole.Student)); Assert.True(issue.CanRead(Replacement, UserRole.FacilityManager)); Assert.Equal(IssueActionAvailability.Forbidden, issue.Availability(IssueAction.Comment, Manager, UserRole.Management)); Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Comment, Reporter, UserRole.Admin)); + Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.AddAttachments, Replacement, UserRole.Admin)); issue.RecordParticipation(IssueAction.Comment, Reporter, UserRole.Admin); issue.Transition(IssueAction.Reject, Assignee, UserRole.FacilityManager, "Důvod"); Assert.Equal(IssueActionAvailability.InvalidState, issue.Availability(IssueAction.AddAttachments, Reporter, UserRole.Admin)); diff --git a/backend/tests/Helpdesk.UnitTests/ProposalTests.cs b/backend/tests/Helpdesk.UnitTests/ProposalTests.cs index 7fa42f5..de74312 100644 --- a/backend/tests/Helpdesk.UnitTests/ProposalTests.cs +++ b/backend/tests/Helpdesk.UnitTests/ProposalTests.cs @@ -35,12 +35,14 @@ public sealed class ProposalTests } [Fact] - public void ReviewRequiresManagementAndRejectionRequiresNote() + public void ReviewRequiresManagementOrAdminAndRejectionRequiresNote() { var proposal = At(ProposalStatus.Submitted); - Assert.Throws(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Admin, null)); - Assert.Throws(() => proposal.ChangeStatus(ProposalStatus.Rejected, UserRole.Management, " ")); + Assert.Throws(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Student, null)); + Assert.Throws(() => proposal.ChangeStatus(ProposalStatus.Rejected, UserRole.Admin, " ")); Assert.Equal(ProposalStatus.Submitted, proposal.Status); + proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Admin, null); + Assert.Equal(ProposalStatus.Accepted, proposal.Status); } [Theory] @@ -49,22 +51,25 @@ public sealed class ProposalTests [InlineData(ProposalStatus.Accepted, false, false)] [InlineData(ProposalStatus.Rejected, false, false)] [InlineData(ProposalStatus.Implemented, false, false)] - public void AuthorEditsAndOtherUserVotesOnlyInEligibleStates(ProposalStatus state, bool mayEdit, bool mayVote) + public void AuthorAndAdminEditAndOtherUsersVoteOnlyInEligibleStates(ProposalStatus state, bool mayEdit, bool mayVote) { var proposal = At(state); - Assert.Equal(mayEdit, proposal.CanEdit(Author)); - Assert.False(proposal.CanEdit(Voter)); + Assert.Equal(mayEdit, proposal.IsEditable); Assert.False(proposal.CanVote(Author)); Assert.Equal(mayVote, proposal.CanVote(Voter)); - Assert.Throws(() => proposal.Edit(Voter, "Změna", "Popis", 1)); + Assert.Throws(() => proposal.Edit(Voter, UserRole.Student, "Změna", "Popis", 1)); if (mayEdit) { - proposal.Edit(Author, "Změna", "Popis", 1); + proposal.Edit(Author, UserRole.Student, "Změna", "Popis", 1); Assert.Equal("Změna", proposal.Title); + proposal.Edit(Voter, UserRole.Admin, "Další změna", "Popis", 1); + Assert.Equal("Další změna", proposal.Title); + Assert.Equal(Author, proposal.AuthorId); } else { - Assert.Throws(() => proposal.Edit(Author, "Změna", "Popis", 1)); + Assert.Throws(() => proposal.Edit(Author, UserRole.Student, "Změna", "Popis", 1)); + Assert.Throws(() => proposal.Edit(Voter, UserRole.Admin, "Změna", "Popis", 1)); } } diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 63a4376..d96815a 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -1,6 +1,6 @@ # 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 -# (/ → web, /api/* a /swagger → api). +# (/ včetně /swagger → web, /api/* → api). name: helpdesk @@ -53,6 +53,7 @@ services: Smtp__Password: ${SMTP_PASSWORD:-} Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-} ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-} + ReverseProxy__TrustedWebIp: ${WEB_API_WEB_IP:-172.30.242.6} ADMIN_EMAIL: ${ADMIN_EMAIL:-} ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} volumes: @@ -62,7 +63,11 @@ services: condition: service_completed_successfully ports: - "${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: build: @@ -70,8 +75,7 @@ services: dockerfile: web/Dockerfile environment: 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:8080/ + Api__BaseUrl: http://api-web:8080/ ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-} volumes: # Klíče pro šifrování cookie – bez nich by restart kontejneru odhlásil všechny uživatele. @@ -80,12 +84,21 @@ services: - api ports: - "${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: frontend: backend: 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: db-data: diff --git a/docs/navrh-aplikace.md b/docs/navrh-aplikace.md index 305b8c7..3f7ea34 100644 --- a/docs/navrh-aplikace.md +++ b/docs/navrh-aplikace.md @@ -72,7 +72,7 @@ Webová i mobilní aplikace jsou **tenké klienty** – nepřistupují do datab | `TEACHER` | Vyučující | Samoregistrace | Stejná oprávnění jako student | | `FACILITY_MANAGER` | Správce budov | Přiděluje administrátor | Řeší přiřazené závady (odpovědná osoba) | | `MANAGEMENT` | Vedení školy | Přiděluje administrátor | Přiřazuje závady řešitelům, hodnotí návrhy, vidí statistiky | -| `ADMIN` | Administrátor | Přiděluje administrátor / vytvořen při instalaci | Správa uživatelů a jejich rolí, správa číselníků | +| `ADMIN` | Administrátor | Přiděluje administrátor / vytvořen při instalaci | Správa systému, všechny akce nad závadami a návrhy, statistiky | - Každý uživatel má **právě jednu roli** (sloupec `app_user.role`). Základní funkce (hlásit závady, podávat návrhy, hlasovat) má každá role, takže kombinace rolí nejsou potřeba – např. vyučující, který je ve vedení, dostane roli `MANAGEMENT`. - Při samoregistraci se role `STUDENT` / `TEACHER` určí automaticky **podle domény e-mailu** (např. `@student.univerzita.cz` → student, `@univerzita.cz` → vyučující). Domény jsou v konfiguraci backendu. Registrace z jiné domény není povolena. Tím se zabrání tomu, aby se student zaregistroval jako vyučující. @@ -86,23 +86,26 @@ Legenda: ✅ povoleno, 🔸 povoleno s podmínkou, — nepovoleno |---|:-:|:-:|:-:|:-:| | Nahlásit závadu, přiložit soubory | ✅ | ✅ | ✅ | ✅ | | Zobrazit vlastní hlášení | ✅ | ✅ | ✅ | ✅ | -| Upravit vlastní hlášení | 🔸 jen ve stavu *Přijata* | 🔸 | 🔸 | 🔸 | -| Centrální přehled všech závad (filtry) | — | ✅ (jen čtení) | ✅ | — | -| Přiřadit / přeřadit závadu řešiteli, nastavit prioritu | — | — | ✅ | — | -| Zahájit řešení, předat k ověření | — | 🔸 jen přiřazené jemu | 🔸 jen přiřazené jemu | — | -| Zamítnout závadu (s důvodem) | — | 🔸 jen přiřazené jemu | 🔸 přiřazené jemu nebo nepřiřazené ve stavu *Přijata* | — | -| Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | -| Komentovat závadu | 🔸 hlásič | 🔸 hlásič nebo řešitel | 🔸 hlásič nebo řešitel; ostatní jen čtení | 🔸 hlásič | +| Upravit hlášení | 🔸 vlastní ve stavu *Přijata* | 🔸 vlastní ve stavu *Přijata* | 🔸 vlastní ve stavu *Přijata* | 🔸 libovolné ve stavu *Přijata* | +| Centrální přehled všech závad (filtry) | — | ✅ (jen čtení) | ✅ | ✅ | +| Přiřadit / přeřadit závadu řešiteli, nastavit prioritu | — | — | ✅ | ✅ | +| Zahájit řešení, předat k ověření | — | 🔸 jen přiřazené jemu | 🔸 jen přiřazené jemu | 🔸 ve stavu příslušného přechodu | +| Zamítnout závadu (s důvodem) | — | 🔸 jen přiřazené jemu | 🔸 přiřazené jemu nebo nepřiřazené ve stavu *Přijata* | 🔸 ve stavu příslušného přechodu | +| Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 ve stavu *Čeká na ověření* | +| Komentovat závadu / přidat přílohu | 🔸 hlásič | 🔸 hlásič nebo řešitel | 🔸 hlásič nebo řešitel; ostatní jen čtení | 🔸 libovolná otevřená závada | | Podat návrh na zlepšení | ✅ | ✅ | ✅ | ✅ | | Zobrazit všechny návrhy | ✅ | ✅ | ✅ | ✅ | | Hlasovat pro návrh | 🔸 ne pro vlastní | 🔸 | 🔸 | 🔸 | -| Hodnotit návrhy (změna stavu, vyjádření) | — | — | ✅ | — | -| Statistiky a výkazy | — | — | ✅ | — | +| Upravit návrh ve stavu *Podán* | 🔸 autor | 🔸 autor | 🔸 autor | ✅ | +| Hodnotit návrhy (změna stavu, vyjádření) | — | — | ✅ | ✅ | +| Statistiky a výkazy | — | — | ✅ | ✅ | | Správa uživatelů a rolí | — | — | — | ✅ | | Správa číselníků (budovy, kategorie) | — | — | — | ✅ | Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkrétním záznamem** (resource-based authorization) a kontroluje je aplikační vrstva backendu (viz kap. 9.3). +`ADMIN` může spravovat závady a návrhy ostatních uživatelů. Požadavky na stav záznamu, povinné údaje a `rowVersion` platí pro všechny role. Profil, přihlášení, hlasování, zařízení a osobní notifikace se vztahují k aktuálně přihlášenému účtu. + --- ## 3. Funkční požadavky @@ -122,7 +125,7 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr | FR-10 | Uživatel nahlásí závadu: název, popis, kategorie (typ), budova a upřesnění místa. | | FR-11 | K hlášení lze při vytvoření i později v průběhu komunikace přiložit fotografii nebo jiný soubor (JPG, PNG, HEIC, PDF, DOCX; max. 10 MB/soubor, max. 5 souborů najednou). | | FR-12 | Závada prochází stavy *Přijata → Přiřazena → V řešení → Čeká na ověření → Vyřešena*, případně *Zamítnuta* (kap. 6). Nepovolené přechody server odmítne. | -| FR-13 | Vedení přiřazuje závadu odpovědné osobě (správci budov); u každého správce vidí počet jeho otevřených závad. | +| FR-13 | Vedení a administrátor přiřazují závadu odpovědné osobě; u každého řešitele vidí počet jeho otevřených závad. | | FR-14 | Řešitel může závadu zamítnout s povinným uvedením důvodu. | | FR-15 | Hlásič potvrdí vyřešení, nebo závadu znovu otevře (s povinným důvodem) → stav *V řešení*. | | FR-16 | Hlásič a řešitel si u závady vyměňují komentáře; protistrana je o novém komentáři informována. | @@ -134,13 +137,13 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr | FR-20 | Každý uživatel podá návrh: název, popis, oblast (studium, služby, prostředí, ostatní). | | FR-21 | Uživatel hlasuje pro/proti návrhu jiného uživatele; jeden hlas na návrh, hlas lze změnit či zrušit; autor pro vlastní návrh hlasovat nemůže. | | FR-22 | Seznam návrhů lze řadit podle podpory (skóre) a data a filtrovat podle stavu a oblasti. | -| FR-23 | Vedení hodnotí návrhy – mění stav (*V posouzení, Přijat, Zamítnut, Realizován*) a připojuje vyjádření. | +| FR-23 | Vedení a administrátor hodnotí návrhy, mění jejich stav (*V posouzení, Přijat, Zamítnut, Realizován*) a připojují vyjádření. | ### Správa, přehledy, notifikace | ID | Požadavek | |---|---| | FR-30 | Centrální přehled závad a návrhů s filtrováním podle typu (kategorie), stavu, lokality (budovy), řešitele a data; stránkování a řazení. | -| FR-31 | Statistiky pro vedení: počet závad podle stavu / kategorie / budovy, průměrná doba do přiřazení a do uzavření, vytížení řešitelů, nejpodporovanější návrhy, vše za zvolené období. | +| FR-31 | Statistiky pro vedení a administrátory zahrnují počty závad podle stavu, kategorie či budovy, průměrnou dobu do přiřazení a uzavření, vytížení řešitelů a nejpodporovanější návrhy za zvolené období. | | FR-32 | Notifikace v aplikaci (seznam, počet nepřečtených), e-mailem a push notifikací v mobilní aplikaci (kap. 8). | | FR-33 | Nedoručené e-maily a push notifikace se automaticky opakují; trvale nedoručené vidí administrátor a může je odeslat znovu. | @@ -153,7 +156,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-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-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-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`. | @@ -198,7 +201,7 @@ flowchart LR S --- UC1 & UC2 & UC3 & UC4 & UC10 & UC11 F --- UC3 & UC6 & UC7 & UC20 M --- UC5 & UC7 & UC12 & UC20 & UC21 - A --- UC22 & UC23 + A --- UC5 & UC6 & UC7 & UC12 & UC20 & UC21 & UC22 & UC23 ``` *Správce budov, vedení i administrátor mají navíc všechny případy užití studenta (hlášení závad, návrhy, hlasování).* @@ -229,16 +232,16 @@ stateDiagram-v2 state "Zamítnuta" as REJECTED [*] --> RECEIVED : hlásič vytvoří - RECEIVED --> ASSIGNED : vedení přiřadí řešitele - ASSIGNED --> ASSIGNED : vedení přeřadí - ASSIGNED --> IN_PROGRESS : řešitel zahájí - IN_PROGRESS --> ASSIGNED : vedení přeřadí - IN_PROGRESS --> PENDING_VERIFICATION : řešitel předá k ověření - PENDING_VERIFICATION --> RESOLVED : hlásič potvrdí - PENDING_VERIFICATION --> IN_PROGRESS : hlásič znovu otevře - RECEIVED --> REJECTED : vedení zamítne - ASSIGNED --> REJECTED : řešitel zamítne - IN_PROGRESS --> REJECTED : řešitel zamítne + RECEIVED --> ASSIGNED : vedení nebo admin přiřadí řešitele + ASSIGNED --> ASSIGNED : vedení nebo admin přeřadí + ASSIGNED --> IN_PROGRESS : řešitel nebo admin zahájí + IN_PROGRESS --> ASSIGNED : vedení nebo admin přeřadí + IN_PROGRESS --> PENDING_VERIFICATION : řešitel nebo admin předá k ověření + PENDING_VERIFICATION --> RESOLVED : hlásič nebo admin potvrdí + PENDING_VERIFICATION --> IN_PROGRESS : hlásič nebo admin znovu otevře + RECEIVED --> REJECTED : vedení nebo admin zamítne + ASSIGNED --> REJECTED : řešitel nebo admin zamítne + IN_PROGRESS --> REJECTED : řešitel nebo admin zamítne RESOLVED --> [*] REJECTED --> [*] ``` @@ -248,14 +251,14 @@ stateDiagram-v2 | # | Z → Do | Kdo smí | Povinné údaje | Vedlejší efekty | Notifikace | |---|---|---|---|---|---| | 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 | -| 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` | -| 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č | -| T6 | Čeká na ověření → **Vyřešena** | hlásič | — | událost `STATUS_CHANGED` (= čas uzavření) | řešitel | -| T7 | Čeká na ověření → **V řešení** | hlásič | důvod znovuotevření | událost s důvodem v `note` | řešitel: `ISSUE_REOPENED` | -| T8 | Přiřazena / V řešení → **Zamítnuta** | přiřazený řešitel | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič | -| T9 | Přijata → **Zamítnuta** | vedení | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič | +| T2 | Přijata → **Přiřazena** | vedení / admin | řešitel (správce budov / vedení / admin) | `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í / admin | 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 / admin | — | událost `STATUS_CHANGED` | hlásič | +| T5 | V řešení → **Čeká na ověření** | přiřazený řešitel / admin | volitelná poznámka | událost `STATUS_CHANGED` | hlásič | +| T6 | Čeká na ověření → **Vyřešena** | hlásič / admin | — | událost `STATUS_CHANGED` (= čas uzavření) | řešitel | +| T7 | Čeká na ověření → **V řešení** | hlásič / admin | důvod znovuotevření | událost s důvodem v `note` | řešitel: `ISSUE_REOPENED` | +| T8 | Přiřazena / V řešení → **Zamítnuta** | přiřazený řešitel / admin | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič | +| T9 | Přijata → **Zamítnuta** | vedení / admin | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič | **Obecná pravidla** @@ -300,19 +303,19 @@ stateDiagram-v2 state "Realizován" as IMPLEMENTED [*] --> SUBMITTED : uživatel podá - SUBMITTED --> UNDER_REVIEW : vedení - SUBMITTED --> ACCEPTED : vedení - SUBMITTED --> REJECTED : vedení (s vyjádřením) - UNDER_REVIEW --> ACCEPTED : vedení - UNDER_REVIEW --> REJECTED : vedení (s vyjádřením) - ACCEPTED --> IMPLEMENTED : vedení + SUBMITTED --> UNDER_REVIEW : vedení nebo admin + SUBMITTED --> ACCEPTED : vedení nebo admin + SUBMITTED --> REJECTED : vedení nebo admin (s vyjádřením) + UNDER_REVIEW --> ACCEPTED : vedení nebo admin + UNDER_REVIEW --> REJECTED : vedení nebo admin (s vyjádřením) + ACCEPTED --> IMPLEMENTED : vedení nebo admin REJECTED --> [*] IMPLEMENTED --> [*] ``` -- Stavy mění pouze **vedení školy**; zamítnutí vyžaduje vyjádření, u ostatních je volitelné. Vyjádření se ukládá do `note` příslušné události. -- Autor může návrh upravit, dokud je ve stavu *Podán* (událost `UPDATED`). -- Každá změna se zapisuje do `proposal_event`, autor dostane notifikaci. +- Stavy může měnit vedení školy nebo administrátor. Zamítnutí vyžaduje vyjádření, u ostatních přechodů je volitelné. Vyjádření se ukládá do `note` příslušné události. +- Autor nebo administrátor může návrh upravit, dokud je ve stavu *Podán* (událost `UPDATED`). +- Každá změna se zapisuje do `proposal_event`. Při změně stavu dostane autor notifikaci, pokud stav nezměnil sám. ### 7.2 Pravidla hlasování @@ -407,8 +410,8 @@ flowchart TB subgraph Docker["Docker Compose"] PROXY[Reverzní proxy nginx
HTTPS / TLS] - WEB[Webová aplikace
ASP.NET Core MVC] - API[Backend REST API
ASP.NET Core Web API
+ Swagger] + WEB[Webová aplikace
ASP.NET Core MVC
+ Swagger UI] + API[Backend REST API
ASP.NET Core Web API
+ OpenAPI] DB[(MariaDB 11)] FILES[[Volume: přílohy]] end @@ -419,7 +422,7 @@ flowchart TB BROWSER -- HTTPS --> PROXY MOB -- "HTTPS, JWT" --> PROXY PROXY --> WEB - PROXY -- "/api/*, /swagger" --> API + PROXY -- "/api/*" --> API WEB -- "REST, JWT" --> API API --> DB API --> FILES @@ -444,8 +447,8 @@ Fyzické nasazení (sítě, porty, úložiště, tajné klíče) popisuje kapito ### 9.3 Autorizace -1. **Podle role** – atribut `[Authorize(Roles = "MANAGEMENT")]` / politiky (např. `CanAssignIssues`, `CanEvaluateProposals`, `IsAdmin`). Role je v JWT jako claim `role`. -2. **Nad konkrétním záznamem** – v aplikační vrstvě (`IssueAuthorizationService`): „je aktuální uživatel hlásičem / přiřazeným řešitelem této závady?“, „je autorem návrhu?“. Porušení → 403. +1. **Podle role** – atributy jako `[Authorize(Roles = Roles.ManagementOrAdmin)]` a autorizační politiky. Role je v JWT jako claim `role`. +2. **Nad konkrétním záznamem** – aplikační a doménová vrstva ověřují oprávnění k akci. U závad a úprav návrhů může administrátor jednat i u cizích záznamů. Porušení → 403. 3. **Podle stavu** – stavový automat v doméně. Porušení → 409. Detail závady vrací pole `allowedActions` (např. `["START_WORK", "REJECT", "COMMENT"]`), podle kterého klienti zobrazují ovládací prvky – logika tak není duplikována v klientech. @@ -615,7 +618,7 @@ SET revoked_at = UTC_TIMESTAMP(6), revoke_reason = 'USED' 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. 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 +650,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. -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 | Metoda | Endpoint | Role | Popis | @@ -665,21 +668,21 @@ Swagger UI je na `/swagger` a OpenAPI dokument pro v1 na `/swagger/v1/swagger.js ### Hlášení závad | Metoda | Endpoint | Role | Popis | |---|---|---|---| -| GET | `/issues` | přihlášený | Seznam; filtry `status`, `categoryId`, `buildingId`, `assigneeId`, `reporterId`, `from`, `to`, `q`, `mine`; řazení `sort=newest\|oldest`. Student, vyučující a administrátor vidí jen vlastní. | +| GET | `/issues` | přihlášený | Seznam; filtry `status`, `categoryId`, `buildingId`, `assigneeId`, `reporterId`, `from`, `to`, `q`, `mine`; řazení `sort=newest\|oldest`. Student a vyučující vidí jen vlastní. | | POST | `/issues` | přihlášený | Vytvoření hlášení (T1), JSON do 1 MiB nebo multipart s poli hlášení a soubory v poli `files` | -| GET | `/issues/{id}` | účastník / správce / vedení | Detail vč. `allowedActions` a `rowVersion` | -| PUT | `/issues/{id}` | hlásič | Úprava ve stavu Přijata s `rowVersion` | -| POST | `/issues/{id}/assign` | vedení | `{ assigneeId, priority?, rowVersion }` (T2, T3) | -| POST | `/issues/{id}/start` | řešitel | `{ rowVersion }` (T4) | -| POST | `/issues/{id}/submit-for-verification` | řešitel | `{ rowVersion, note? }` (T5) | -| POST | `/issues/{id}/confirm` | hlásič | `{ rowVersion }` (T6) | -| POST | `/issues/{id}/reopen` | hlásič | `{ rowVersion, reason }` (T7) | -| POST | `/issues/{id}/reject` | řešitel / vedení | `{ rowVersion, reason }` (T8, T9) | +| GET | `/issues/{id}` | účastník / správce / vedení / admin | Detail vč. `allowedActions` a `rowVersion` | +| PUT | `/issues/{id}` | hlásič / admin | Úprava ve stavu Přijata s `rowVersion` | +| POST | `/issues/{id}/assign` | vedení / admin | `{ assigneeId, priority?, rowVersion }` (T2, T3) | +| POST | `/issues/{id}/start` | řešitel / admin | `{ rowVersion }` (T4) | +| POST | `/issues/{id}/submit-for-verification` | řešitel / admin | `{ rowVersion, note? }` (T5) | +| POST | `/issues/{id}/confirm` | hlásič / admin | `{ rowVersion }` (T6) | +| POST | `/issues/{id}/reopen` | hlásič / admin | `{ rowVersion, reason }` (T7) | +| POST | `/issues/{id}/reject` | řešitel / vedení / admin | `{ rowVersion, reason }` (T8, T9) | | GET | `/issues/{id}/events` | jako detail | Časová osa – všechny události včetně komentářů (`issue_event`) | -| POST | `/issues/{id}/comments` | hlásič, řešitel | `{ text }` – zapíše událost `COMMENTED` | -| POST | `/issues/{id}/attachments` | hlásič, řešitel | `multipart/form-data`, 1–5 souborů v poli `files` | +| POST | `/issues/{id}/comments` | hlásič / řešitel / admin | `{ text }` – zapíše událost `COMMENTED` | +| POST | `/issues/{id}/attachments` | hlásič / řešitel / admin | `multipart/form-data`, 1–5 souborů v poli `files` | | GET | `/attachments/{id}` | jako detail závady | Stažení souboru | -| GET | `/users/assignable` | vedení | Možní řešitelé s počtem otevřených závad | +| GET | `/users/assignable` | vedení / admin | Možní řešitelé s počtem otevřených závad | Přechody stavů jsou záměrně **samostatné akční endpointy** místo obecného `PATCH status` – každý má vlastní vstupní data, oprávnění a je jednoznačně zdokumentovaný ve Swaggeru. Po přidání komentáře nebo příloh klient znovu načte detail, aby získal aktuální `rowVersion`. @@ -690,10 +693,10 @@ Po přidání komentáře nebo příloh klient znovu načte detail, aby získal | GET | `/proposals` | přihlášený | Filtry `status`, `categoryId`, `authorId`, `q`; `sort=score\|newest`; obsahuje skóre a můj hlas | | POST | `/proposals` | přihlášený | Podání návrhu | | GET | `/proposals/{id}` | přihlášený | Detail vč. událostí a vyjádření vedení | -| PUT | `/proposals/{id}` | autor | Úprava ve stavu Podán | +| PUT | `/proposals/{id}` | autor / admin | Úprava ve stavu Podán | | PUT | `/proposals/{id}/vote` | přihlášený (ne autor) | `{ value: 1 \| -1 }` – vytvoření nebo změna hlasu | | DELETE | `/proposals/{id}/vote` | přihlášený | Zrušení hlasu | -| POST | `/proposals/{id}/status` | vedení | `{ status, note? }` | +| POST | `/proposals/{id}/status` | vedení / admin | `{ status, note? }` | ### Notifikace a zařízení | Metoda | Endpoint | Role | Popis | @@ -708,12 +711,12 @@ Po přidání komentáře nebo příloh klient znovu načte detail, aby získal ### Statistiky | Metoda | Endpoint | Role | Popis | |---|---|---|---| -| GET | `/statistics/overview?from=&to=` | vedení | Souhrnné KPI: počty podle stavu, průměrná doba do přiřazení a do uzavření | -| GET | `/statistics/issues/by-category` | vedení | Počty a průměrná doba řešení podle kategorie | -| GET | `/statistics/issues/by-building` | vedení | Podle budovy | -| GET | `/statistics/issues/by-assignee` | vedení | Vytížení řešitelů (otevřené / uzavřené) | -| GET | `/statistics/issues/trend?granularity=month` | vedení | Nové vs. uzavřené závady v čase | -| GET | `/statistics/proposals/top?limit=10` | vedení | Nejpodporovanější návrhy | +| GET | `/statistics/overview?from=&to=` | vedení / admin | Souhrnné KPI: počty podle stavu, průměrná doba do přiřazení a do uzavření | +| GET | `/statistics/issues/by-category` | vedení / admin | Počty a průměrná doba řešení podle kategorie | +| GET | `/statistics/issues/by-building` | vedení / admin | Podle budovy | +| GET | `/statistics/issues/by-assignee` | vedení / admin | Vytížení řešitelů (otevřené / uzavřené) | +| GET | `/statistics/issues/trend?granularity=month` | vedení / admin | Nové vs. uzavřené závady v čase | +| GET | `/statistics/proposals/top?limit=10` | vedení / admin | Nejpodporovanější návrhy | ### Číselníky a administrace | Metoda | Endpoint | Role | Popis | @@ -976,7 +979,7 @@ V první verzi byla tabulka uživatelů „chobotnice“: vedlo na ni 17 cizích - **Normalizace (3NF)**: číselníky jsou v samostatných tabulkách. Časy životního cyklu se neukládají redundantně, ale odvozují se z událostí. - **Stavy jako text + CHECK** místo nativního `ENUM`: hodnoty jsou v DB čitelné, rozšíření je snadné a v EF Core se mapují na C# `enum` přes `HasConversion()`. - **Integritní omezení v DB** jako druhá linie obrany za aplikační logikou. Zamítnutí i znovuotevření musí mít důvod. Závada ve stavu *Přiřazena / V řešení / Čeká na ověření* musí mít řešitele. Událost `CREATED` musí začínat výchozím stavem, komentář (`COMMENTED`) musí mít text a nesmí měnit stav. Hlas je jen `+1`/`-1`, příloha má max. 10 MB a odeslané doručení musí mít `sent_at`. Notifikace typu `ISSUE_*` musí odkazovat na závadu, typu `PROPOSAL_*` na návrh. -- **Pravidla vyžadující více tabulek** (autor nehlasuje pro svůj návrh, řešitel musí mít roli správce budov / vedení) hlídá aplikační vrstva. V DB by vyžadovala triggery a logika by se rozdělila na dvě místa. +- **Pravidla vyžadující více tabulek** (autor nehlasuje pro svůj návrh, řešitel musí mít roli správce budov, vedení nebo administrátora) hlídá aplikační vrstva. V DB by vyžadovala triggery a logika by se rozdělila na dvě místa. - **Optimistické zamykání**: `issue.row_version` (EF Core concurrency token). - **Mazání**: uživatelé, závady, návrhy a číselníky se nemažou. Uživatelé a číselníky se deaktivují (`is_active`). `ON DELETE CASCADE` je jen u čistě závislých dat. - **Časy v UTC**, `DATETIME(6)`; převod do místního času dělá klient. @@ -1035,13 +1038,13 @@ ORDER BY n.created_at DESC; | Nástěnka (moje otevřená hlášení, poslední notifikace, top návrhy) | ✅ | ✅ | všichni | | Nové hlášení závady (formulář + přílohy / fotoaparát) | ✅ | ✅ | všichni | | Moje hlášení (seznam se stavem) | ✅ | ✅ | všichni | -| Detail závady (stav, časová osa, akce podle `allowedActions`, komentáře, přílohy) | ✅ | ✅ | účastníci, správce, vedení | +| Detail závady (stav, časová osa, akce podle `allowedActions`, komentáře, přílohy) | ✅ | ✅ | účastníci, správce, vedení, admin | | Přiřazené závady (pracovní fronta řešitele) | ✅ | ✅ | správce budov | -| Centrální přehled závad (tabulka, filtry, hromadný přehled) | ✅ | — | správce budov, vedení | +| Centrální přehled závad (tabulka, filtry, hromadný přehled) | ✅ | — | správce budov, vedení, admin | | Návrhy – seznam (řazení podle skóre, hlasování přímo v seznamu) | ✅ | ✅ | všichni | | Detail návrhu / nový návrh | ✅ | ✅ | všichni | -| Hodnocení návrhů (fronta podaných návrhů) | ✅ | — | vedení | -| Statistiky (KPI dlaždice, grafy, filtr období) | ✅ | — | vedení | +| Hodnocení návrhů (fronta podaných návrhů) | ✅ | — | vedení, admin | +| Statistiky (KPI dlaždice, grafy, filtr období) | ✅ | — | vedení, admin | | Notifikace | ✅ | ✅ | všichni | | Profil a nastavení notifikací | ✅ | ✅ | všichni | | Správa uživatelů a rolí | ✅ | — | admin | @@ -1129,7 +1132,7 @@ flowchart LR BROWSER -- "HTTPS 443" --> PROXY MOBILE -- "HTTPS 443 /api/v1/*" --> PROXY PROXY -- "HTTP 8080 /" --> WEB - PROXY -- "HTTP 8080 /api/*, /swagger" --> API + PROXY -- "HTTP 8080 /api/*" --> API WEB -- "HTTP 8080 REST + JWT" --> API API -- "TCP 3306" --> DB MIG -- "TCP 3306" --> DB @@ -1157,8 +1160,8 @@ flowchart LR |---|---|---|---|---| | prohlížeč | proxy | HTTPS 443 (HTTP 80 → přesměrování) | internet | webová aplikace | | mobil | proxy | HTTPS 443 | internet | REST API | -| proxy | web | HTTP 8080 | frontend | stránky (`/`) | -| proxy | api | HTTP 8080 | frontend | `/api/*`, `/swagger` | +| proxy | web | HTTP 8080 | frontend | stránky (`/`), administrátorské Swagger UI (`/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 | | api | db | TCP 3306 | backend | data – DB účet `helpdesk_app` | | migrator | db | TCP 3306 | backend | migrace – DB účet `helpdesk_migrator` | @@ -1171,8 +1174,8 @@ flowchart LR | 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) | -| `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) | -| `api` | vlastní (`dotnet/aspnet`) | frontend, backend | interně 8080 | `uploads` | Swagger na `/swagger`, `GET /health`, vytvoření admin účtu z env | +| `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` | 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čí | | `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í | diff --git a/web/Directory.Packages.props b/web/Directory.Packages.props index 7356f7a..6cbdbed 100644 --- a/web/Directory.Packages.props +++ b/web/Directory.Packages.props @@ -3,7 +3,9 @@ true - + + + diff --git a/web/Helpdesk.Web.Tests/ForwardedClientIpHandlerTests.cs b/web/Helpdesk.Web.Tests/ForwardedClientIpHandlerTests.cs new file mode 100644 index 0000000..5c382eb --- /dev/null +++ b/web/Helpdesk.Web.Tests/ForwardedClientIpHandlerTests.cs @@ -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 SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)); + } +} diff --git a/web/Helpdesk.Web.Tests/Helpdesk.Web.Tests.csproj b/web/Helpdesk.Web.Tests/Helpdesk.Web.Tests.csproj index 1803180..63c22e7 100644 --- a/web/Helpdesk.Web.Tests/Helpdesk.Web.Tests.csproj +++ b/web/Helpdesk.Web.Tests/Helpdesk.Web.Tests.csproj @@ -11,6 +11,7 @@ + diff --git a/web/Helpdesk.Web.Tests/SwaggerAccessTests.cs b/web/Helpdesk.Web.Tests/SwaggerAccessTests.cs new file mode 100644 index 0000000..b0c442d --- /dev/null +++ b/web/Helpdesk.Web.Tests/SwaggerAccessTests.cs @@ -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().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>().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, "test@example.test", "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 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"), + }); + } + } +} diff --git a/web/Helpdesk.Web/Api/ForwardedClientIpHandler.cs b/web/Helpdesk.Web/Api/ForwardedClientIpHandler.cs new file mode 100644 index 0000000..f0e7c0f --- /dev/null +++ b/web/Helpdesk.Web/Api/ForwardedClientIpHandler.cs @@ -0,0 +1,15 @@ +using Microsoft.AspNetCore.HttpOverrides; + +namespace Helpdesk.Web.Api; + +internal sealed class ForwardedClientIpHandler(IHttpContextAccessor accessor) : DelegatingHandler +{ + protected override Task 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); + } +} diff --git a/web/Helpdesk.Web/Api/HelpdeskApiClient.cs b/web/Helpdesk.Web/Api/HelpdeskApiClient.cs index 08e289e..21b4807 100644 --- a/web/Helpdesk.Web/Api/HelpdeskApiClient.cs +++ b/web/Helpdesk.Web/Api/HelpdeskApiClient.cs @@ -8,6 +8,13 @@ namespace Helpdesk.Web.Api; /// Endpointy API pro přihlášeného uživatele; access token přidává . public sealed class HelpdeskApiClient(HttpClient http) { + public async Task 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 GetMeAsync(CancellationToken ct) { using var response = await http.GetAsync("users/me", ct); diff --git a/web/Helpdesk.Web/Controllers/SwaggerController.cs b/web/Helpdesk.Web/Controllers/SwaggerController.cs new file mode 100644 index 0000000..69fc639 --- /dev/null +++ b/web/Helpdesk.Web/Controllers/SwaggerController.cs @@ -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 Document(CancellationToken ct) => + Content(await api.GetOpenApiAsync(ct), "application/json"); +} diff --git a/web/Helpdesk.Web/Helpdesk.Web.csproj b/web/Helpdesk.Web/Helpdesk.Web.csproj index 64a026b..8c436cd 100644 --- a/web/Helpdesk.Web/Helpdesk.Web.csproj +++ b/web/Helpdesk.Web/Helpdesk.Web.csproj @@ -11,6 +11,7 @@ + diff --git a/web/Helpdesk.Web/Program.cs b/web/Helpdesk.Web/Program.cs index 85b4272..fddf1d1 100644 --- a/web/Helpdesk.Web/Program.cs +++ b/web/Helpdesk.Web/Program.cs @@ -37,8 +37,12 @@ static void ConfigureApiClient(IServiceProvider services, HttpClient http) builder.Services.AddHttpContextAccessor(); builder.Services.AddTransient(); -builder.Services.AddHttpClient(ConfigureApiClient); -builder.Services.AddHttpClient(ConfigureApiClient).AddHttpMessageHandler(); +builder.Services.AddTransient(); +builder.Services.AddHttpClient(ConfigureApiClient) + .AddHttpMessageHandler(); +builder.Services.AddHttpClient(ConfigureApiClient) + .AddHttpMessageHandler() + .AddHttpMessageHandler(); // Přihlášení: tokeny API v šifrované HttpOnly cookie, obnova access tokenu při ověření cookie. builder.Services.AddSingleton(TimeProvider.System); @@ -111,6 +115,13 @@ app.UseRouting(); app.UseAuthentication(); 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.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}").WithStaticAssets(); diff --git a/web/Helpdesk.Web/Views/Shared/_UserMenu.cshtml b/web/Helpdesk.Web/Views/Shared/_UserMenu.cshtml index b272d1e..05cc93d 100644 --- a/web/Helpdesk.Web/Views/Shared/_UserMenu.cshtml +++ b/web/Helpdesk.Web/Views/Shared/_UserMenu.cshtml @@ -9,6 +9,10 @@