Voeg Api.AndreaSlopFotografie toe met setup-token, proxy-bewuste limiters en ASF-admin-thema
- Core: opt-in ForwardedHeaders:KnownProxies en rate limiters per clientadres (zonder configuratie ongewijzigd gedrag) - Identity: optioneel setup-token (X-Setup-Token), beide setup-endpoints onder de login-limiter, beveiligingsgebeurtenis setup_token_rejected (5007) - Nieuw client-project SlpModularCms.Api.AndreaSlopFotografie (Identity + Availability) met bijbehorende tests - Frontend: thema asf (VITE_THEME), VITE_DEFAULT_LANGUAGE, tokenveld op de setup-pagina - CI: jobs publish/deploy-asf-test achter ASF_TEST_DEPLOY_ENABLED - Fix U1: 301-Location wordt nu percent-encoded (gevonden door de property-test) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,7 @@ using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SlpModularCms.Core.Hosting.Health;
|
||||
using SlpModularCms.Core.Hosting.Observability;
|
||||
using SlpModularCms.Core.Hosting.Proxy;
|
||||
using SlpModularCms.Core.Hosting.Security;
|
||||
using SlpModularCms.Core.Hosting.Website;
|
||||
using Scalar.AspNetCore;
|
||||
@@ -52,6 +53,7 @@ public static class CmsHost
|
||||
// 2. Add Core Infrastructure
|
||||
builder.Services.AddCoreInfrastructure(builder.Configuration);
|
||||
builder.Services.AddCmsCors(builder.Configuration);
|
||||
builder.Services.AddCmsForwardedHeaders(builder.Configuration);
|
||||
builder.Services.AddCmsRateLimiting(builder.Configuration);
|
||||
builder.Services.AddCmsHealthChecks();
|
||||
builder.Services.AddCmsSecurityHeaders(builder.Configuration);
|
||||
@@ -97,6 +99,12 @@ public static class CmsHost
|
||||
// what makes a liveness-only health check trustworthy.
|
||||
app.MigrateCoreDatabase();
|
||||
|
||||
// Opt-in (ForwardedHeaders:KnownProxies): makes the real visitor address and scheme visible to
|
||||
// everything below (rate limiter partitions, HTTPS redirection, logging). Not added at all when
|
||||
// no proxy is configured. First in the pipeline so the exception handler and all later
|
||||
// middleware already see the corrected values.
|
||||
app.UseCmsForwardedHeaders();
|
||||
|
||||
// 5. Global Exception Handling
|
||||
app.UseExceptionHandler();
|
||||
|
||||
|
||||
@@ -24,7 +24,8 @@ public sealed class SecurityEventProcessor : ISentryEventProcessor
|
||||
SecurityEventNames.MasterApiKeyRejected,
|
||||
SecurityEventNames.AdminBypassRejected,
|
||||
SecurityEventNames.RateLimitTriggered,
|
||||
SecurityEventNames.MigrationFailure
|
||||
SecurityEventNames.MigrationFailure,
|
||||
SecurityEventNames.SetupTokenRejected
|
||||
}.ToFrozenSet(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Proxy;
|
||||
|
||||
/// <summary>
|
||||
/// The key that separates rate-limit buckets per client. It is the remote address as seen by the
|
||||
/// pipeline (the real visitor once forwarded headers are trusted, otherwise the direct peer).
|
||||
/// </summary>
|
||||
public static class ClientPartitionKey
|
||||
{
|
||||
public const string Unknown = "(unknown)";
|
||||
|
||||
public static string For(HttpContext context)
|
||||
{
|
||||
var address = context.Connection.RemoteIpAddress;
|
||||
if (address is null)
|
||||
{
|
||||
return Unknown;
|
||||
}
|
||||
|
||||
return (address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address).ToString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Proxy;
|
||||
|
||||
public static class ForwardedHeadersExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Validates the <c>ForwardedHeaders</c> section and configures the framework middleware to
|
||||
/// trust only the listed proxies (default trust of loopback is cleared, one hop only).
|
||||
/// Nothing is observable until <see cref="UseCmsForwardedHeaders"/> finds a proxy configured.
|
||||
/// </summary>
|
||||
public static IServiceCollection AddCmsForwardedHeaders(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var settings = configuration.GetSection(ForwardedHeadersSettings.SectionName).Get<ForwardedHeadersSettings>()
|
||||
?? new ForwardedHeadersSettings();
|
||||
var proxies = ForwardedHeadersSettings.ParseKnownProxies(settings.KnownProxies);
|
||||
|
||||
services.AddSingleton(new ForwardedHeadersState(proxies.Count > 0));
|
||||
services.Configure<ForwardedHeadersOptions>(options =>
|
||||
{
|
||||
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
||||
options.ForwardLimit = 1;
|
||||
options.KnownProxies.Clear();
|
||||
options.KnownIPNetworks.Clear();
|
||||
foreach (var proxy in proxies)
|
||||
{
|
||||
options.KnownProxies.Add(proxy);
|
||||
}
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>Adds the forwarded-headers middleware only when at least one proxy is configured.</summary>
|
||||
public static IApplicationBuilder UseCmsForwardedHeaders(this IApplicationBuilder app)
|
||||
{
|
||||
var state = app.ApplicationServices.GetService<ForwardedHeadersState>();
|
||||
return state is { Enabled: true } ? app.UseForwardedHeaders() : app;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed record ForwardedHeadersState(bool Enabled);
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Net;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Proxy;
|
||||
|
||||
/// <summary>
|
||||
/// Opt-in trust in a reverse proxy (section <c>ForwardedHeaders</c>). With no known proxy
|
||||
/// configured the host ignores <c>X-Forwarded-*</c> headers completely, exactly as before.
|
||||
/// </summary>
|
||||
public sealed class ForwardedHeadersSettings
|
||||
{
|
||||
public const string SectionName = "ForwardedHeaders";
|
||||
|
||||
/// <summary>IP addresses of the reverse proxies whose <c>X-Forwarded-For</c>/<c>-Proto</c> are trusted.</summary>
|
||||
public string[] KnownProxies { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Parses and validates the configured proxy addresses.
|
||||
/// Throws <see cref="InvalidOperationException"/> for an unparsable entry or a wildcard
|
||||
/// (any-address) entry: trusting every sender would let any client spoof its address.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<IPAddress> ParseKnownProxies(IEnumerable<string>? entries)
|
||||
{
|
||||
var result = new List<IPAddress>();
|
||||
foreach (var entry in entries ?? [])
|
||||
{
|
||||
if (!IPAddress.TryParse(entry?.Trim(), out var address))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"{SectionName}:KnownProxies contains an entry that is not an IP address.");
|
||||
}
|
||||
|
||||
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"{SectionName}:KnownProxies must not contain an any-address entry (0.0.0.0 or ::).");
|
||||
}
|
||||
|
||||
result.Add(address);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ using Microsoft.IdentityModel.Tokens;
|
||||
using SlpModularCms.Core.Availability;
|
||||
using SlpModularCms.Core.Data;
|
||||
using SlpModularCms.Core.Exceptions;
|
||||
using SlpModularCms.Core.Hosting.Proxy;
|
||||
using SlpModularCms.Core.Hosting.Security;
|
||||
using SlpModularCms.Core.Identity.Authorization;
|
||||
using SlpModularCms.Core.Identity.Entities;
|
||||
@@ -157,43 +158,58 @@ public static class ServiceCollectionExtensions
|
||||
return ValueTask.CompletedTask;
|
||||
};
|
||||
|
||||
options.AddFixedWindowLimiter("login", opt =>
|
||||
// Every named policy is partitioned per client address (ClientPartitionKey). Behind a
|
||||
// reverse proxy that is only meaningful once ForwardedHeaders:KnownProxies is set;
|
||||
// without it all callers share the proxy address, i.e. one bucket, as before.
|
||||
options.AddPolicy("login", context =>
|
||||
{
|
||||
var settings = configuration.GetSection("RateLimiting:Login");
|
||||
opt.PermitLimit = settings.GetValue<int>("PermitLimit", 5);
|
||||
opt.Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60));
|
||||
opt.QueueLimit = 0;
|
||||
return RateLimitPartition.GetFixedWindowLimiter(ClientPartitionKey.For(context), _ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = settings.GetValue<int>("PermitLimit", 5),
|
||||
Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60)),
|
||||
QueueLimit = 0
|
||||
});
|
||||
});
|
||||
|
||||
options.AddSlidingWindowLimiter("refresh", opt =>
|
||||
options.AddPolicy("refresh", context =>
|
||||
{
|
||||
var settings = configuration.GetSection("RateLimiting:Refresh");
|
||||
opt.PermitLimit = settings.GetValue<int>("PermitLimit", 20);
|
||||
opt.Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60));
|
||||
opt.SegmentsPerWindow = 4;
|
||||
opt.QueueLimit = 0;
|
||||
return RateLimitPartition.GetSlidingWindowLimiter(ClientPartitionKey.For(context), _ => new SlidingWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = settings.GetValue<int>("PermitLimit", 20),
|
||||
Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60)),
|
||||
SegmentsPerWindow = 4,
|
||||
QueueLimit = 0
|
||||
});
|
||||
});
|
||||
|
||||
// Guards the anonymous Sentry tunnel. Generous, because a burst of browser errors is
|
||||
// exactly when reporting matters most, but bounded, because the endpoint makes an
|
||||
// outbound HTTPS request per call.
|
||||
options.AddFixedWindowLimiter(SentryTunnelExtensions.RateLimiterName, opt =>
|
||||
options.AddPolicy(SentryTunnelExtensions.RateLimiterName, context =>
|
||||
{
|
||||
var settings = configuration.GetSection("RateLimiting:SentryTunnel");
|
||||
opt.PermitLimit = settings.GetValue<int>("PermitLimit", 60);
|
||||
opt.Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60));
|
||||
opt.QueueLimit = 0;
|
||||
return RateLimitPartition.GetFixedWindowLimiter(ClientPartitionKey.For(context), _ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = settings.GetValue<int>("PermitLimit", 60),
|
||||
Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60)),
|
||||
QueueLimit = 0
|
||||
});
|
||||
});
|
||||
|
||||
// Guards the anonymous public offerings listing (NFR-OFF-01) against scraping.
|
||||
// Only the public GET carries this policy — admin mutation endpoints are already
|
||||
// behind AdminOnly authentication (Offerings NFR Requirements Q1 = A).
|
||||
options.AddFixedWindowLimiter("offerings-public", opt =>
|
||||
options.AddPolicy("offerings-public", context =>
|
||||
{
|
||||
var settings = configuration.GetSection("RateLimiting:OfferingsPublic");
|
||||
opt.PermitLimit = settings.GetValue<int>("PermitLimit", 120);
|
||||
opt.Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60));
|
||||
opt.QueueLimit = 0;
|
||||
return RateLimitPartition.GetFixedWindowLimiter(ClientPartitionKey.For(context), _ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = settings.GetValue<int>("PermitLimit", 120),
|
||||
Window = TimeSpan.FromSeconds(settings.GetValue<int>("WindowSeconds", 60)),
|
||||
QueueLimit = 0
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Website;
|
||||
|
||||
/// <summary>
|
||||
@@ -138,13 +140,13 @@ public static class WebsitePathResolver
|
||||
{
|
||||
return !hasTrailingSlash && name == pageName
|
||||
? new WebsiteResolution.ServeFile(pageName + ".html")
|
||||
: new WebsiteResolution.Redirect("/" + pageName + query);
|
||||
: new WebsiteResolution.Redirect(EncodePath("/" + pageName) + query);
|
||||
}
|
||||
|
||||
// R11 - trailing slashes are stripped by a 301, whether or not the target exists.
|
||||
if (hasTrailingSlash)
|
||||
{
|
||||
return new WebsiteResolution.Redirect(stripped + query);
|
||||
return new WebsiteResolution.Redirect(EncodePath(stripped) + query);
|
||||
}
|
||||
|
||||
// R8 - paths that look like files are served as they are (never lower-cased) or not found.
|
||||
@@ -158,6 +160,13 @@ public static class WebsitePathResolver
|
||||
return fileExists(directoryIndex) ? new WebsiteResolution.ServeFile(directoryIndex) : notFound;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The input path is decoded, but a Location header must be a valid URL reference: without this a
|
||||
/// request for <c>/a%3Fb/</c> would redirect to <c>/a?b</c> (a different resource), a '#' would
|
||||
/// start a fragment, and non-ASCII characters would end up raw in a header value.
|
||||
/// </summary>
|
||||
private static string EncodePath(string decodedPath) => new PathString(decodedPath).ToUriComponent();
|
||||
|
||||
private static bool HasForbiddenCharacters(string path)
|
||||
{
|
||||
foreach (var c in path)
|
||||
|
||||
Reference in New Issue
Block a user