backend + web: Protect Swagger UI behind admin login

This commit is contained in:
GonnaHetzMe committed 2026-12-03 00:49:36 +01:00
1 parent d8de714481
commit eddf5837eb
16 files changed
+158 -28

No files matched your search

+2 -2
View File
@@ -30,7 +30,7 @@ Potřeba je jen Docker Desktop.
docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
```
3. Webová aplikace: <http://localhost:8081> · Swagger UI: <http://localhost:8080/swagger> · stav a verze schématu: <http://localhost:8080/health>
3. Webová aplikace: <http://localhost:8081> · Swagger UI po přihlášení administrátora: <http://localhost:8081/swagger> · stav a verze schématu: <http://localhost:8080/health>
Lokálně bez reverse proxy nastavte `PUBLIC_BASE_URL=http://localhost:8081`, aby odkazy pro ověření e-mailu a obnovu hesla vedly na web v Dockeru.
@@ -38,7 +38,7 @@ 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.
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.
+1 -1
View File
@@ -15,7 +15,7 @@
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.14" />
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.14" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="10.3.1" />
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerGen" Version="10.3.1" />
<PackageVersion Include="BCrypt.Net-Next" Version="4.2.0" />
<PackageVersion Include="MailKit" Version="5.0.0" />
<PackageVersion Include="FirebaseAdmin" Version="3.7.1" />
+1 -1
View File
@@ -13,7 +13,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
<PackageReference Include="Swashbuckle.AspNetCore" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" />
</ItemGroup>
</Project>
@@ -9,7 +9,7 @@ public static class SwaggerSetup
{
private const string SchemeId = "Bearer";
/// <summary>Swagger UI na <c>/swagger</c> včetně přihlášení access tokenem (NFR-04).</summary>
/// <summary>Generování OpenAPI dokumentu pro administrátorské Swagger UI (NFR-04).</summary>
public static IServiceCollection AddHelpdeskSwagger(this IServiceCollection services)
{
services.AddEndpointsApiExplorer();
+2 -7
View File
@@ -78,17 +78,12 @@ if (trustedProxies.Length > 0)
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();
@@ -1,5 +1,6 @@
using Helpdesk.Api.Controllers;
using System.Net;
using System.Text.Json;
using Helpdesk.Api.Controllers;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
@@ -44,10 +45,18 @@ public sealed class DatabaseTests(BackendFixture fixture) : IClassFixture<Backen
}
[Fact]
public async Task OpenApiDescribesMultipartIssueRequests()
public async Task OnlyAdministratorsCanReadTheOpenApiDocument()
{
using var client = fixture.CreateClient();
using var document = await ReadAsync<JsonDocument>(client.GetAsync("/swagger/v1/swagger.json", Cancellation));
const string path = "/api/v1/admin/openapi/v1.json";
await ExpectAsync(client.GetAsync(path, Cancellation), HttpStatusCode.Unauthorized);
var student = await fixture.RegisterAsync(client);
using var studentClient = fixture.CreateClient((await LoginAsync(client, student.Email)).AccessToken);
await ExpectAsync(studentClient.GetAsync(path, Cancellation), HttpStatusCode.Forbidden);
using var admin = fixture.CreateClient((await LoginAsync(client, AdminEmail)).AccessToken);
await ExpectAsync(admin.GetAsync("/swagger/index.html", Cancellation), HttpStatusCode.NotFound);
await ExpectAsync(admin.GetAsync("/swagger/v1/swagger.json", Cancellation), HttpStatusCode.NotFound);
using var document = await ReadAsync<JsonDocument>(admin.GetAsync(path, Cancellation));
var paths = document.RootElement.GetProperty("paths");
var create = paths.GetProperty("/api/v1/issues").GetProperty("post").GetProperty("requestBody").GetProperty("content");
Assert.True(create.TryGetProperty("application/json", out _));
@@ -66,7 +75,7 @@ public sealed class DatabaseTests(BackendFixture fixture) : IClassFixture<Backen
{
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var reporterId = await db.Users.Select(user => user.Id).SingleAsync(Cancellation);
var reporterId = await db.Users.Where(user => user.Email == AdminEmail).Select(user => user.Id).SingleAsync(Cancellation);
var categoryId = await db.IssueCategories.MinAsync(category => category.Id, Cancellation);
var error = await Assert.ThrowsAsync<MySqlException>(() => db.Database.ExecuteSqlInterpolatedAsync($"""
+1 -1
View File
@@ -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
+10 -10
View File
@@ -153,7 +153,7 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
| NFR-01 | Bezpečnost | Komunikace výhradně přes HTTPS; hesla hashovaná; JWT s krátkou platností; citlivé údaje šifrované (kap. 10). |
| NFR-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`. |
@@ -407,8 +407,8 @@ flowchart TB
subgraph Docker["Docker Compose"]
PROXY[Reverzní proxy nginx<br/>HTTPS / TLS]
WEB[Webová aplikace<br/>ASP.NET Core MVC]
API[Backend REST API<br/>ASP.NET Core Web API<br/>+ Swagger]
WEB[Webová aplikace<br/>ASP.NET Core MVC<br/>+ Swagger UI]
API[Backend REST API<br/>ASP.NET Core Web API<br/>+ OpenAPI]
DB[(MariaDB 11)]
FILES[[Volume: přílohy]]
end
@@ -419,7 +419,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
@@ -647,7 +647,7 @@ Aplikační API má základní cestu **`/api/v1`**. Připojte tento prefix před
Číslo v URL je hlavní verze API. Zpětně kompatibilní rozšíření patří do stávající verze. Při nekompatibilní změně vznikne nová cesta (např. `/api/v2`) a samostatný OpenAPI dokument. Během přechodu klientů poběží obě verze souběžně. Před ukončením podpory starší verze se oznámí termín a zdokumentuje přechod.
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 |
@@ -1129,7 +1129,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 +1157,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 +1171,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í |
+3 -1
View File
@@ -3,7 +3,9 @@
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<!-- Webová aplikace vystačí se sdíleným frameworkem ASP.NET Core; balíčky jsou jen pro testy. -->
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.3.1" />
<!-- Testy -->
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageVersion Include="xunit.v3" Version="4.0.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
@@ -11,6 +11,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<PackageReference Include="xunit.runner.visualstudio" />
@@ -0,0 +1,89 @@
using System.Net;
using System.Text;
using Helpdesk.Web.Api;
using Helpdesk.Web.Auth;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Helpdesk.Web.Tests;
public sealed class SwaggerAccessTests
{
[Fact]
public async Task SwaggerAndItsAssetsRequireAnAdministratorSession()
{
await using var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient))
.ConfigurePrimaryHttpMessageHandler(() => new OpenApiBackend())));
using var client = application.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
BaseAddress = new Uri("https://localhost"),
});
var ct = TestContext.Current.CancellationToken;
string[] paths = ["/swagger", "/swagger/index.html", "/swagger/index.js", "/swagger/swagger-ui.css", "/swagger/v1/swagger.json"];
foreach (var path in paths)
{
using var response = await client.GetAsync(path, ct);
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("/login", response.Headers.Location?.AbsolutePath);
}
SignIn(application.Services, client, UserRoles.Student);
foreach (var path in paths)
{
using var response = await client.GetAsync(path, ct);
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Equal("/error/403", response.Headers.Location?.AbsolutePath);
}
SignIn(application.Services, client, UserRoles.Admin);
using var entry = await client.GetAsync("/swagger", ct);
Assert.Equal(HttpStatusCode.MovedPermanently, entry.StatusCode);
using var index = await client.GetAsync("/swagger/index.html", ct);
Assert.Equal(HttpStatusCode.OK, index.StatusCode);
Assert.Contains("Helpdesk API", await index.Content.ReadAsStringAsync(ct));
Assert.True(index.Headers.CacheControl?.NoStore == true);
using var script = await client.GetAsync("/swagger/index.js", ct);
Assert.Equal(HttpStatusCode.OK, script.StatusCode);
Assert.Contains("v1/swagger.json", await script.Content.ReadAsStringAsync(ct));
using var css = await client.GetAsync("/swagger/swagger-ui.css", ct);
Assert.Equal(HttpStatusCode.OK, css.StatusCode);
using var document = await client.GetAsync("/swagger/v1/swagger.json", ct);
Assert.Equal(HttpStatusCode.OK, document.StatusCode);
Assert.Contains("\"openapi\"", await document.Content.ReadAsStringAsync(ct));
Assert.True(document.Headers.CacheControl?.NoStore == true);
}
private static void SignIn(IServiceProvider services, HttpClient client, string role)
{
var scheme = CookieAuthenticationDefaults.AuthenticationScheme;
var options = services.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get(scheme);
var now = DateTimeOffset.UtcNow;
var properties = new AuthenticationProperties { IssuedUtc = now, ExpiresUtc = now.AddHours(1) };
AuthCookie.StoreTokens(properties, new TokenSet("test-access", now.AddMinutes(15), "test-refresh", now.AddDays(1)));
var user = new UserDto(1, "[email protected]", "Test", "User", null, role, true);
var ticket = new AuthenticationTicket(AuthCookie.CreatePrincipal(user), properties, scheme);
client.DefaultRequestHeaders.Remove("Cookie");
client.DefaultRequestHeaders.Add("Cookie", $"{AuthCookie.Name}={options.TicketDataFormat.Protect(ticket)}");
}
private sealed class OpenApiBackend : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Assert.Equal("/api/v1/admin/openapi/v1.json", request.RequestUri?.AbsolutePath);
Assert.Equal("Bearer", request.Headers.Authorization?.Scheme);
Assert.Equal("test-access", request.Headers.Authorization?.Parameter);
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("""{"openapi":"3.0.4"}""", Encoding.UTF8, "application/json"),
});
}
}
}
@@ -5,6 +5,13 @@ namespace Helpdesk.Web.Api;
/// <summary>Endpointy API pro přihlášeného uživatele; access token přidává <see cref="BearerTokenHandler"/>.</summary>
public sealed class HelpdeskApiClient(HttpClient http)
{
public async Task<string> GetOpenApiAsync(CancellationToken ct)
{
using var response = await http.GetAsync("api/v1/admin/openapi/v1.json", ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
return await response.Content.ReadAsStringAsync(ct);
}
public async Task<UserDto> GetMeAsync(CancellationToken ct)
{
using var response = await http.GetAsync("api/v1/users/me", ct);
@@ -0,0 +1,15 @@
using Helpdesk.Web.Api;
using Helpdesk.Web.Auth;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Helpdesk.Web.Controllers;
[Authorize(Roles = UserRoles.Admin)]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public sealed class SwaggerController(HelpdeskApiClient api) : Controller
{
[HttpGet("/swagger/v1/swagger.json")]
public async Task<IActionResult> Document(CancellationToken ct) =>
Content(await api.GetOpenApiAsync(ct), "application/json");
}
+1
View File
@@ -2,6 +2,7 @@
<ItemGroup>
<InternalsVisibleTo Include="Helpdesk.Web.Tests" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" />
</ItemGroup>
</Project>
+7
View File
@@ -115,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();
@@ -9,6 +9,10 @@
<ul class="dropdown-menu dropdown-menu-end">
<li><span class="dropdown-item-text small text-body-secondary">@User.FindFirst(ClaimTypes.Email)?.Value</span></li>
<li><a class="dropdown-item" asp-controller="Profile" asp-action="Index">Můj profil</a></li>
@if (User.IsInRole(UserRoles.Admin))
{
<li><a class="dropdown-item" href="~/swagger">Swagger API</a></li>
}
<li><hr class="dropdown-divider" /></li>
<li>
<form method="post" asp-controller="Account" asp-action="Logout">