Makes the application say what it is doing and when it fails
U4. Console logging plus Sentry, a same-origin tunnel so ad blockers cannot silence browser errors, Umami on the admin SPA, and six security events that alert rules can actually be built on. The correlation id is the W3C trace id from the ambient Activity, enabled by one line of ActivityTrackingOptions so every entry from every category carries it without touching a call site. It propagates across the master/slave boundary via traceparent, which TraceIdentifier cannot do at all, and it is the same value ProblemDetails already returns to the browser. The security events use source-generated LoggerMessage with constant templates. Sentry groups log events by message, so interpolating an email address would give every address its own issue and "more than 20 failed logins in five minutes" could never fire — the events would arrive, be visible, be tagged, and the alerting would silently be impossible. A test asserts the rendered message is identical across argument values. Scrubbing happens in-process, before transmission, and covers Set-Cookie as well as Cookie: the login response issues the refreshToken there, so scrubbing only the request side would protect nothing. Transactions are scrubbed too, because they carry request data and are the channel nobody thinks of. The tunnel derives its destination from the DSN once at startup and reads nothing from the request, which is what separates a tunnel from a server-side request forgery primitive. Size is capped by a bounded read rather than by trusting Content-Length, and the endpoint is rate limited. Two things found along the way. Zod 4's url() hands the value to the URL constructor, which accepts any scheme — so the existing frontend validation would have accepted the exact "htp://" typo BR-U4-24 names, and the SPA would have called a nonexistent origin. Now constrained to http(s). And the new appsettings comments are verified against the real configuration provider, because the failure mode if it rejected them is both hosts refusing to start after a release switch. One deviation. IAdminTokenValidator was meant to gain a reason-reporting overload; implemented that way, a substitute returning false by default silently inverted the access decision while both methods compiled. Two methods whose difference is invisible at the call site is the defect, so it is now a single Validate returning AdminTokenResult. Touches two files from already-committed units: DatabaseMigrationExtensions (U2) gains a flush before the rethrow, or the one Critical event in the system dies with the process; AdminTokenValidator (U1) classifies why a bypass was refused. Build 0 errors; 366 backend tests pass, up from 315, and 237 frontend tests, up from 213. tsc clean, eslint clean on every changed file. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HHoJpxYXzHACSQguHrC5fw
This commit is contained in:
@@ -3,7 +3,9 @@ using Microsoft.Data.SqlClient;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Sentry;
|
||||
using SlpModularCms.Core.Data;
|
||||
using SlpModularCms.Core.Observability;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting;
|
||||
|
||||
@@ -79,10 +81,15 @@ public static class DatabaseMigrationExtensions
|
||||
{
|
||||
// Logged with the failure reason but never the connection string or credentials —
|
||||
// this message travels to the console and to Sentry.
|
||||
logger.LogCritical(
|
||||
ex,
|
||||
"Core database migration failed after {Attempts} attempt(s). The application will not start.",
|
||||
attempt);
|
||||
SecurityEvents.MigrationFailure(logger, ex, attempt);
|
||||
|
||||
// The SDK batches and sends in the background, and this process is about to exit
|
||||
// — which would kill the sender before it transmits. Without this flush the one
|
||||
// Critical event in the whole system is also the event most likely never to
|
||||
// arrive. Bounded at five seconds: a host that cannot reach its database is
|
||||
// already down, and five seconds buys the alert that says why. A no-op when
|
||||
// Sentry was never initialised, so the no-DSN path is unaffected.
|
||||
SentrySdk.Flush(TimeSpan.FromSeconds(5));
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Observability;
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class LoggingExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures structured console logging with a correlation identifier on every entry.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Must be called <b>before</b> Sentry is registered, so that a problem initialising Sentry
|
||||
/// is itself logged.
|
||||
/// </remarks>
|
||||
public static ILoggingBuilder AddCmsLogging(this ILoggingBuilder logging, IHostEnvironment environment)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(logging);
|
||||
ArgumentNullException.ThrowIfNull(environment);
|
||||
|
||||
// The default host already added a console provider without IncludeScopes. Adding a
|
||||
// second one prints every line twice — once with the correlation ID and once without —
|
||||
// which reads as a logging bug and wastes real time.
|
||||
logging.ClearProviders();
|
||||
|
||||
// The correlation identifier required by SECURITY-03, resolved as the W3C trace ID from
|
||||
// the ambient Activity rather than HttpContext.TraceIdentifier.
|
||||
//
|
||||
// Two reasons, the first decisive:
|
||||
// 1. It crosses the master/slave HTTP boundary. HttpClient injects traceparent and the
|
||||
// slave's hosting layer adopts it, so both sides' log entries carry the SAME value.
|
||||
// "The master says the slave rejected its API key — what did the slave see?" is the
|
||||
// hardest diagnostic question in this codebase, and TraceIdentifier, being host-local,
|
||||
// cannot answer it at all.
|
||||
// 2. It is already the value the client is shown: ASP.NET Core's ProblemDetails writes
|
||||
// traceId as Activity.Current?.Id ?? HttpContext.TraceIdentifier. So the log entry,
|
||||
// the Sentry event, the slave's log entry and the browser's error response all carry
|
||||
// one value, and an operator handed a traceId from a screenshot can find the request.
|
||||
//
|
||||
// This puts TraceId into the scope of EVERY entry from every category, framework included,
|
||||
// without touching a single call site — which matters, because the alternative is
|
||||
// remembering to pass an identifier into every existing log call.
|
||||
logging.Configure(options =>
|
||||
options.ActivityTrackingOptions =
|
||||
ActivityTrackingOptions.TraceId |
|
||||
ActivityTrackingOptions.SpanId |
|
||||
ActivityTrackingOptions.ParentId);
|
||||
|
||||
if (environment.IsDevelopment())
|
||||
{
|
||||
// A developer reads this with their eyes, and JSON is hostile to that.
|
||||
logging.AddSimpleConsole(options =>
|
||||
{
|
||||
options.IncludeScopes = true;
|
||||
options.SingleLine = true;
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
// In test and production the process is supervised and its stdout lands in the
|
||||
// journal, where JSON is greppable and TraceId is a field rather than a substring.
|
||||
logging.AddJsonConsole(options => options.IncludeScopes = true);
|
||||
}
|
||||
|
||||
return logging;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
namespace SlpModularCms.Core.Hosting.Observability;
|
||||
|
||||
/// <summary>
|
||||
/// Configuration for logging and error reporting.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Every value here is optional. An absent DSN is a normal, fully supported state — local
|
||||
/// development and any deployment without Sentry must work unchanged — so nothing in this
|
||||
/// section is required and nothing warns about being empty.
|
||||
///
|
||||
/// Deliberately <b>not</b> configurable: the scrub list and the tunnel's destination host. Both
|
||||
/// are security-critical, and making either configurable would create a way to switch the
|
||||
/// protection off — the scrub list by omission, the destination by turning the tunnel into a
|
||||
/// request-forgery primitive.
|
||||
/// </remarks>
|
||||
public sealed class ObservabilityOptions
|
||||
{
|
||||
public const string SectionName = "Observability";
|
||||
|
||||
/// <summary>
|
||||
/// Sentry DSN. Empty means Sentry is skipped entirely.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Not a secret in the usual sense — it identifies a project and permits event submission,
|
||||
/// and the frontend's copy is visible in the page source. It still comes from an environment
|
||||
/// variable (<c>Observability__SentryDsn</c>) in test and production rather than being
|
||||
/// committed: it belongs to an account, and the repository is not where it should be written
|
||||
/// down.
|
||||
/// </remarks>
|
||||
public string SentryDsn { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Environment tag. Falls back to <c>ASPNETCORE_ENVIRONMENT</c> when empty.</summary>
|
||||
public string Environment { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Performance sampling rate.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Kept low: Sentry's free plan counts transactions against the same quota as errors, and
|
||||
/// this setup's value is in errors rather than performance traces.
|
||||
/// </remarks>
|
||||
public double TracesSampleRate { get; set; } = 0.1;
|
||||
|
||||
/// <summary>
|
||||
/// Hard upper bound on a tunnelled envelope. Envelopes with a stack trace and breadcrumbs
|
||||
/// run to tens of kilobytes, so this is generous without being an allocation risk on a
|
||||
/// Raspberry Pi.
|
||||
/// </summary>
|
||||
public int TunnelMaxPayloadBytes { get; set; } = 204_800;
|
||||
|
||||
public bool IsSentryConfigured => !string.IsNullOrWhiteSpace(SentryDsn);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization.Policy;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SlpModularCms.Core.Observability;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Observability;
|
||||
|
||||
/// <summary>
|
||||
/// Reports authorization denials, then defers entirely to the framework's own handler.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Hooked in at <see cref="IAuthorizationMiddlewareResultHandler"/> rather than inside an
|
||||
/// <see cref="IAuthorizationHandler"/>, because a handler sees one requirement at a time: a
|
||||
/// requirement that does not succeed is not the same as the request being denied, and reporting
|
||||
/// from there would produce events for requests that were ultimately allowed. This interface sees
|
||||
/// the final result, which is the thing worth alerting on.
|
||||
///
|
||||
/// The response itself is unchanged — this only observes.
|
||||
/// </remarks>
|
||||
public sealed class SecurityAuthorizationResultHandler : IAuthorizationMiddlewareResultHandler
|
||||
{
|
||||
private readonly AuthorizationMiddlewareResultHandler _inner = new();
|
||||
private readonly ILogger<SecurityAuthorizationResultHandler> _logger;
|
||||
|
||||
public SecurityAuthorizationResultHandler(ILogger<SecurityAuthorizationResultHandler> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public Task HandleAsync(
|
||||
RequestDelegate next,
|
||||
HttpContext context,
|
||||
AuthorizationPolicy policy,
|
||||
PolicyAuthorizationResult authorizeResult)
|
||||
{
|
||||
// Challenged means "not authenticated yet" — a 401 that the browser resolves by logging
|
||||
// in, and an entirely ordinary event. Forbidden means an authenticated caller reached
|
||||
// something they lack the rights for, which is the case worth knowing about.
|
||||
if (authorizeResult.Forbidden)
|
||||
{
|
||||
SecurityEvents.AuthorizationDenied(
|
||||
_logger,
|
||||
context.Request.Path,
|
||||
DescribePolicy(policy));
|
||||
}
|
||||
|
||||
return _inner.HandleAsync(next, context, policy, authorizeResult);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Names the requirements rather than the policy, because ASP.NET Core resolves the policy
|
||||
/// object before this point and the original name is no longer available.
|
||||
/// </summary>
|
||||
private static string DescribePolicy(AuthorizationPolicy policy) =>
|
||||
string.Join(", ", policy.Requirements.Select(requirement => requirement.GetType().Name));
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.Collections.Frozen;
|
||||
using Sentry;
|
||||
using Sentry.Extensibility;
|
||||
using SlpModularCms.Core.Observability;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Observability;
|
||||
|
||||
/// <summary>
|
||||
/// Promotes a security event's constant name to a Sentry tag.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Alert rules then filter on <c>security_event:failed_login</c>, which survives a change to the
|
||||
/// message wording. Matching on message text would not — and it would break silently, because a
|
||||
/// rule that matches nothing looks exactly like a rule with nothing to match.
|
||||
/// </remarks>
|
||||
public sealed class SecurityEventProcessor : ISentryEventProcessor
|
||||
{
|
||||
public const string TagName = "security_event";
|
||||
|
||||
private static readonly FrozenSet<string> KnownEventNames = new[]
|
||||
{
|
||||
SecurityEventNames.FailedLogin,
|
||||
SecurityEventNames.AuthorizationDenied,
|
||||
SecurityEventNames.MasterApiKeyRejected,
|
||||
SecurityEventNames.AdminBypassRejected,
|
||||
SecurityEventNames.RateLimitTriggered,
|
||||
SecurityEventNames.MigrationFailure
|
||||
}.ToFrozenSet(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// The structured property name that <see cref="SecurityEvents"/> attaches to every entry.
|
||||
/// </summary>
|
||||
private const string PropertyName = "SecurityEvent";
|
||||
|
||||
public SentryEvent? Process(SentryEvent @event)
|
||||
{
|
||||
if (@event is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (@event.Extra.TryGetValue(PropertyName, out var value) &&
|
||||
value is string name &&
|
||||
KnownEventNames.Contains(name))
|
||||
{
|
||||
@event.SetTag(TagName, name);
|
||||
}
|
||||
|
||||
return @event;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using Sentry;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Observability;
|
||||
|
||||
/// <summary>Removes credentials from an outbound Sentry event.</summary>
|
||||
public interface ISentryEventScrubber
|
||||
{
|
||||
SentryEvent Scrub(SentryEvent sentryEvent);
|
||||
|
||||
SentryTransaction ScrubTransaction(SentryTransaction transaction);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Strips credential-bearing headers and the request body before anything leaves the process.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Enabling <c>SendDefaultPii</c> attaches request headers, and "PII" understates what this
|
||||
/// application carries in them: a <c>refreshToken</c> cookie and the master/slave shared secret
|
||||
/// are <b>credentials</b>, not merely personal data. Sending them to a third party would be
|
||||
/// worse than the problem the setting solves.
|
||||
///
|
||||
/// This runs <b>in-process, before transmission</b>. Sentry offers server-side scrubbing, but by
|
||||
/// then the secret has already left the building — doing it here is the only version that
|
||||
/// actually protects anything.
|
||||
///
|
||||
/// It is a class rather than a lambda inside the <c>UseSentry</c> callback because it is the most
|
||||
/// security-critical code in this unit, and a lambda there cannot be unit-tested without
|
||||
/// initialising the SDK.
|
||||
/// </remarks>
|
||||
public sealed class SentryEventScrubber : ISentryEventScrubber
|
||||
{
|
||||
/// <summary>
|
||||
/// A <c>static readonly</c> array in code, never an options property: a configurable scrub
|
||||
/// list is a supported way to switch the protection off by omission.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> RemovedHeaders => RemovedHeaderNames;
|
||||
|
||||
private static readonly string[] RemovedHeaderNames =
|
||||
[
|
||||
// The whole header, not one cookie. It carries the refreshToken, and removing a single
|
||||
// cookie by rewriting the header is error-prone in a way that removing the header is not.
|
||||
"Cookie",
|
||||
|
||||
// The response counterpart. The login and refresh responses ISSUE the refreshToken here,
|
||||
// so scrubbing the request cookie while sending this one would protect nothing.
|
||||
"Set-Cookie",
|
||||
|
||||
// Bearer token.
|
||||
"Authorization",
|
||||
|
||||
// The master/slave shared secret. Not mentioned when SendDefaultPii was chosen, but the
|
||||
// same class of secret — and it would otherwise be sent to a third party on every error
|
||||
// raised during a master/slave call.
|
||||
"X-Master-Api-Key"
|
||||
];
|
||||
|
||||
public SentryEvent Scrub(SentryEvent sentryEvent)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sentryEvent);
|
||||
|
||||
ScrubRequest(sentryEvent.Request);
|
||||
return sentryEvent;
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// Transactions carry request data too. Scrubbing only events would leave a second channel
|
||||
/// open — less obvious precisely because nobody thinks of a transaction as containing
|
||||
/// headers — so raising <c>TracesSampleRate</c> later, without touching this file, would
|
||||
/// start leaking.
|
||||
/// </remarks>
|
||||
public SentryTransaction ScrubTransaction(SentryTransaction transaction)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(transaction);
|
||||
|
||||
ScrubRequest(transaction.Request);
|
||||
return transaction;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What is deliberately <b>retained</b>: method, path, query string, user agent, IP address,
|
||||
/// authenticated username and the correlation ID — all genuinely diagnostic.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Query strings are kept even though invitation tokens travel as <c>?token=…</c> on one
|
||||
/// endpoint. That token is single-use and time-limited rather than a standing credential, and
|
||||
/// knowing which endpoint was called outweighs it. Recorded so the trade-off is visible
|
||||
/// rather than accidental.
|
||||
/// </remarks>
|
||||
private static void ScrubRequest(SentryRequest request)
|
||||
{
|
||||
foreach (var header in RemovedHeaderNames)
|
||||
{
|
||||
request.Headers.Remove(header);
|
||||
}
|
||||
|
||||
// Belt and braces: MaxRequestBodySize is None, so the body should never have been
|
||||
// captured in the first place. Nulling it here means a future change to that option
|
||||
// cannot quietly start shipping login payloads.
|
||||
request.Data = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Sentry.AspNetCore;
|
||||
using Sentry.Extensibility;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Observability;
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class SentryExtensions
|
||||
{
|
||||
public static IServiceCollection AddCmsObservability(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
services.AddOptions<ObservabilityOptions>()
|
||||
.Bind(configuration.GetSection(ObservabilityOptions.SectionName))
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddSingleton<ISentryEventScrubber, SentryEventScrubber>();
|
||||
services.AddSingleton<SecurityEventProcessor>();
|
||||
|
||||
// Resolving this at startup is what makes an unparseable DSN a startup failure rather
|
||||
// than a per-request one.
|
||||
services.AddSingleton<SentryTunnelTarget>();
|
||||
|
||||
services.AddHttpClient(SentryTunnelExtensions.HttpClientName, client =>
|
||||
{
|
||||
// Short, and no retry. A dropped error report is acceptable; a request thread held
|
||||
// open by an anonymous caller is not.
|
||||
client.Timeout = TimeSpan.FromSeconds(5);
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers Sentry, or does nothing at all when no DSN is configured.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// An absent DSN is a normal, supported state and produces <b>no warning</b>. Local
|
||||
/// development is the common case, and a startup warning that always appears trains people to
|
||||
/// ignore startup warnings — including the ones that matter.
|
||||
/// </remarks>
|
||||
public static IWebHostBuilder UseCmsSentry(this IWebHostBuilder webHost, IConfiguration configuration)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(webHost);
|
||||
ArgumentNullException.ThrowIfNull(configuration);
|
||||
|
||||
var settings = configuration.GetSection(ObservabilityOptions.SectionName).Get<ObservabilityOptions>()
|
||||
?? new ObservabilityOptions();
|
||||
|
||||
if (!settings.IsSentryConfigured)
|
||||
{
|
||||
return webHost;
|
||||
}
|
||||
|
||||
// Stateless, and needed inside a callback that runs before any service provider exists.
|
||||
// The same types are also registered in DI, where the tests reach them.
|
||||
var scrubber = new SentryEventScrubber();
|
||||
var processor = new SecurityEventProcessor();
|
||||
|
||||
return webHost.UseSentry(options =>
|
||||
{
|
||||
options.Dsn = settings.SentryDsn;
|
||||
options.Environment = string.IsNullOrWhiteSpace(settings.Environment) ? null : settings.Environment;
|
||||
options.Release = GetRelease();
|
||||
options.TracesSampleRate = settings.TracesSampleRate;
|
||||
|
||||
// Reconciles two answers rather than choosing between them: the console gets
|
||||
// everything at Information, Sentry gets warnings and errors as EVENTS — still more
|
||||
// than exceptions — and informational entries travel attached to those events as
|
||||
// breadcrumbs. Sending every framework Information entry as an event would mean one
|
||||
// event per request, exhausting the free plan within hours and burying real errors in
|
||||
// request noise.
|
||||
options.MinimumBreadcrumbLevel = LogLevel.Information;
|
||||
options.MinimumEventLevel = LogLevel.Warning;
|
||||
|
||||
// Attaches request context — and therefore requires the scrubber below.
|
||||
options.SendDefaultPii = true;
|
||||
|
||||
// The safest version of "the request body is never sent to Sentry" is that it is
|
||||
// never read into an event at all. This is the SDK default; set explicitly so that a
|
||||
// future change to it has to be deliberate.
|
||||
options.MaxRequestBodySize = RequestSize.None;
|
||||
|
||||
options.SetBeforeSend((sentryEvent, _) => scrubber.Scrub(sentryEvent));
|
||||
options.SetBeforeSendTransaction((transaction, _) => scrubber.ScrubTransaction(transaction));
|
||||
options.AddEventProcessor(processor);
|
||||
});
|
||||
}
|
||||
|
||||
private static string GetRelease()
|
||||
{
|
||||
var assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();
|
||||
|
||||
return assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion
|
||||
?? assembly.GetName().Version?.ToString()
|
||||
?? "unknown";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Observability;
|
||||
|
||||
/// <summary>
|
||||
/// Forwards browser Sentry envelopes through this application's own origin.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Ad blockers block requests to Sentry domains with <c>ERR_BLOCKED_BY_CLIENT</c>. Without a
|
||||
/// tunnel, errors are lost precisely for the users who have an ad blocker — a silently biased
|
||||
/// sample of exactly the group most likely to have browser oddities. It also keeps browser
|
||||
/// traffic same-origin, so the CSP needs <c>connect-src 'self'</c> and no external Sentry origin.
|
||||
///
|
||||
/// The reference project tunnels through nginx. Relying on server configuration is what this
|
||||
/// deployment model forbids, so the application forwards it instead.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class SentryTunnelExtensions
|
||||
{
|
||||
public const string HttpClientName = "sentry-tunnel";
|
||||
public const string RateLimiterName = "sentry-tunnel";
|
||||
|
||||
public static IEndpointRouteBuilder MapSentryTunnel(this IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapPost(SentryTunnelTarget.Path, HandleAsync)
|
||||
// Anonymous on purpose: the errors most worth capturing include authentication
|
||||
// failures, so error reporting must work for a user whose session just expired.
|
||||
.AllowAnonymous()
|
||||
// An anonymous endpoint that triggers an outbound HTTPS request per call is a free
|
||||
// amplifier and a way to burn the Sentry plan's quota from outside. The other three
|
||||
// controls — fixed destination, size cap, no-DSN-no-forwarding — bound what each call
|
||||
// can do but not how many calls there can be.
|
||||
.RequireRateLimiting(RateLimiterName)
|
||||
// Not a versioned CMS API and not part of the public contract.
|
||||
.ExcludeFromDescription()
|
||||
.WithName("SentryTunnel");
|
||||
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
private static async Task<IResult> HandleAsync(
|
||||
HttpContext context,
|
||||
SentryTunnelTarget target,
|
||||
IHttpClientFactory httpClientFactory,
|
||||
ILoggerFactory loggerFactory,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!target.IsConfigured)
|
||||
{
|
||||
// 404 rather than 503: with no DSN configured this endpoint genuinely does not exist.
|
||||
return Results.NotFound();
|
||||
}
|
||||
|
||||
// Content-Length is absent under chunked transfer encoding and is attacker-controlled in
|
||||
// any case, so this is an optimisation rather than the control.
|
||||
if (context.Request.ContentLength > target.MaxPayloadBytes)
|
||||
{
|
||||
return Results.StatusCode(StatusCodes.Status413PayloadTooLarge);
|
||||
}
|
||||
|
||||
// This bounded read IS the control. Trusting Content-Length alone would give an anonymous
|
||||
// caller an unbounded memory allocation on a Raspberry Pi.
|
||||
var payload = await ReadAtMostAsync(context.Request.Body, target.MaxPayloadBytes, cancellationToken);
|
||||
if (payload is null)
|
||||
{
|
||||
return Results.StatusCode(StatusCodes.Status413PayloadTooLarge);
|
||||
}
|
||||
|
||||
var logger = loggerFactory.CreateLogger(typeof(SentryTunnelExtensions).FullName!);
|
||||
|
||||
try
|
||||
{
|
||||
using var content = new ByteArrayContent(payload);
|
||||
var client = httpClientFactory.CreateClient(HttpClientName);
|
||||
|
||||
// target.EnvelopeEndpoint was derived from configuration at startup. No part of the
|
||||
// destination comes from this request, and that is what separates a tunnel from a
|
||||
// server-side request forgery primitive.
|
||||
using var response = await client.PostAsync(target.EnvelopeEndpoint, content, cancellationToken);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
logger.LogWarning(
|
||||
"Sentry tunnel: ingest returned {StatusCode} for a {ByteCount}-byte envelope.",
|
||||
(int)response.StatusCode, payload.Length);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogWarning(ex, "Sentry tunnel: forwarding an envelope failed.");
|
||||
}
|
||||
|
||||
// Accepted regardless of what happened upstream. The browser must not retry or log a
|
||||
// console error over a failed error report: failing to report an error must not itself
|
||||
// become an error.
|
||||
return Results.Accepted();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads at most <paramref name="maxBytes"/>. Returns null when the stream carries more.
|
||||
/// </summary>
|
||||
private static async Task<byte[]?> ReadAtMostAsync(Stream body, int maxBytes, CancellationToken cancellationToken)
|
||||
{
|
||||
// One byte of headroom, so "exactly at the limit" and "over the limit" are distinguishable.
|
||||
var buffer = new byte[maxBytes + 1];
|
||||
var total = 0;
|
||||
|
||||
while (total < buffer.Length)
|
||||
{
|
||||
var read = await body.ReadAsync(buffer.AsMemory(total), cancellationToken);
|
||||
if (read == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
total += read;
|
||||
}
|
||||
|
||||
return total > maxBytes ? null : buffer[..total];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Observability;
|
||||
|
||||
/// <summary>
|
||||
/// The one destination the Sentry tunnel is allowed to forward to, derived from the configured
|
||||
/// DSN at startup.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <b>This class is the rule that keeps the tunnel from being a liability.</b> An anonymous
|
||||
/// endpoint that makes an outbound request on demand is a server-side request forgery primitive
|
||||
/// if the destination comes from the caller. Computing it once, from configuration, and never
|
||||
/// reading anything from the request makes that structurally impossible rather than merely
|
||||
/// avoided by the current code.
|
||||
///
|
||||
/// An unparseable DSN fails at startup rather than per request, consistent with the security
|
||||
/// headers unit and with failing closed generally.
|
||||
/// </remarks>
|
||||
public sealed class SentryTunnelTarget
|
||||
{
|
||||
/// <summary>Same path the reference project uses, where nginx serves it.</summary>
|
||||
/// <remarks>
|
||||
/// Here the application forwards it, because relying on reverse-proxy configuration is
|
||||
/// exactly what this deployment model forbids. Keeping the path identical means the frontend
|
||||
/// <c>tunnel</c> option, the vite dev proxy and an operator's muscle memory all carry over
|
||||
/// unchanged between the two workspaces.
|
||||
///
|
||||
/// Deliberately outside <c>/api/v1</c>: it is not a versioned CMS API, it must not appear in
|
||||
/// the OpenAPI document, and <c>/api/v1</c> maps to the strict CSP policy for reasons that
|
||||
/// have nothing to do with this endpoint.
|
||||
/// </remarks>
|
||||
public const string Path = "/sentry-tunnel";
|
||||
|
||||
/// <summary>Null when no DSN is configured — the tunnel then accepts nothing.</summary>
|
||||
public Uri? EnvelopeEndpoint { get; }
|
||||
|
||||
public int MaxPayloadBytes { get; }
|
||||
|
||||
public bool IsConfigured => EnvelopeEndpoint is not null;
|
||||
|
||||
public SentryTunnelTarget(IOptions<ObservabilityOptions> options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
var value = options.Value;
|
||||
|
||||
MaxPayloadBytes = value.TunnelMaxPayloadBytes > 0 ? value.TunnelMaxPayloadBytes : 204_800;
|
||||
EnvelopeEndpoint = value.IsSentryConfigured ? BuildEnvelopeEndpoint(value.SentryDsn) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Turns <c>https://{publicKey}@{host}/{projectId}</c> into
|
||||
/// <c>https://{host}/api/{projectId}/envelope/</c>.
|
||||
/// </summary>
|
||||
private static Uri BuildEnvelopeEndpoint(string dsn)
|
||||
{
|
||||
if (!Uri.TryCreate(dsn.Trim(), UriKind.Absolute, out var uri))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"{ObservabilityOptions.SectionName}:SentryDsn is not a valid absolute URI.");
|
||||
}
|
||||
|
||||
var projectId = uri.AbsolutePath.Trim('/');
|
||||
if (projectId.Length == 0)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"{ObservabilityOptions.SectionName}:SentryDsn does not contain a project id.");
|
||||
}
|
||||
|
||||
return new Uri($"{uri.Scheme}://{uri.Host}/api/{projectId}/envelope/");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using SlpModularCms.Core.Observability;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Security;
|
||||
|
||||
@@ -30,18 +31,18 @@ public sealed class AdminTokenValidator : IAdminTokenValidator
|
||||
_validationParameters = validationParameters ?? throw new ArgumentNullException(nameof(validationParameters));
|
||||
}
|
||||
|
||||
public bool IsVerifiedAdmin(string? authorizationHeader)
|
||||
public AdminTokenResult Validate(string? authorizationHeader)
|
||||
{
|
||||
if (string.IsNullOrEmpty(authorizationHeader) ||
|
||||
!authorizationHeader.StartsWith(BearerPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
return Rejected(BypassRejectionReason.Absent);
|
||||
}
|
||||
|
||||
var token = authorizationHeader[BearerPrefix.Length..].Trim();
|
||||
if (token.Length == 0)
|
||||
{
|
||||
return false;
|
||||
return Rejected(BypassRejectionReason.Absent);
|
||||
}
|
||||
|
||||
ClaimsPrincipal principal;
|
||||
@@ -52,13 +53,34 @@ public sealed class AdminTokenValidator : IAdminTokenValidator
|
||||
// whether to serve is this component's job; returning 401 is not.
|
||||
principal = _handler.ValidateToken(token, _validationParameters, out _);
|
||||
}
|
||||
catch (Exception)
|
||||
catch (Exception ex)
|
||||
{
|
||||
return false;
|
||||
return Rejected(Classify(ex));
|
||||
}
|
||||
|
||||
return AdminRoles.Any(role => principal.IsInRole(role))
|
||||
|| principal.FindAll(ClaimTypes.Role).Any(c => AdminRoles.Contains(c.Value))
|
||||
|| principal.FindAll("role").Any(c => AdminRoles.Contains(c.Value));
|
||||
var isAdmin = AdminRoles.Any(role => principal.IsInRole(role))
|
||||
|| principal.FindAll(ClaimTypes.Role).Any(c => AdminRoles.Contains(c.Value))
|
||||
|| principal.FindAll("role").Any(c => AdminRoles.Contains(c.Value));
|
||||
|
||||
return isAdmin
|
||||
? new AdminTokenResult(true, default)
|
||||
: Rejected(BypassRejectionReason.NotAdmin);
|
||||
}
|
||||
|
||||
private static AdminTokenResult Rejected(BypassRejectionReason reason) => new(false, reason);
|
||||
|
||||
/// <summary>
|
||||
/// Maps a validation exception onto a reason class. The exception type is the only thing
|
||||
/// inspected — never the token, and never the exception message, which can quote it.
|
||||
/// </summary>
|
||||
private static BypassRejectionReason Classify(Exception exception) => exception switch
|
||||
{
|
||||
SecurityTokenExpiredException => BypassRejectionReason.Expired,
|
||||
// Covers SecurityTokenSignatureKeyNotFoundException too, which derives from it — a key
|
||||
// that cannot be found and a signature that does not verify are the same signal here.
|
||||
SecurityTokenInvalidSignatureException => BypassRejectionReason.InvalidSignature,
|
||||
SecurityTokenInvalidIssuerException => BypassRejectionReason.WrongIssuer,
|
||||
SecurityTokenInvalidAudienceException => BypassRejectionReason.WrongAudience,
|
||||
_ => BypassRejectionReason.Malformed
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
using SlpModularCms.Core.Observability;
|
||||
|
||||
namespace SlpModularCms.Core.Hosting.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Outcome of validating an admin bypass token.
|
||||
/// </summary>
|
||||
/// <param name="IsVerifiedAdmin">True only for a fully valid Owner or Administrator token.</param>
|
||||
/// <param name="Reason">
|
||||
/// Why a rejected token was rejected; meaningless when <paramref name="IsVerifiedAdmin"/> is true.
|
||||
/// Never the token or any part of it.
|
||||
/// </param>
|
||||
public readonly record struct AdminTokenResult(bool IsVerifiedAdmin, BypassRejectionReason Reason);
|
||||
|
||||
/// <summary>
|
||||
/// Decides whether a request carries a genuinely valid Owner or Administrator token.
|
||||
/// </summary>
|
||||
@@ -12,13 +24,25 @@ namespace SlpModularCms.Core.Hosting.Security;
|
||||
public interface IAdminTokenValidator
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns true only when the supplied Authorization header contains a bearer token that
|
||||
/// validates successfully and carries the Owner or Administrator role.
|
||||
/// Validates the supplied Authorization header and reports both the decision and, on
|
||||
/// rejection, its cause.
|
||||
/// </summary>
|
||||
/// <param name="authorizationHeader">Raw Authorization header value; may be null or empty.</param>
|
||||
/// <returns>
|
||||
/// True when the caller is a verified Owner or Administrator; false in every other case,
|
||||
/// including an absent, malformed, forged, expired or non-admin token. Never throws.
|
||||
/// A verified-admin result only for a bearer token that validates successfully and carries the
|
||||
/// Owner or Administrator role. Every other case — absent, malformed, forged, expired or
|
||||
/// non-admin — is a rejection with a reason. Never throws.
|
||||
/// </returns>
|
||||
bool IsVerifiedAdmin(string? authorizationHeader);
|
||||
/// <remarks>
|
||||
/// <b>Deliberately the only method on this interface.</b> An earlier shape had a plain
|
||||
/// boolean overload alongside this one, and the difference was invisible at a call site: a
|
||||
/// caller using the boolean form got the right access decision and silently emitted no
|
||||
/// security event. One method means the reason cannot be skipped by accident.
|
||||
///
|
||||
/// The reason class matters operationally:
|
||||
/// <see cref="BypassRejectionReason.InvalidSignature"/> suggests forgery, while
|
||||
/// <see cref="BypassRejectionReason.Expired"/> is usually an administrator with a stale tab,
|
||||
/// and an alert that cannot tell those apart is one nobody acts on.
|
||||
/// </remarks>
|
||||
AdminTokenResult Validate(string? authorizationHeader);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization.Policy;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
@@ -7,6 +8,7 @@ using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using SlpModularCms.Core.Availability;
|
||||
using SlpModularCms.Core.Data;
|
||||
@@ -16,6 +18,8 @@ using SlpModularCms.Core.Identity.Authorization;
|
||||
using SlpModularCms.Core.Identity.Entities;
|
||||
using SlpModularCms.Core.Identity.Models;
|
||||
using SlpModularCms.Core.Identity.Services;
|
||||
using SlpModularCms.Core.Hosting.Observability;
|
||||
using SlpModularCms.Core.Observability;
|
||||
using System.Threading.RateLimiting;
|
||||
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -86,6 +90,11 @@ public static class ServiceCollectionExtensions
|
||||
|
||||
services.AddSingleton<IAuthorizationHandler, HierarchicalRoleHandler>();
|
||||
|
||||
// Observes the final authorization result so a denial becomes an alertable event.
|
||||
// Replaces the framework's handler and delegates straight back to it — the response is
|
||||
// unchanged.
|
||||
services.AddSingleton<IAuthorizationMiddlewareResultHandler, SecurityAuthorizationResultHandler>();
|
||||
|
||||
// 6. Exception Handling
|
||||
services.AddExceptionHandler<GlobalExceptionHandler>();
|
||||
services.AddProblemDetails();
|
||||
@@ -126,6 +135,24 @@ public static class ServiceCollectionExtensions
|
||||
{
|
||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||
|
||||
// Without this callback a brute-force attempt against /api/v1/Auth/login returns 429
|
||||
// and leaves NO trace anywhere — the one rate limiter this application has would be
|
||||
// entirely unobservable, and the alert rule for it could never fire.
|
||||
options.OnRejected = (context, _) =>
|
||||
{
|
||||
var logger = context.HttpContext.RequestServices
|
||||
.GetRequiredService<ILoggerFactory>()
|
||||
.CreateLogger(typeof(ServiceCollectionExtensions).FullName!);
|
||||
|
||||
SecurityEvents.RateLimitTriggered(
|
||||
logger,
|
||||
context.HttpContext.GetEndpoint()?.Metadata
|
||||
.GetMetadata<EnableRateLimitingAttribute>()?.PolicyName ?? "(unknown)",
|
||||
context.HttpContext.Request.Path);
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
};
|
||||
|
||||
options.AddFixedWindowLimiter("login", opt =>
|
||||
{
|
||||
var settings = configuration.GetSection("RateLimiting:Login");
|
||||
@@ -142,6 +169,17 @@ public static class ServiceCollectionExtensions
|
||||
opt.SegmentsPerWindow = 4;
|
||||
opt.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 =>
|
||||
{
|
||||
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 services;
|
||||
|
||||
Reference in New Issue
Block a user