Files
Heimdall/src/Heimdall.Api/Program.cs
T

268 lines
10 KiB
C#
Raw Normal View History

using System.Text;
using Microsoft.AspNetCore.RateLimiting;
2026-07-17 17:45:44 +00:00
using Scalar.AspNetCore;
using Heimdall.Api.Filters;
using Heimdall.Application;
using Heimdall.Application.Services;
using Heimdall.Infrastructure;
using Heimdall.Api.Hubs;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
// ── Sentry (GlitchTip) — DSN from env var, with hardcoded fallback ─
var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN")
?? "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6";
var builder = WebApplication.CreateBuilder(args);
// ── Sentry ────────────────────────────────────────────────────────
builder.WebHost.UseSentry(options =>
{
options.Dsn = sentryDsn;
options.MinimumBreadcrumbLevel = LogLevel.Debug;
options.MinimumEventLevel = LogLevel.Error;
options.TracesSampleRate = 0.1;
});
// ── 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;
});
});
// ── Services ──────────────────────────────────────────────────────
if (!builder.Environment.IsEnvironment("Testing"))
{
builder.Services.AddControllers(options =>
{
options.Filters.Add<ExceptionFilter>();
});
}
else
{
builder.Services.AddControllers();
}
builder.Services.AddSignalR();
builder.Services.AddScoped<IEventBroadcastService, EventBroadcastService>();
builder.Services.AddScoped<IConfigBroadcastService, ConfigBroadcastService>();
builder.Services.AddOpenApi();
// ── Application layer ─────────────────────────────────────────────
builder.Services.AddApplication();
// ── Infrastructure layer ──────────────────────────────────────────
builder.Services.AddInfrastructure(builder.Configuration, builder.Environment.EnvironmentName);
// ── Authentication ────────────────────────────────────────────────
var jwtKey = builder.Configuration["Jwt:Key"]
?? Environment.GetEnvironmentVariable("JWT__KEY")
?? throw new InvalidOperationException("JWT:Key is not configured");
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall";
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api";
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
};
})
.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 =>
{
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"));
}
});
// ── Pipeline ──────────────────────────────────────────────────────
var app = builder.Build();
// ── 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
// 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).
if (!app.Environment.IsEnvironment("Testing"))
{
using var migrationScope = app.Services.CreateScope();
var migrationLogger = migrationScope.ServiceProvider
.GetRequiredService<ILogger<Program>>();
var db = migrationScope.ServiceProvider.GetRequiredService<AppDbContext>();
var maxRetries = 5;
var retryDelay = TimeSpan.FromSeconds(2);
for (var attempt = 1; attempt <= maxRetries; attempt++)
{
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;
}
}
}
// ── Seed Identity roles (requires roles table to exist) ──────────────
using var seedScope = app.Services.CreateScope();
{
var roleManager = seedScope.ServiceProvider
.GetRequiredService<Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Domain.Entities.AppRole>>();
var userManager = seedScope.ServiceProvider
.GetRequiredService<Microsoft.AspNetCore.Identity.UserManager<Heimdall.Domain.Entities.AppUser>>();
foreach (var roleName in AppRoles.All)
{
if (!await roleManager.RoleExistsAsync(roleName))
{
await roleManager.CreateAsync(new Heimdall.Domain.Entities.AppRole(roleName));
}
}
// 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
}));
}
}
await groupDb.SaveChangesAsync();
// Seed demo admin in Development (NOT Testing — tests create their own users)
if (app.Environment.IsDevelopment())
{
var testAdmin = await userManager.FindByEmailAsync("admin@heimdall.test");
if (testAdmin is null)
{
testAdmin = new Heimdall.Domain.Entities.AppUser
{
UserName = "admin@heimdall.test",
Email = "admin@heimdall.test",
DisplayName = "Admin"
};
await userManager.CreateAsync(testAdmin, "Admin123!Pass");
await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin);
}
var demoDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
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);
await demoDb.SaveChangesAsync();
}
}
}
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
2026-07-17 17:45:44 +00:00
app.MapScalarApiReference(); // Beautiful API docs UI
}
app.UseCors("ApiPolicy");
app.UseHttpsRedirection();
app.UseRateLimiter();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapHub<ConfigHub>("/hubs/config");
app.MapHub<EventsHub>("/hubs/events");
app.Run();