fix(security): Phase 4 edge hardening + SSRF egress guard
Backend security fixes from the Phase 1 register / Phase 2 roadmap (PR1 + V-01): - V-01 SSRF: new SafeHttpGuard validates outbound unsubscribe URLs (scheme allowlist + DNS-resolve-and-block private/loopback/link-local/ULA/metadata ranges), wired into UnsubscribeService; the "unsubscribe" HttpClient now disables auto-redirect so a validated external URL can't 3xx into an internal target. +33 unit tests. - V-04: session cookie SecurePolicy=Always in non-dev (SameAsRequest in dev). - V-06: UseExceptionHandler/ProblemDetails in prod; Cleanup/Unsubscribe no longer echo ex.Message to clients (logged server-side, generic message returned). - V-08: ForwardedHeaders trusted only from configurable KnownNetworks (default private ranges) + ForwardLimit, instead of trusting any client. New ForwardedHeaders config. - V-09: returnUrl validated with Url.IsLocalUrl (no open redirect via OAuth flow). - V-10: SearchService clamps Page/PageSize (<=200); Analytics clamps take/days. - V-11: baseline security headers (nosniff, X-Frame-Options DENY, Referrer-Policy, COOP) + HSTS in prod. - V-13: /app/info discloses only devMode to anonymous callers unless dev mode is on. - V-12: API container runs as non-root 'app' user (keys dir pre-owned). - V-03: Postgres + API ports bound to 127.0.0.1; POSTGRES_PASSWORD now required (no weak default fallback). API compatibility preserved (clamps not rejections; error-body shape changes only on failure paths). No DB migrations. Build + all 33 unit tests green. V-15 (MailKit NU1902) persists across versions and the SMTP path is default-off — tracked, not bumped. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -16,11 +16,13 @@ public class AnalyticsController : ApiControllerBase
|
||||
|
||||
[HttpGet("top-senders")]
|
||||
public async Task<IActionResult> TopSenders([FromQuery] int take = 20, CancellationToken ct = default)
|
||||
=> Ok(await _analytics.GetTopSendersAsync(UserId, take, ct));
|
||||
// V-10: clamp to a sane bound (the SPA legitimately requests up to 5000 to list
|
||||
// all senders) so a caller cannot force an unbounded scan.
|
||||
=> Ok(await _analytics.GetTopSendersAsync(UserId, Math.Clamp(take, 1, 5000), ct));
|
||||
|
||||
[HttpGet("volume")]
|
||||
public async Task<IActionResult> Volume([FromQuery] int days = 90, CancellationToken ct = default)
|
||||
=> Ok(await _analytics.GetVolumeOverTimeAsync(UserId, days, ct));
|
||||
=> Ok(await _analytics.GetVolumeOverTimeAsync(UserId, Math.Clamp(days, 1, 3660), ct));
|
||||
|
||||
[HttpGet("heatmap")]
|
||||
public async Task<IActionResult> Heatmap(CancellationToken ct) => Ok(await _analytics.GetHeatmapAsync(UserId, ct));
|
||||
|
||||
@@ -28,10 +28,17 @@ public class AppInfoController : ControllerBase
|
||||
public IActionResult Info()
|
||||
{
|
||||
var devMode = _config.GetValue<bool?>("App:DevMode") ?? _env.IsDevelopment();
|
||||
// V-13: when NOT in dev mode, disclose nothing beyond the flag to anonymous
|
||||
// callers. The dev banner (the only consumer of environment/maxMessages) only
|
||||
// renders when devMode is true, so this preserves the feature without leaking
|
||||
// the environment name or sync cap in production.
|
||||
if (!devMode)
|
||||
return Ok(new { devMode = false });
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
devMode = true,
|
||||
environment = _env.EnvironmentName,
|
||||
devMode,
|
||||
maxMessages = _config.GetValue<int>("GmailSync:MaxMessages")
|
||||
});
|
||||
}
|
||||
|
||||
@@ -17,7 +17,12 @@ public class AuthController : ControllerBase
|
||||
[HttpGet("login")]
|
||||
[AllowAnonymous]
|
||||
public IActionResult Login([FromQuery] string? returnUrl = "/")
|
||||
=> Challenge(new AuthenticationProperties { RedirectUri = returnUrl }, GoogleDefaults.AuthenticationScheme);
|
||||
{
|
||||
// V-09: only allow local post-login redirects; reject absolute/off-host targets
|
||||
// so the OAuth flow can't be abused as an open redirect for phishing.
|
||||
var safe = !string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) ? returnUrl : "/app";
|
||||
return Challenge(new AuthenticationProperties { RedirectUri = safe }, GoogleDefaults.AuthenticationScheme);
|
||||
}
|
||||
|
||||
[HttpPost("logout")]
|
||||
[Authorize]
|
||||
|
||||
@@ -16,5 +16,13 @@ RUN dotnet publish src/InboxIntel.Api/InboxIntel.Api.csproj -c Release -o /app/p
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/publish .
|
||||
|
||||
# V-12: run as the non-root 'app' user shipped in the .NET 8 images. Pre-create the
|
||||
# DataProtection key directory owned by that user so the (initially empty) 'keys'
|
||||
# volume inherits app ownership on first mount and key persistence still works.
|
||||
# NOTE: an EXISTING root-owned keys volume must be recreated for this to take effect.
|
||||
RUN mkdir -p /keys && chown -R app:app /keys /app
|
||||
USER app
|
||||
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["dotnet", "InboxIntel.Api.dll"]
|
||||
|
||||
@@ -48,6 +48,12 @@ builder.Services.AddAuthentication(options =>
|
||||
{
|
||||
options.Cookie.HttpOnly = true;
|
||||
options.Cookie.SameSite = SameSiteMode.Lax;
|
||||
// V-04: never emit the session cookie over plain HTTP in non-dev. Behind nginx
|
||||
// the forwarded proto (now only trusted from known proxies, see below) makes
|
||||
// Always work; local http://localhost dev still functions via SameAsRequest.
|
||||
options.Cookie.SecurePolicy = builder.Environment.IsDevelopment()
|
||||
? CookieSecurePolicy.SameAsRequest
|
||||
: CookieSecurePolicy.Always;
|
||||
options.Cookie.Name = "inboxintel.session";
|
||||
options.ExpireTimeSpan = TimeSpan.FromDays(7);
|
||||
options.SlidingExpiration = true;
|
||||
@@ -94,6 +100,9 @@ builder.Services.AddApiVersioning(o =>
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
// V-06: RFC7807 ProblemDetails so the global exception handler returns a safe,
|
||||
// generic error body instead of leaking framework stack traces / internal messages.
|
||||
builder.Services.AddProblemDetails();
|
||||
|
||||
builder.Services.AddCors(o => o.AddPolicy("frontend", p => p
|
||||
.WithOrigins(builder.Configuration.GetSection("Cors:Origins").Get<string[]>() ?? new[] { "http://localhost:5173" })
|
||||
@@ -109,21 +118,53 @@ using (var scope = app.Services.CreateScope())
|
||||
await db.Database.MigrateAsync();
|
||||
}
|
||||
|
||||
// Honor X-Forwarded-* from the nginx reverse proxy so OAuth redirect URIs and
|
||||
// cookie Secure flags reflect the external scheme/host, not the container's.
|
||||
// V-08: only trust these headers from KNOWN proxy networks (configurable). The
|
||||
// default covers private/Docker ranges so the compose nginx works, while a client
|
||||
// reaching the API directly can no longer spoof scheme/host/forwarded-for.
|
||||
var forwardedOptions = new ForwardedHeadersOptions
|
||||
{
|
||||
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost,
|
||||
ForwardLimit = app.Configuration.GetValue<int?>("ForwardedHeaders:ForwardLimit") ?? 1
|
||||
};
|
||||
forwardedOptions.KnownNetworks.Clear();
|
||||
forwardedOptions.KnownProxies.Clear();
|
||||
var trustedNetworks = app.Configuration.GetSection("ForwardedHeaders:KnownNetworks").Get<string[]>()
|
||||
?? new[] { "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.0/8", "::1/128" };
|
||||
foreach (var cidr in trustedNetworks)
|
||||
{
|
||||
var parts = cidr.Split('/');
|
||||
if (parts.Length == 2 && System.Net.IPAddress.TryParse(parts[0], out var prefix) && int.TryParse(parts[1], out var len))
|
||||
forwardedOptions.KnownNetworks.Add(new Microsoft.AspNetCore.HttpOverrides.IPNetwork(prefix, len));
|
||||
}
|
||||
app.UseForwardedHeaders(forwardedOptions);
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
// Honor X-Forwarded-* from the nginx reverse proxy so OAuth redirect URIs and
|
||||
// cookie Secure flags reflect the external scheme/host, not the container's.
|
||||
var forwardedOptions = new ForwardedHeadersOptions
|
||||
else
|
||||
{
|
||||
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost
|
||||
};
|
||||
forwardedOptions.KnownNetworks.Clear();
|
||||
forwardedOptions.KnownProxies.Clear();
|
||||
app.UseForwardedHeaders(forwardedOptions);
|
||||
// V-06: generic ProblemDetails for unhandled exceptions (no stack traces to clients).
|
||||
app.UseExceptionHandler();
|
||||
// V-11: HSTS once TLS is enforced at the proxy (forwarded proto now trustworthy).
|
||||
app.UseHsts();
|
||||
}
|
||||
|
||||
// V-11: baseline security response headers. CSP is report-only for now so it can be
|
||||
// tuned against the SPA before enforcing (the SPA itself is also served with headers
|
||||
// by its nginx). Applied to API responses here as defense-in-depth.
|
||||
app.Use(async (ctx, next) =>
|
||||
{
|
||||
var h = ctx.Response.Headers;
|
||||
h["X-Content-Type-Options"] = "nosniff";
|
||||
h["X-Frame-Options"] = "DENY";
|
||||
h["Referrer-Policy"] = "no-referrer";
|
||||
h["Cross-Origin-Opener-Policy"] = "same-origin";
|
||||
await next();
|
||||
});
|
||||
|
||||
app.UseSerilogRequestLogging();
|
||||
app.UseCors("frontend");
|
||||
|
||||
@@ -51,6 +51,10 @@
|
||||
"FrequencyDays": 7,
|
||||
"SendHourUtc": 8
|
||||
},
|
||||
"ForwardedHeaders": {
|
||||
"ForwardLimit": 1,
|
||||
"KnownNetworks": [ "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.0/8", "::1/128" ]
|
||||
},
|
||||
"Cors": {
|
||||
"Origins": [ "http://localhost:5173" ]
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user