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(options => { options.UseSqlite(builder.Configuration.GetConnectionString(nameof(YaleContext))); }); // Configure the options builder.Services.Configure(builder.Configuration.GetSection(AuthenticationOptions.Authentication)); builder.Services.Configure(builder.Configuration.GetSection(CodesOptions.Codes)); builder.Services.Configure(builder.Configuration.GetSection(DevicesOptions.Devices)); builder.Services.Configure(builder.Configuration.GetSection(ZWaveOptions.ZWave)); builder.Services.Configure(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(); // If the environment is development and the mock option is set to true, use the mock service if (builder.Environment.IsDevelopment() && configuration.GetValue("UseMockDevelopmentMode")) { builder.Services.AddSingleton(); builder.Services.AddSingleton(); } else { builder.Services.AddSingleton(); } // 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(); 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()?.Error; context.RequestServices.GetRequiredService() .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) public partial class Program { }