Harden backend auth, validation and error handling

- Rate limit login (5 attempts/min per IP) with a JSON 429 response
- Constant-time password comparison; refuse login if no password is configured
- Explicit SameSite=Strict auth cookie; log failed logins with client IP
- Stop logging door codes (update log lines and the SMS body)
- Replace per-action try/catch -> 400 with a global exception handler (JSON 500)
- Return proper statuses: 404 for missing person, 502 for failed lock writes
- Validate codes as ASCII digits only (int.TryParse accepted +/-/whitespace)
- Validate person name and E.164 phone number; reject sending an unset code
- Rename TwiloOptions -> TwilioOptions and fix message typos
- Expose Program for integration tests
This commit is contained in:
LiamPietralla committed 2026-11-16 12:23:31 +11:00
1 parent 768bcc90e4
commit d0425c8cb2
38 files changed
+189 -487

No files matched your search

+45 -1
View File
@@ -1,8 +1,12 @@
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.EntityFrameworkCore;
using System.Threading.RateLimiting;
using OpenTelemetry.Logs;
using YaleAccess.Controllers;
using YaleAccess.Data;
using YaleAccess.Models;
using YaleAccess.Models.Options;
using YaleAccess.Services;
using YaleAccess.Services.Interfaces;
@@ -42,7 +46,7 @@ try
builder.Services.Configure<CodesOptions>(builder.Configuration.GetSection(CodesOptions.Codes));
builder.Services.Configure<DevicesOptions>(builder.Configuration.GetSection(DevicesOptions.Devices));
builder.Services.Configure<ZWaveOptions>(builder.Configuration.GetSection(ZWaveOptions.ZWave));
builder.Services.Configure<TwiloOptions>(builder.Configuration.GetSection(TwiloOptions.Twilio));
builder.Services.Configure<TwilioOptions>(builder.Configuration.GetSection(TwilioOptions.Twilio));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
@@ -86,6 +90,9 @@ try
// Set HTTP only to true to prevent XSS attacks
options.Cookie.HttpOnly = true;
// The frontend and API are served from the same site, so strict SameSite blocks cross-site (CSRF) requests
options.Cookie.SameSite = SameSiteMode.Strict;
// Set secure policy to always to prevent sending cookies over HTTP for production use, for development set to None
if (builder.Environment.IsDevelopment())
options.Cookie.SecurePolicy = CookieSecurePolicy.None;
@@ -102,6 +109,26 @@ try
};
});
// Rate limit login attempts per client IP to slow down password guessing
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy(AuthenticationController.LoginRateLimitPolicy, context =>
RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1),
QueueLimit = 0
}));
options.OnRejected = async (context, token) =>
{
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
await context.HttpContext.Response.WriteAsJsonAsync(new ApiResponse("Too many login attempts. Please wait a minute and try again."), token);
};
});
var app = builder.Build();
// Create the database if it doesn't exist
@@ -129,10 +156,24 @@ try
app.UseCors();
// Turn unhandled exceptions into a JSON 500 (after CORS, so the browser can still read the response)
app.UseExceptionHandler(errorApp => errorApp.Run(async context =>
{
var exception = context.Features.Get<IExceptionHandlerFeature>()?.Error;
context.RequestServices.GetRequiredService<ILoggerFactory>()
.CreateLogger("UnhandledException")
.LogError(exception, "An unhandled error occurred handling {Method} {Path}.", context.Request.Method, context.Request.Path);
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
await context.Response.WriteAsJsonAsync(new ApiResponse("An unexpected error occurred."));
}));
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
app.MapControllers();
app.Run();
@@ -147,3 +188,6 @@ catch (Exception ex)
throw;
}
}
// Exposes the entry point to the integration tests (WebApplicationFactory<Program>)
public partial class Program { }