using System.Security.Claims; using System.Threading.RateLimiting; using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Identity; using Npgsql; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.WebUtilities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging.Console; using StatiKosev.Data; using StatiKosev.Logging; namespace StatiKosev; public class Program { public const string AdminScheme = "Admin"; public static async Task Main(string[] arguments) { var builder = WebApplication.CreateBuilder(arguments); var databaseConnectionString = builder.Configuration.GetConnectionString("DefaultConnection"); var messageRateLimitSeconds = builder.Configuration.GetValue("MessageRateLimitSeconds", 10); builder.Services.AddLocalization(o => o.ResourcesPath = "LanguagesValues"); builder.Services.AddRazorPages(); builder.Services.AddControllers(); builder.Services.AddScoped(); builder.Services.AddNpgsqlDataSource(databaseConnectionString); builder.Services.AddDbContext((sp, o) => o.UseNpgsql(sp.GetRequiredService())); // EF shares the same connection pool //builder.Services.AddLogging(); builder.Services.AddDefaultIdentity(o => { o.SignIn.RequireConfirmedAccount = false; // no email sending configured yet o.User.RequireUniqueEmail = true; o.Password.RequiredLength = 8; o.Password.RequireNonAlphanumeric = false; }) .AddRoles() .AddEntityFrameworkStores(); builder.Services.ConfigureApplicationCookie(o => { o.LoginPath = "/Login"; o.AccessDeniedPath = "/"; }); //the admin has no account: the AdminPassword from appsettings.json, entered on /Inbox, signs this separate cookie in builder.Services.AddAuthentication().AddCookie(AdminScheme, o => { o.Cookie.Name = ".StatiKosev.Admin"; o.LoginPath = "/Inbox"; o.AccessDeniedPath = "/Inbox"; o.ExpireTimeSpan = TimeSpan.FromHours(8); o.SlidingExpiration = true; }); builder.Services.AddAuthorizationBuilder() .AddPolicy("AdminOnly", p => p.AddAuthenticationSchemes(AdminScheme).RequireRole("Admin")); //rate limiting for messages builder.Services.AddRateLimiter(o => { o.RejectionStatusCode = StatusCodes.Status429TooManyRequests; o.OnRejected = (ctx, _) => { var http = ctx.HttpContext; if (http.Request.HasFormContentType) { var referer = http.Request.Headers.Referer.ToString(); var path = Uri.TryCreate(referer, UriKind.Absolute, out var uri) && uri.Host == http.Request.Host.Host ? uri.AbsolutePath : "/"; http.Response.Redirect(path + "?wait=1"); } return ValueTask.CompletedTask; }; //password guessing on /Inbox: 5 tries per 15 minutes per IP o.AddPolicy("admin-login", ctx => RateLimitPartition.GetFixedWindowLimiter("ip:" + ctx.Connection.RemoteIpAddress, _ => new FixedWindowRateLimiterOptions { PermitLimit = 5, Window = TimeSpan.FromMinutes(15), QueueLimit = 0 })); o.AddPolicy("contact", ctx => // ← the policy [EnableRateLimiting("contact")] uses { var userId = ctx.User.FindFirstValue(ClaimTypes.NameIdentifier); var key = userId is not null ? "user:" + userId : "ip:" + ctx.Connection.RemoteIpAddress; return RateLimitPartition.GetFixedWindowLimiter(key, _ => new FixedWindowRateLimiterOptions { PermitLimit = 1, Window = TimeSpan.FromSeconds(messageRateLimitSeconds), QueueLimit = 0 }); }); }); builder.Logging.ClearProviders(); builder.Logging.AddConsole(o => o.FormatterName = "color") .AddConsoleFormatter(); Console.WriteLine($"Database connection string: {databaseConnectionString}"); var app = builder.Build(); await DbSeeder.SeedAsync(app.Services); app.UseAntiforgery(); app.UseRateLimiter(); //accounts //safety check if form sends us to the same domain //if starting with / -> u, if null or else -> "/" redirects to Index static string ForceLocalizeUrl(string? u) => !string.IsNullOrEmpty(u) && u.StartsWith('/') && !u.StartsWith("//") && !u.StartsWith("/\\") ? u : "/"; //failed login/register go back to the login page with the reason and the original returnUrl static string LoginPage(string auth, string back) => QueryHelpers.AddQueryString("/Login", new Dictionary { ["auth"] = auth, ["returnUrl"] = back }); var account = app.MapGroup("/account"); account.MapPost("/login", async ([FromForm] string email, [FromForm] string password, [FromForm] string? returnUrl, SignInManager signIn) => { var r = await signIn.PasswordSignInAsync(email, password, isPersistent: true, lockoutOnFailure: true); var back = ForceLocalizeUrl(returnUrl); return Results.LocalRedirect(r.Succeeded ? back : LoginPage("login-failed", back)); }); account.MapPost("/register", async ([FromForm] string email, [FromForm] string password, [FromForm] string? returnUrl, UserManager users, SignInManager signIn) => { var back = ForceLocalizeUrl(returnUrl); var user = new IdentityUser { UserName = email, Email = email }; var res = await users.CreateAsync(user, password); if (!res.Succeeded) return Results.LocalRedirect(LoginPage("register-failed", back)); await users.AddToRoleAsync(user, DbSeeder.UserRole); await signIn.SignInAsync(user, isPersistent: true); return Results.LocalRedirect(back); }); account.MapPost("/logout", async (SignInManager signIn) => { await signIn.SignOutAsync(); return Results.LocalRedirect("/"); }).WithMetadata(new RequireAntiforgeryTokenAttribute()); //accounts end app.UseRequestLocalization(o => o .SetDefaultCulture("bg") .AddSupportedCultures("bg", "en") .AddSupportedUICultures("bg", "en")); app.UseStaticFiles(); // CSS/JS/images from wwwroot app.MapRazorPages(); app.MapControllers(); //get version of database the software is configured to work with (appsettings.json) app.MapGet("/db_version", async (NpgsqlDataSource db) => { await using var cmd = db.CreateCommand("SELECT version()"); var version = await cmd.ExecuteScalarAsync(); Console.WriteLine("db_version api called and returned==" + version); return version; }); app.MapGet("/set-language", (string culture, string? returnUrl, HttpContext ctx) => { ctx.Response.Cookies.Append( CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)), new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1), IsEssential = true }); return Results.LocalRedirect(string.IsNullOrEmpty(returnUrl) ? "/" : returnUrl); }); app.MapStaticAssets(); app.MapGet("/_res", () => string.Join("\n", typeof(StatiKosev.StringValues).Assembly.GetManifestResourceNames())); app.Logger.LogInformation("Configured message rate limit secs==" + messageRateLimitSeconds); app.Logger.LogInformation("Application started!"); app.Run(); } }