backend + web: Protect Swagger UI behind admin login
This commit is contained in:
1 parent
d8de714481
commit
eddf5837eb
16 files changed
+158
-28
No files matched your search
@@ -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");
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Helpdesk.Web.Tests" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -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">
|
||||
|
||||
Reference in new issue
Block a user