2026-07-16 20:53:56 +00:00
|
|
|
using System.Text;
|
2026-07-17 06:57:00 +00:00
|
|
|
using Microsoft.AspNetCore.RateLimiting;
|
2026-07-17 17:45:44 +00:00
|
|
|
using Scalar.AspNetCore;
|
2026-07-16 20:53:56 +00:00
|
|
|
using Heimdall.Api.Filters;
|
|
|
|
|
using Heimdall.Application;
|
2026-07-19 15:24:52 +00:00
|
|
|
using Heimdall.Application.Services;
|
2026-07-16 20:53:56 +00:00
|
|
|
using Heimdall.Infrastructure;
|
2026-07-18 18:58:20 +00:00
|
|
|
using Heimdall.Api.Hubs;
|
2026-07-16 20:53:56 +00:00
|
|
|
using Heimdall.Infrastructure.Data;
|
|
|
|
|
using Heimdall.Infrastructure.Security;
|
|
|
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
|
|
2026-07-19 19:33:10 +00:00
|
|
|
// ── Sentry (GlitchTip) — DSN from env var only ───────────────────
|
|
|
|
|
var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN");
|
2026-07-18 19:41:57 +00:00
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
2026-07-18 19:41:57 +00:00
|
|
|
|
|
|
|
|
// ── Sentry ────────────────────────────────────────────────────────
|
2026-07-19 19:33:10 +00:00
|
|
|
if (sentryDsn is not null)
|
2026-07-18 19:41:57 +00:00
|
|
|
{
|
2026-07-19 19:33:10 +00:00
|
|
|
builder.WebHost.UseSentry(options =>
|
|
|
|
|
{
|
|
|
|
|
options.Dsn = sentryDsn;
|
|
|
|
|
options.MinimumBreadcrumbLevel = LogLevel.Debug;
|
|
|
|
|
options.MinimumEventLevel = LogLevel.Error;
|
|
|
|
|
options.TracesSampleRate = 0.1;
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-07-16 19:09:28 +00:00
|
|
|
|
2026-07-17 06:57:00 +00:00
|
|
|
// ── Rate Limiting (Polly/System.Threading.RateLimiting) ───────────
|
|
|
|
|
builder.Services.AddRateLimiter(options =>
|
|
|
|
|
{
|
|
|
|
|
options.RejectionStatusCode = 429;
|
|
|
|
|
|
|
|
|
|
options.AddFixedWindowLimiter("Auth", opt =>
|
|
|
|
|
{
|
|
|
|
|
opt.PermitLimit = 10;
|
|
|
|
|
opt.Window = TimeSpan.FromMinutes(1);
|
|
|
|
|
opt.QueueLimit = 0;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
options.AddFixedWindowLimiter("Api", opt =>
|
|
|
|
|
{
|
|
|
|
|
opt.PermitLimit = 200;
|
|
|
|
|
opt.Window = TimeSpan.FromMinutes(1);
|
|
|
|
|
opt.QueueLimit = 0;
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-16 20:53:56 +00:00
|
|
|
// ── Services ──────────────────────────────────────────────────────
|
|
|
|
|
|
2026-07-16 21:19:16 +00:00
|
|
|
if (!builder.Environment.IsEnvironment("Testing"))
|
2026-07-16 20:53:56 +00:00
|
|
|
{
|
2026-07-16 21:19:16 +00:00
|
|
|
builder.Services.AddControllers(options =>
|
|
|
|
|
{
|
|
|
|
|
options.Filters.Add<ExceptionFilter>();
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
builder.Services.AddControllers();
|
|
|
|
|
}
|
2026-07-16 19:09:28 +00:00
|
|
|
|
2026-07-19 15:49:46 +00:00
|
|
|
// Global JSON serialization — string enums for API responses
|
|
|
|
|
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(opts =>
|
|
|
|
|
{
|
|
|
|
|
opts.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-18 18:58:20 +00:00
|
|
|
builder.Services.AddSignalR();
|
2026-07-19 15:24:52 +00:00
|
|
|
builder.Services.AddScoped<IEventBroadcastService, EventBroadcastService>();
|
2026-07-18 18:58:20 +00:00
|
|
|
builder.Services.AddScoped<IConfigBroadcastService, ConfigBroadcastService>();
|
|
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
builder.Services.AddOpenApi();
|
|
|
|
|
|
2026-07-16 20:53:56 +00:00
|
|
|
// ── Application layer ─────────────────────────────────────────────
|
|
|
|
|
builder.Services.AddApplication();
|
|
|
|
|
|
|
|
|
|
// ── Infrastructure layer ──────────────────────────────────────────
|
2026-07-16 21:19:16 +00:00
|
|
|
builder.Services.AddInfrastructure(builder.Configuration, builder.Environment.EnvironmentName);
|
2026-07-16 20:53:56 +00:00
|
|
|
|
|
|
|
|
// ── Authentication ────────────────────────────────────────────────
|
|
|
|
|
var jwtKey = builder.Configuration["Jwt:Key"]
|
2026-07-16 21:19:16 +00:00
|
|
|
?? Environment.GetEnvironmentVariable("JWT__KEY")
|
2026-07-16 20:53:56 +00:00
|
|
|
?? throw new InvalidOperationException("JWT:Key is not configured");
|
2026-07-16 21:19:16 +00:00
|
|
|
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall";
|
|
|
|
|
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api";
|
2026-07-16 20:53:56 +00:00
|
|
|
|
|
|
|
|
builder.Services.AddAuthentication(options =>
|
|
|
|
|
{
|
|
|
|
|
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
|
|
|
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
|
|
|
})
|
|
|
|
|
.AddJwtBearer("JwtBearer", options =>
|
|
|
|
|
{
|
|
|
|
|
options.TokenValidationParameters = new TokenValidationParameters
|
|
|
|
|
{
|
|
|
|
|
ValidateIssuerSigningKey = true,
|
|
|
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
|
|
|
|
|
ValidateIssuer = true,
|
|
|
|
|
ValidIssuer = jwtIssuer,
|
|
|
|
|
ValidateAudience = true,
|
|
|
|
|
ValidAudience = jwtAudience,
|
|
|
|
|
ValidateLifetime = true,
|
|
|
|
|
ClockSkew = TimeSpan.Zero
|
|
|
|
|
};
|
2026-07-19 15:49:13 +00:00
|
|
|
|
|
|
|
|
// SignalR WebSocket transport sends JWT as access_token query parameter
|
|
|
|
|
options.Events = new JwtBearerEvents
|
|
|
|
|
{
|
|
|
|
|
OnMessageReceived = context =>
|
|
|
|
|
{
|
|
|
|
|
var accessToken = context.Request.Query["access_token"];
|
|
|
|
|
var path = context.HttpContext.Request.Path;
|
|
|
|
|
|
|
|
|
|
if (!string.IsNullOrEmpty(accessToken) &&
|
|
|
|
|
path.StartsWithSegments("/hubs"))
|
|
|
|
|
{
|
|
|
|
|
context.Token = accessToken;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
|
|
|
|
};
|
2026-07-16 20:53:56 +00:00
|
|
|
})
|
|
|
|
|
.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>("ApiKey", null);
|
|
|
|
|
|
|
|
|
|
// ── Authorization policies ───────────────────────────────────────
|
|
|
|
|
builder.Services.AddAuthorization(options =>
|
|
|
|
|
{
|
|
|
|
|
var allPermissions = AppPermissions.RolePermissions.Values
|
|
|
|
|
.SelectMany(p => p).Distinct();
|
|
|
|
|
|
|
|
|
|
foreach (var permission in allPermissions)
|
|
|
|
|
{
|
|
|
|
|
options.AddPolicy(permission, policy =>
|
|
|
|
|
policy.RequireClaim("permission", permission));
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// ── CORS ──────────────────────────────────────────────────────────
|
|
|
|
|
var allowedOrigins = builder.Configuration["Cors:AllowedOrigins"]?.Split(',')
|
|
|
|
|
?? ["https://localhost:5001"];
|
|
|
|
|
|
|
|
|
|
builder.Services.AddCors(options =>
|
|
|
|
|
{
|
2026-07-16 21:19:16 +00:00
|
|
|
var isWildcard = allowedOrigins.Length == 1 && allowedOrigins[0] == "*";
|
|
|
|
|
if (isWildcard)
|
|
|
|
|
{
|
|
|
|
|
options.AddPolicy("ApiPolicy", policy =>
|
|
|
|
|
policy.AllowAnyOrigin()
|
|
|
|
|
.AllowAnyHeader()
|
|
|
|
|
.AllowAnyMethod());
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
options.AddPolicy("ApiPolicy", policy =>
|
|
|
|
|
policy.WithOrigins(allowedOrigins)
|
|
|
|
|
.AllowCredentials()
|
|
|
|
|
.AllowAnyHeader()
|
|
|
|
|
.WithMethods("GET", "POST", "PUT", "DELETE", "PATCH"));
|
|
|
|
|
}
|
2026-07-16 20:53:56 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// ── Pipeline ──────────────────────────────────────────────────────
|
|
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
var app = builder.Build();
|
|
|
|
|
|
2026-07-18 19:28:16 +00:00
|
|
|
// ── Apply pending migrations before any database access ──────────────
|
|
|
|
|
// Migration runs inline (not as IHostedService) to guarantee the schema
|
|
|
|
|
// exists before Identity seeding below and before the web host starts
|
|
|
|
|
// serving requests. Using a separate scope keeps migration lifetime
|
2026-07-18 20:31:37 +00:00
|
|
|
// independent of the seeding scope.
|
|
|
|
|
// Retry with exponential backoff to handle container startup races where
|
|
|
|
|
// PostgreSQL accepts TCP connections but isn't ready to serve queries yet
|
|
|
|
|
// (see GlitchTip #538 — Failed executing DbCommand on __EFMigrationsHistory).
|
2026-07-18 19:28:16 +00:00
|
|
|
if (!app.Environment.IsEnvironment("Testing"))
|
2026-07-16 20:53:56 +00:00
|
|
|
{
|
2026-07-18 19:28:16 +00:00
|
|
|
using var migrationScope = app.Services.CreateScope();
|
|
|
|
|
var migrationLogger = migrationScope.ServiceProvider
|
|
|
|
|
.GetRequiredService<ILogger<Program>>();
|
|
|
|
|
var db = migrationScope.ServiceProvider.GetRequiredService<AppDbContext>();
|
|
|
|
|
|
2026-07-18 20:31:37 +00:00
|
|
|
var maxRetries = 5;
|
|
|
|
|
var retryDelay = TimeSpan.FromSeconds(2);
|
|
|
|
|
|
|
|
|
|
for (var attempt = 1; attempt <= maxRetries; attempt++)
|
2026-07-18 19:28:16 +00:00
|
|
|
{
|
2026-07-18 20:31:37 +00:00
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
migrationLogger.LogInformation("Applying pending database migrations (attempt {Attempt}/{MaxRetries})...", attempt, maxRetries);
|
|
|
|
|
await db.Database.MigrateAsync(CancellationToken.None);
|
|
|
|
|
migrationLogger.LogInformation("Database migrations applied successfully");
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex) when (attempt < maxRetries)
|
|
|
|
|
{
|
|
|
|
|
migrationLogger.LogWarning(ex,
|
|
|
|
|
"Database migration attempt {Attempt}/{MaxRetries} failed. Retrying in {Delay}s...",
|
|
|
|
|
attempt, maxRetries, retryDelay.TotalSeconds);
|
|
|
|
|
await Task.Delay(retryDelay);
|
|
|
|
|
retryDelay = TimeSpan.FromSeconds(retryDelay.TotalSeconds * 2); // Exponential backoff
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
migrationLogger.LogCritical(ex, "Failed to apply database migrations after {MaxRetries} attempts. " +
|
|
|
|
|
"The application cannot start without a migrated database. " +
|
|
|
|
|
"Ensure the database server is running and accessible.", maxRetries);
|
|
|
|
|
throw;
|
|
|
|
|
}
|
2026-07-18 19:28:16 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ── Seed Identity roles (requires roles table to exist) ──────────────
|
|
|
|
|
using var seedScope = app.Services.CreateScope();
|
|
|
|
|
{
|
|
|
|
|
var roleManager = seedScope.ServiceProvider
|
2026-07-16 20:53:56 +00:00
|
|
|
.GetRequiredService<Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Domain.Entities.AppRole>>();
|
2026-07-18 19:28:16 +00:00
|
|
|
var userManager = seedScope.ServiceProvider
|
2026-07-16 21:19:16 +00:00
|
|
|
.GetRequiredService<Microsoft.AspNetCore.Identity.UserManager<Heimdall.Domain.Entities.AppUser>>();
|
2026-07-16 20:53:56 +00:00
|
|
|
|
|
|
|
|
foreach (var roleName in AppRoles.All)
|
|
|
|
|
{
|
|
|
|
|
if (!await roleManager.RoleExistsAsync(roleName))
|
|
|
|
|
{
|
|
|
|
|
await roleManager.CreateAsync(new Heimdall.Domain.Entities.AppRole(roleName));
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-07-16 21:19:16 +00:00
|
|
|
|
2026-07-19 07:04:25 +00:00
|
|
|
// Seed default groups
|
|
|
|
|
var groupDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
|
|
|
|
|
var defaultGroups = new[] { "Administrateurs", "Superviseurs", "Visiteurs", "Techniciens" };
|
|
|
|
|
foreach (var groupName in defaultGroups)
|
|
|
|
|
{
|
|
|
|
|
if (!await groupDb.Groups.AnyAsync(g => g.Name == groupName))
|
|
|
|
|
{
|
|
|
|
|
groupDb.Groups.Add(new Heimdall.Domain.Entities.Group(groupName,
|
|
|
|
|
groupName switch
|
|
|
|
|
{
|
|
|
|
|
"Administrateurs" => "Accès complet à toutes les fonctionnalités",
|
|
|
|
|
"Superviseurs" => "Gestion des sites, caméras et événements",
|
|
|
|
|
"Visiteurs" => "Consultation en lecture seule",
|
|
|
|
|
"Techniciens" => "Maintenance technique et support",
|
|
|
|
|
_ => null
|
|
|
|
|
}));
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-07-20 10:15:39 +00:00
|
|
|
await groupDb.SaveChangesWithRetryAsync();
|
2026-07-19 07:04:25 +00:00
|
|
|
|
2026-07-17 13:15:25 +00:00
|
|
|
// Seed demo admin in Development (NOT Testing — tests create their own users)
|
|
|
|
|
if (app.Environment.IsDevelopment())
|
2026-07-16 21:19:16 +00:00
|
|
|
{
|
2026-07-17 13:15:25 +00:00
|
|
|
var testAdmin = await userManager.FindByEmailAsync("admin@heimdall.test");
|
2026-07-16 21:19:16 +00:00
|
|
|
if (testAdmin is null)
|
|
|
|
|
{
|
|
|
|
|
testAdmin = new Heimdall.Domain.Entities.AppUser
|
|
|
|
|
{
|
2026-07-17 13:15:25 +00:00
|
|
|
UserName = "admin@heimdall.test",
|
|
|
|
|
Email = "admin@heimdall.test",
|
|
|
|
|
DisplayName = "Admin"
|
2026-07-16 21:19:16 +00:00
|
|
|
};
|
2026-07-17 19:27:16 +00:00
|
|
|
await userManager.CreateAsync(testAdmin, "Admin123!Pass");
|
2026-07-16 21:19:16 +00:00
|
|
|
await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin);
|
|
|
|
|
}
|
2026-07-17 13:15:25 +00:00
|
|
|
|
2026-07-18 19:28:16 +00:00
|
|
|
var demoDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
|
2026-07-17 13:15:25 +00:00
|
|
|
var demoSite = await demoDb.Sites.FirstOrDefaultAsync(s => s.Name == "Site Démo");
|
|
|
|
|
if (demoSite is null)
|
|
|
|
|
{
|
|
|
|
|
demoSite = new Heimdall.Domain.Entities.Site("Site Démo", "Paris", "Europe/Paris");
|
|
|
|
|
demoDb.Sites.Add(demoSite);
|
2026-07-20 10:15:39 +00:00
|
|
|
await demoDb.SaveChangesWithRetryAsync();
|
2026-07-17 13:15:25 +00:00
|
|
|
}
|
2026-07-16 21:19:16 +00:00
|
|
|
}
|
2026-07-16 20:53:56 +00:00
|
|
|
}
|
|
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
if (app.Environment.IsDevelopment())
|
|
|
|
|
{
|
|
|
|
|
app.MapOpenApi();
|
2026-07-17 17:45:44 +00:00
|
|
|
app.MapScalarApiReference(); // Beautiful API docs UI
|
2026-07-16 19:09:28 +00:00
|
|
|
}
|
|
|
|
|
|
2026-07-16 20:53:56 +00:00
|
|
|
app.UseCors("ApiPolicy");
|
2026-07-16 19:09:28 +00:00
|
|
|
app.UseHttpsRedirection();
|
2026-07-17 06:57:00 +00:00
|
|
|
app.UseRateLimiter();
|
2026-07-16 20:53:56 +00:00
|
|
|
app.UseAuthentication();
|
2026-07-16 19:09:28 +00:00
|
|
|
app.UseAuthorization();
|
|
|
|
|
app.MapControllers();
|
2026-07-18 18:58:20 +00:00
|
|
|
app.MapHub<ConfigHub>("/hubs/config");
|
2026-07-19 15:24:52 +00:00
|
|
|
app.MapHub<EventsHub>("/hubs/events");
|
2026-07-16 19:09:28 +00:00
|
|
|
|
|
|
|
|
app.Run();
|