Files
yale-user-access/packages/backend/Program.cs
T
LiamPietralla d0425c8cb2 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
2026-11-16 12:23:31 +11:00

194 lines
6.9 KiB
C#

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;
var builder = WebApplication.CreateBuilder(args);
try
{
var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
builder.Logging.AddOpenTelemetry(logging =>
{
logging.IncludeFormattedMessage = true;
logging.IncludeScopes = true;
if (useOtlpExporter)
{
logging.AddOtlpExporter();
}
else
{
Console.WriteLine("OTEL_EXPORTER_OTLP_ENDPOINT is not set. Skipping OTLP exporter configuration.");
}
});
// Add services to the container.
builder.Services.AddControllers();
// Add the database context
builder.Services.AddDbContext<YaleContext>(options =>
{
options.UseSqlite(builder.Configuration.GetConnectionString(nameof(YaleContext)));
});
// Configure the options
builder.Services.Configure<AuthenticationOptions>(builder.Configuration.GetSection(AuthenticationOptions.Authentication));
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<TwilioOptions>(builder.Configuration.GetSection(TwilioOptions.Twilio));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Get a copy of the configuration
IConfiguration configuration = builder.Configuration;
// Configure the DI services
builder.Services.AddScoped<SMSService>();
// If the environment is development and the mock option is set to true, use the mock service
if (builder.Environment.IsDevelopment() && configuration.GetValue<bool>("UseMockDevelopmentMode"))
{
builder.Services.AddSingleton<MockYaleData>();
builder.Services.AddSingleton<IYaleAccessor, MockYaleAccessor>();
}
else
{
builder.Services.AddSingleton<IYaleAccessor, YaleAccessor>();
}
// Setup CORS
string[] corsAllowedOrigins = (configuration["CorsAllowedOrigins"] ?? "http://localhost:3000").Split(",") ;
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.WithOrigins(corsAllowedOrigins)
.AllowCredentials()
.AllowAnyMethod()
.WithHeaders("Content-Type", "Authorization");
});
});
// Setup cookie authentication scheme
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
// 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;
else
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
// Ensure that the API will return a 401 Unauthorized instead of redirecting to the login page
options.AccessDeniedPath = string.Empty;
options.LoginPath = string.Empty;
options.Events.OnRedirectToLogin = context =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
});
// 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
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<YaleContext>();
context.Database.Migrate();
}
// Configure the forwarded headers middleware
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
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();
}
catch (Exception ex)
{
// Ignore host aborted exceptions caused by build checks
if (ex is not HostAbortedException)
{
Console.WriteLine("Host terminated unexpectedly");
throw;
}
}
// Exposes the entry point to the integration tests (WebApplicationFactory<Program>)
public partial class Program { }