Merge remote-tracking branch 'origin/main' into feature/web-zavady

This commit is contained in:
PatTheEvil committed 2026-12-04 15:44:41 +01:00
commit 1550c0343b
45 files changed
+1516 -169

No files matched your search

@@ -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"),
});
}
}
}