- 13 controllers migrated from service DI to IMediator dispatch - 11 AutoMapper mapping profiles (Sites, Cameras, Auth, Users, Agents, Events, Assignments, Settings, Groups, Persons, Discovery) - SignalR notifications bridged via MediatR INotificationHandler - Hangfire config moved from Program.cs to Infrastructure/BackgroundJobs - 0 build errors, 0 warnings
473 lines
19 KiB
C#
473 lines
19 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using FluentValidation.AspNetCore;
|
|
using Heimdall.Application;
|
|
using Heimdall.Application.Services;
|
|
using Heimdall.Infrastructure;
|
|
using Heimdall.Infrastructure.Data;
|
|
using Heimdall.Infrastructure.BackgroundJobs;
|
|
using Heimdall.Infrastructure.Security;
|
|
using Heimdall.Web.Components;
|
|
using Heimdall.Api.Hubs;
|
|
using Heimdall.Web.Services;
|
|
using Hangfire;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
|
using Microsoft.AspNetCore.RateLimiting;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using MudBlazor.Services;
|
|
using Scalar.AspNetCore;
|
|
|
|
// ── Sentry (GlitchTip) — DSN from env var only ───────────────────
|
|
var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN");
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
|
|
// ── Sentry ────────────────────────────────────────────────────────
|
|
if (sentryDsn is not null)
|
|
{
|
|
builder.WebHost.UseSentry(options =>
|
|
{
|
|
options.Dsn = sentryDsn;
|
|
options.MinimumBreadcrumbLevel = LogLevel.Debug;
|
|
options.MinimumEventLevel = LogLevel.Error;
|
|
options.TracesSampleRate = 0.1;
|
|
});
|
|
}
|
|
|
|
builder.Services.AddRazorComponents()
|
|
.AddInteractiveServerComponents();
|
|
|
|
// ── Authentication (Microsoft Identity pattern: cookie auth) ──────
|
|
// The app uses JWT auth via the Heimdall API at the application level.
|
|
// At the ASP.NET Core middleware level, we use cookie authentication
|
|
// to persist the user session across requests.
|
|
// The cookie is created after successful API login (see /_auth/signin).
|
|
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";
|
|
|
|
// Shared JWT validation parameters — used by both AddJwtBearer and /_auth/signin.
|
|
// Extracted to a single location to prevent configuration drift (single source of truth).
|
|
static TokenValidationParameters GetJwtValidationParameters(string key, string issuer, string audience) => new()
|
|
{
|
|
ValidateIssuerSigningKey = true,
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)),
|
|
ValidateIssuer = true,
|
|
ValidIssuer = issuer,
|
|
ValidateAudience = true,
|
|
ValidAudience = audience,
|
|
ValidateLifetime = true,
|
|
ClockSkew = TimeSpan.Zero
|
|
};
|
|
|
|
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
|
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
|
|
{
|
|
options.LoginPath = "/login";
|
|
options.LogoutPath = "/_auth/signout";
|
|
options.AccessDeniedPath = "/not-found";
|
|
options.Cookie.Name = ".Heimdall.Auth";
|
|
options.Cookie.HttpOnly = true;
|
|
options.Cookie.SameSite = SameSiteMode.Lax;
|
|
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
|
|
options.ExpireTimeSpan = TimeSpan.FromDays(7);
|
|
options.SlidingExpiration = true;
|
|
})
|
|
.AddJwtBearer("JwtBearer", options =>
|
|
{
|
|
options.TokenValidationParameters = GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience);
|
|
|
|
// 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;
|
|
}
|
|
};
|
|
})
|
|
.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>("ApiKey", null);
|
|
|
|
builder.Services.AddAuthorizationCore(options =>
|
|
{
|
|
// Register all permission-based policies from AppPermissions
|
|
var allPermissions = AppPermissions.RolePermissions.Values
|
|
.SelectMany(p => p).Distinct();
|
|
foreach (var permission in allPermissions)
|
|
{
|
|
options.AddPolicy(permission, policy =>
|
|
policy.RequireClaim("permission", permission));
|
|
}
|
|
});
|
|
builder.Services.AddCascadingAuthenticationState();
|
|
|
|
// Blazor auth state provider (reads JWT from ProtectedLocalStorage)
|
|
// Register the concrete type so @inject HeimdallAuthStateProvider works in pages,
|
|
// then make the base AuthenticationStateProvider resolve to the same instance.
|
|
builder.Services.AddScoped<HeimdallAuthStateProvider>();
|
|
builder.Services.AddScoped<AuthenticationStateProvider>(
|
|
sp => sp.GetRequiredService<HeimdallAuthStateProvider>());
|
|
|
|
// ── MudBlazor ─────────────────────────────────────────────────────
|
|
builder.Services.AddMudServices(config =>
|
|
{
|
|
config.SnackbarConfiguration.PositionClass = "mud-alert-center-top";
|
|
config.SnackbarConfiguration.PreventDuplicates = true;
|
|
config.SnackbarConfiguration.ShowCloseIcon = true;
|
|
config.SnackbarConfiguration.VisibleStateDuration = 4000;
|
|
});
|
|
|
|
// ── 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;
|
|
});
|
|
});
|
|
|
|
// ── Controllers (REST API) ────────────────────────────────────────
|
|
builder.Services.AddControllers(options =>
|
|
{
|
|
options.Filters.Add<Heimdall.Api.Filters.ExceptionFilter>();
|
|
});
|
|
|
|
// Auto-validation with FluentValidation
|
|
builder.Services.AddFluentValidationAutoValidation();
|
|
|
|
// 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());
|
|
});
|
|
|
|
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);
|
|
|
|
// ── Hangfire (required: heartbeat monitor, agent failover, etc.) ──
|
|
// Skipped in Testing — WebApplicationFactory doesn't have PostgreSQL.
|
|
// In Production: enabled if DATABASE_URL or ConnectionStrings:Default is set.
|
|
var isTesting = builder.Environment.IsEnvironment("Testing");
|
|
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
|
|
?? builder.Configuration.GetConnectionString("Default");
|
|
|
|
if (!isTesting && !string.IsNullOrEmpty(connectionString))
|
|
{
|
|
builder.Services.AddBackgroundJobs(builder.Configuration);
|
|
}
|
|
|
|
// ── HTTP client for Heimdall API (with auto-refresh handler) ──────
|
|
builder.Services.AddScoped<HeimdallApiClient>();
|
|
builder.Services.AddTransient<TokenRefreshHandler>();
|
|
var apiBaseUrl = builder.Configuration.GetValue<string>("ApiBaseUrl")
|
|
?? Environment.GetEnvironmentVariable("API_BASE_URL")
|
|
?? "http://localhost:8080";
|
|
builder.Services.AddHttpClient("HeimdallApi", client =>
|
|
{
|
|
client.BaseAddress = new Uri(apiBaseUrl.TrimEnd('/') + "/");
|
|
client.Timeout = TimeSpan.FromSeconds(30);
|
|
})
|
|
.AddHttpMessageHandler<TokenRefreshHandler>();
|
|
|
|
// Auth state (shared between services and components)
|
|
builder.Services.AddScoped<AuthState>();
|
|
|
|
var app = builder.Build();
|
|
|
|
// ── Middleware pipeline ────────────────────────────────────────────
|
|
if (!app.Environment.IsDevelopment())
|
|
{
|
|
app.UseExceptionHandler("/Error", createScopeForErrors: true);
|
|
app.UseHsts();
|
|
}
|
|
|
|
app.UseHttpsRedirection();
|
|
app.UseStaticFiles();
|
|
|
|
app.UseAuthentication();
|
|
app.UseAuthorization();
|
|
|
|
// Anti-forgery AFTER auth so unauthenticated API calls get 401
|
|
// before the anti-forgery middleware returns 400.
|
|
app.UseAntiforgery();
|
|
|
|
app.MapRazorComponents<App>()
|
|
.AddInteractiveServerRenderMode();
|
|
|
|
// ── REST API controllers & SignalR hubs ───────────────────────────
|
|
app.MapControllers();
|
|
app.MapHub<ConfigHub>("/hubs/config");
|
|
app.MapHub<EventsHub>("/hubs/events");
|
|
|
|
// ── OpenAPI / Scalar (dev only) ───────────────────────────────────
|
|
if (app.Environment.IsDevelopment())
|
|
{
|
|
app.MapOpenApi();
|
|
app.MapScalarApiReference();
|
|
}
|
|
|
|
// ── CORS (for external agents and API clients) ────────────────────
|
|
var allowedOrigins = builder.Configuration["Cors:AllowedOrigins"]?.Split(',')
|
|
?? ["https://localhost:5001"];
|
|
|
|
app.UseCors(options =>
|
|
{
|
|
var isWildcard = allowedOrigins.Length == 1 && allowedOrigins[0] == "*";
|
|
if (isWildcard)
|
|
{
|
|
options.AllowAnyOrigin()
|
|
.AllowAnyHeader()
|
|
.AllowAnyMethod();
|
|
}
|
|
else
|
|
{
|
|
options.WithOrigins(allowedOrigins)
|
|
.AllowCredentials()
|
|
.AllowAnyHeader()
|
|
.WithMethods("GET", "POST", "PUT", "DELETE", "PATCH");
|
|
}
|
|
});
|
|
|
|
app.UseRateLimiter();
|
|
|
|
// ── Cookie auth endpoints (called from Blazor via JS fetch) ───────
|
|
// /_auth/signin — Validates the JWT access token and creates an auth cookie
|
|
// /_auth/signout — Clears the authentication cookie on logout
|
|
//
|
|
// IMPORTANT: The JWT is validated server-side — never trust client-supplied claims.
|
|
|
|
app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request, ILogger<Program> logger) =>
|
|
{
|
|
if (string.IsNullOrEmpty(request.AccessToken))
|
|
{
|
|
logger.LogWarning("Signin attempt without access token");
|
|
return Results.BadRequest(new { error = "AccessToken is required" });
|
|
}
|
|
|
|
// Validate the JWT server-side — extract claims from the validated token, not from client
|
|
// Uses the same GetJwtValidationParameters() as AddJwtBearer (single source of truth).
|
|
try
|
|
{
|
|
var handler = new JwtSecurityTokenHandler();
|
|
var principal = handler.ValidateToken(
|
|
request.AccessToken,
|
|
GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience),
|
|
out _);
|
|
|
|
// Extract claims from the validated JWT only
|
|
var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
|
var email = principal.FindFirst(ClaimTypes.Email)?.Value;
|
|
var displayName = principal.FindFirst(ClaimTypes.Name)?.Value;
|
|
|
|
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(email))
|
|
{
|
|
logger.LogWarning("Signin attempt with valid JWT but missing user claims: UserId={UserId}, Email={Email}", userId, email);
|
|
return Results.BadRequest(new { error = "Invalid token: missing user claims" });
|
|
}
|
|
|
|
logger.LogInformation("Signing in user {Email} ({UserId}) — creating auth cookie", email, userId);
|
|
|
|
// Re-build claims identity from validated token claims (never from client body)
|
|
var claims = new List<Claim>
|
|
{
|
|
new(ClaimTypes.NameIdentifier, userId),
|
|
new(ClaimTypes.Email, email),
|
|
new(ClaimTypes.Name, displayName ?? email),
|
|
};
|
|
|
|
foreach (var role in principal.FindAll(ClaimTypes.Role))
|
|
claims.Add(new Claim(ClaimTypes.Role, role.Value));
|
|
|
|
foreach (var permission in principal.FindAll("permission"))
|
|
claims.Add(new Claim("permission", permission.Value));
|
|
|
|
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
|
var cookiePrincipal = new ClaimsPrincipal(identity);
|
|
|
|
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, cookiePrincipal);
|
|
logger.LogInformation("Auth cookie created for {Email} ({UserId})", email, userId);
|
|
return Results.Ok();
|
|
}
|
|
catch (SecurityTokenExpiredException)
|
|
{
|
|
logger.LogWarning("Signin attempt with expired JWT");
|
|
return Results.Unauthorized();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "Signin failed — JWT validation error");
|
|
return Results.BadRequest(new { error = $"Token validation failed: {ex.Message}" });
|
|
}
|
|
});
|
|
|
|
app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger<Program> logger) =>
|
|
{
|
|
var email = httpContext.User.FindFirst(ClaimTypes.Email)?.Value ?? "(anonymous)";
|
|
logger.LogInformation("Signing out user {Email}", email);
|
|
await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
|
return Results.Ok();
|
|
});
|
|
|
|
// ── Apply pending database migrations ────────────────────────────────
|
|
// Retry with exponential backoff to handle container startup races where
|
|
// PostgreSQL accepts TCP connections but isn't ready to serve queries yet.
|
|
// In Production/Staging: migrations run by default (auto=true).
|
|
// In Testing: disabled via Database:MigrateOnStartup=false config.
|
|
var migrateOnStartup = builder.Configuration.GetValue<bool?>("Database:MigrateOnStartup")
|
|
?? app.Environment.IsProduction();
|
|
if (migrateOnStartup)
|
|
{
|
|
using (var scope = app.Services.CreateScope())
|
|
{
|
|
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
|
|
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
|
var maxRetries = 5;
|
|
var retryDelay = TimeSpan.FromSeconds(2);
|
|
|
|
for (var attempt = 1; attempt <= maxRetries; attempt++)
|
|
{
|
|
try
|
|
{
|
|
logger.LogInformation("Applying database migrations (attempt {Attempt}/{MaxRetries})...", attempt, maxRetries);
|
|
db.Database.Migrate();
|
|
logger.LogInformation("Database migrations applied successfully");
|
|
break;
|
|
}
|
|
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);
|
|
retryDelay = TimeSpan.FromSeconds(retryDelay.TotalSeconds * 2);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogCritical(ex, "Failed to apply database migrations after {MaxRetries} attempts.", maxRetries);
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// ── Register recurring Hangfire jobs (heartbeat monitor, agent failover) ──
|
|
if (!isTesting && !string.IsNullOrEmpty(connectionString))
|
|
{
|
|
using (var scope = app.Services.CreateScope())
|
|
{
|
|
var manager = scope.ServiceProvider.GetRequiredService<IRecurringJobManager>();
|
|
Heimdall.Infrastructure.BackgroundJobs.JobSetup.ConfigureRecurringJobs(manager);
|
|
}
|
|
}
|
|
|
|
// ── Seed Identity roles (required in ALL environments, including Testing) ─
|
|
// This must run before any user registration — AuthService.AddToRoleAsync
|
|
// throws "Role X does not exist" if the role hasn't been created yet.
|
|
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 (idempotent)
|
|
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.SaveChangesWithRetryAsync();
|
|
|
|
// Seed demo admin + demo site in Development only
|
|
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 demoSite = await groupDb.Sites.FirstOrDefaultAsync(s => s.Name == "Site Démo");
|
|
if (demoSite is null)
|
|
{
|
|
demoSite = new Heimdall.Domain.Entities.Site("Site Démo", "Paris", "Europe/Paris");
|
|
groupDb.Sites.Add(demoSite);
|
|
await groupDb.SaveChangesWithRetryAsync();
|
|
}
|
|
}
|
|
}
|
|
|
|
app.Run();
|
|
|
|
// ─── DTO for the cookie sign-in request ───────────────────────────
|
|
|
|
internal sealed record SignInRequest(
|
|
string AccessToken);
|
|
|
|
// Partial class declaration so WebApplicationFactory<Program>
|
|
// works in integration tests.
|
|
public partial class Program { }
|