diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs index bca499b..1633981 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs @@ -18,15 +18,18 @@ public static class DependencyInjection if (string.IsNullOrEmpty(connectionString)) return services; -#pragma warning disable CS0618 +// CS0618: UsePostgreSqlStorage is marked obsolete in Hangfire.PostgreSql 1.20.x. + // Upgrade to Hangfire.PostgreSql 2.x when available which uses SCHEMA-based storage. + // Track: https://github.com/HangfireStorage/Hangfire.PostgreSql/issues services.AddHangfire(config => { +#pragma warning disable CS0618 config.UsePostgreSqlStorage(connectionString, new PostgreSqlStorageOptions { SchemaName = "hangfire" }); - }); #pragma warning restore CS0618 + }); services.AddHangfireServer(options => { diff --git a/src/Heimdall.Infrastructure/Security/CredentialProtector.cs b/src/Heimdall.Infrastructure/Security/CredentialProtector.cs index c65f93b..c62ab06 100644 --- a/src/Heimdall.Infrastructure/Security/CredentialProtector.cs +++ b/src/Heimdall.Infrastructure/Security/CredentialProtector.cs @@ -33,7 +33,7 @@ public sealed class DataProtectorCredentialProtector : ICredentialProtector var unprotectedBytes = _protector.Unprotect(protectedBytes); return Encoding.UTF8.GetString(unprotectedBytes); } - catch + catch (Exception) when (!string.IsNullOrEmpty(ciphertext)) { // If data is not encrypted (plaintext fallback for migration), // return as-is. This prevents data loss if the protector is diff --git a/src/Heimdall.Web/Filters/ExceptionFilter.cs b/src/Heimdall.Web/Filters/ExceptionFilter.cs index 2bfcd16..1c0470f 100644 --- a/src/Heimdall.Web/Filters/ExceptionFilter.cs +++ b/src/Heimdall.Web/Filters/ExceptionFilter.cs @@ -1,7 +1,7 @@ using System.Net; -using Heimdall.Application.Common; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.EntityFrameworkCore; namespace Heimdall.Api.Filters; @@ -15,18 +15,19 @@ public class ExceptionFilter : IExceptionFilter { _logger.LogError(context.Exception, "Unhandled exception: {Message}", context.Exception.Message); - var response = new + var (statusCode, code, message) = context.Exception switch { - error = new - { - code = "InternalServerError", - message = "An unexpected error occurred" - } + DbUpdateConcurrencyException => (409, "ConcurrencyConflict", "The record was modified by another user. Reload and try again."), + OperationCanceledException => (499, "RequestCancelled", "The request was cancelled."), + _ => (500, "InternalServerError", "An unexpected error occurred") }; - context.Result = new ObjectResult(response) + context.Result = new ObjectResult(new { - StatusCode = (int)HttpStatusCode.InternalServerError + error = new { code, message } + }) + { + StatusCode = statusCode }; context.ExceptionHandled = true; diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 4b3dd47..eff2005 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -41,6 +41,11 @@ var migrateOnStartup = builder.Configuration.GetValue("Database:MigrateOn ?? app.Environment.IsProduction(); if (migrateOnStartup) { + // Use a 5-minute overall timeout so startup doesn't hang indefinitely + // if the database is unreachable. Each retry respects this token. + using var migrationCts = new CancellationTokenSource(TimeSpan.FromMinutes(5)); + var migrationCt = migrationCts.Token; + using (var scope = app.Services.CreateScope()) { var logger = scope.ServiceProvider.GetRequiredService>(); @@ -52,17 +57,23 @@ if (migrateOnStartup) { try { + migrationCt.ThrowIfCancellationRequested(); logger.LogInformation("Applying database migrations (attempt {Attempt}/{MaxRetries})...", attempt, maxRetries); db.Database.Migrate(); logger.LogInformation("Database migrations applied successfully"); break; } + catch (OperationCanceledException) + { + logger.LogCritical("Database migration timed out after 5 minutes."); + throw; + } catch (Exception ex) when (attempt < maxRetries) { logger.LogWarning(ex, "Database migration attempt {Attempt}/{MaxRetries} failed. Retrying in {Delay}s...", attempt, maxRetries, retryDelay.TotalSeconds); - await Task.Delay(retryDelay); + await Task.Delay(retryDelay, migrationCt); retryDelay = TimeSpan.FromSeconds(retryDelay.TotalSeconds * 2); } catch (Exception ex) @@ -136,7 +147,10 @@ using (var seedScope = app.Services.CreateScope()) Email = "admin@heimdall.test", DisplayName = "Admin" }; - await userManager.CreateAsync(testAdmin, "Admin123!Pass"); + var adminPassword = builder.Configuration["Seed:AdminPassword"] + ?? Environment.GetEnvironmentVariable("SEED__ADMIN_PASSWORD") + ?? "Admin123!Pass"; + await userManager.CreateAsync(testAdmin, adminPassword); await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin); } @@ -366,7 +380,11 @@ public partial class Program { app.UseHsts(); } - // Only enable HTTPS redirection if HTTPS is actually configured + // Only enable HTTPS redirection if HTTPS is actually configured on Kestrel. + // In production behind a reverse proxy (nginx, Traefik, Caddy), TLS is + // terminated at the proxy level — Kestrel runs on HTTP internally, so + // this block is intentionally skipped (ASPNETCORE_URLS has no https://). + // The proxy handles the HTTP to HTTPS redirect. var urls = Environment.GetEnvironmentVariable("ASPNETCORE_URLS") ?? ""; if (urls.Contains("https://", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/Heimdall.Web/appsettings.json b/src/Heimdall.Web/appsettings.json index 86beff1..82d0a8f 100644 --- a/src/Heimdall.Web/appsettings.json +++ b/src/Heimdall.Web/appsettings.json @@ -6,5 +6,5 @@ } }, "AllowedHosts": "*", - "ApiBaseUrl": "http://localhost:5000" + "ApiBaseUrl": "http://localhost:8080" }