Merge remote-tracking branch 'origin/main' into feature/web-zavady
This commit is contained in:
commit
1550c0343b
45 files changed
+1516
-169
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" />
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
using System.Net;
|
||||
using Helpdesk.Web.Api;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Helpdesk.Web.Tests;
|
||||
|
||||
public sealed class ForwardedClientIpHandlerTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task UsesTheCurrentConnectionAddressInsteadOfTheIncomingHeader()
|
||||
{
|
||||
const string header = "X-Forwarded-For";
|
||||
var context = new DefaultHttpContext();
|
||||
context.Connection.RemoteIpAddress = IPAddress.Parse("198.51.100.10");
|
||||
context.Request.Headers[header] = "203.0.113.11";
|
||||
var accessor = new HttpContextAccessor { HttpContext = context };
|
||||
using var client = new HttpMessageInvoker(new ForwardedClientIpHandler(accessor) { InnerHandler = new Responder() });
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "http://api-web:8080/api/v1/auth/login");
|
||||
using var response = await client.SendAsync(request, TestContext.Current.CancellationToken);
|
||||
Assert.Equal("198.51.100.10", Assert.Single(request.Headers.GetValues(header)));
|
||||
|
||||
accessor.HttpContext = null;
|
||||
using var next = new HttpRequestMessage(HttpMethod.Post, request.RequestUri);
|
||||
using var nextResponse = await client.SendAsync(next, TestContext.Current.CancellationToken);
|
||||
Assert.False(next.Headers.Contains(header));
|
||||
}
|
||||
|
||||
private sealed class Responder : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<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"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
|
||||
namespace Helpdesk.Web.Api;
|
||||
|
||||
internal sealed class ForwardedClientIpHandler(IHttpContextAccessor accessor) : DelegatingHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var header = ForwardedHeadersDefaults.XForwardedForHeaderName;
|
||||
request.Headers.Remove(header);
|
||||
if (accessor.HttpContext?.Connection.RemoteIpAddress is { } address)
|
||||
request.Headers.Add(header, address.ToString());
|
||||
return base.SendAsync(request, cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,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("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");
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Helpdesk.Web.Tests" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -37,8 +37,12 @@ static void ConfigureApiClient(IServiceProvider services, HttpClient http)
|
||||
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddTransient<BearerTokenHandler>();
|
||||
builder.Services.AddHttpClient<AuthApiClient>(ConfigureApiClient);
|
||||
builder.Services.AddHttpClient<HelpdeskApiClient>(ConfigureApiClient).AddHttpMessageHandler<BearerTokenHandler>();
|
||||
builder.Services.AddTransient<ForwardedClientIpHandler>();
|
||||
builder.Services.AddHttpClient<AuthApiClient>(ConfigureApiClient)
|
||||
.AddHttpMessageHandler<ForwardedClientIpHandler>();
|
||||
builder.Services.AddHttpClient<HelpdeskApiClient>(ConfigureApiClient)
|
||||
.AddHttpMessageHandler<ForwardedClientIpHandler>()
|
||||
.AddHttpMessageHandler<BearerTokenHandler>();
|
||||
|
||||
// Přihlášení: tokeny API v šifrované HttpOnly cookie, obnova access tokenu při ověření cookie.
|
||||
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();
|
||||
|
||||
|
||||
@@ -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