feat(agent): télémétrie inventaire matériel — CPU/mémoire/disque/GPU/OS/réseau (Fixes #82 #83 #84 #85) (#137)
## Contexte Implémentation des tickets #82, #83, #84, #85 — télémétrie inventaire matériel agent. L'objectif est de fournir au central un maximum d'informations sur les machines des agents (CPU, mémoire, disques, GPU, OS, réseau, conteneur) sans SSH. ## Changements ### Nouveaux collecteurs (src/Heimdall.Agent/Services/) - **CpuInfoProvider** : parse `/proc/cpuinfo` (vendor, modèle, cœurs physiques/logiques, fréquence, flags AVX/AVX2/FMA/AVX512, cache), topologie, détection cgroup CPU (`/sys/fs/cgroup/cpu.max` v2) - **DiskInventoryProvider** : énumère les montages (`/proc/mounts`), capacité/libre/type SSD/HDD via `/sys/block/*/queue/rotation` - **GpuInventoryProvider** : nvidia-smi, sysfs DRM, vainfo, rocm-smi avec fallback silencieux, multi-GPU - **HostInfoProvider** : os-release, uname, `/proc/uptime` (uptime machine ≠ process), températures sysfs - **ContainerInfoProvider** : détection Docker (/.dockerenv, cgroup), ID conteneur, limites CPU/mémoire ### Refonte SystemMetricsProvider - Séparation host vs process (RAM machine ≠ RAM conteneur ≠ WorkingSet64) - Uptime machine (`/proc/uptime`) distinct de l'uptime process - Mémoire swap ### Entité Agent + Migration - Champs structurés CPU/mémoire/disque/GPU/OS/réseau (tous nullable, rétrocompatible) - Migration EF `AddAgentTelemetryInventory` ### Transport heartbeat - Inventaire au register + refresh périodique (5 min, pas à chaque tick) - Champs JSON pour listes (disques, GPU, interfaces réseau, températures) ### UI Admin (AgentDetail.razor) - Sections CPU, Mémoire/Disques, GPU, Machine/Conteneur avec barres de progression et badges ### Tests - 40+ tests unitaires : providers, handlers, entité Agent - Total : 999 tests verts (Domain 149, Application 397, Agent 210, Web 243) ## Tickets liés - Fixes #82 — CPU inventory - Fixes #83 — Mémoire & disque - Fixes #84 — GPU inventory - Fixes #85 — OS, conteneur, réseau ## Résultats des tests - `dotnet build` : 0 erreur, 0 warning - Domain.Tests : 149 passed - Application.Tests : 397 passed - Agent.Tests : 210 passed - Web.Tests : 243 passed - Total : 999 tests ✅ ## Checklist - [x] `dotnet build` vert (TreatWarningsAsErrors) - [x] Tests unitaires verts - [x] Migration EF créée - [x] Champs nullable (rétrocompatible) - [x] Pas de référence Infrastructure dans les contrôleurs - [x] Collecteurs avec fallback silencieux (pas de crash sans GPU/Docker/sysfs) Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/137
This commit is contained in:
1 parent
f7e6b0cec3
commit
4792b69e46
63 files changed
+8711
-563
No files matched your search
+261
-248
@@ -42,14 +42,14 @@ Program.ConfigureMiddleware(app);
|
||||
// (appsettings.Testing.json sets Database:MigrateOnStartup=false; test
|
||||
// factories opt back in explicitly when they need the schema).
|
||||
var migrateOnStartup = builder.Configuration.GetValue<bool?>("Database:MigrateOnStartup")
|
||||
?? !app.Environment.IsEnvironment("Testing");
|
||||
?? !app.Environment.IsEnvironment(TestingEnvironment);
|
||||
if (migrateOnStartup)
|
||||
{
|
||||
await Program.ApplyMigrationsAsync(app);
|
||||
}
|
||||
|
||||
// ── Register recurring Hangfire jobs (heartbeat monitor, agent failover) ──
|
||||
var isTesting = app.Environment.IsEnvironment("Testing");
|
||||
var isTesting = app.Environment.IsEnvironment(TestingEnvironment);
|
||||
var pgConnStr = Environment.GetEnvironmentVariable("DATABASE_URL") ?? app.Configuration.GetConnectionString("Default");
|
||||
if (!isTesting && !string.IsNullOrEmpty(pgConnStr))
|
||||
{
|
||||
@@ -76,6 +76,30 @@ internal sealed record SignInRequest(
|
||||
// works in integration tests.
|
||||
public partial class Program
|
||||
{
|
||||
private const string TestingEnvironment = "Testing";
|
||||
|
||||
// SonarQube S1118: partial class used by WebApplicationFactory needs a constructor.
|
||||
protected Program() { }
|
||||
|
||||
private static string ResolveCategory(string key)
|
||||
{
|
||||
if (key.StartsWith("ntfy.", StringComparison.Ordinal) || key.StartsWith("email.", StringComparison.Ordinal))
|
||||
return "integrations";
|
||||
if (key.StartsWith("ai.", StringComparison.Ordinal))
|
||||
return "ai";
|
||||
return "agent";
|
||||
}
|
||||
|
||||
private static string FormatSentryStatus(bool enabled, string? dsn)
|
||||
{
|
||||
if (!enabled)
|
||||
return "DISABLED (toggle sentry.enabled=false — redémarrage requis)";
|
||||
if (string.IsNullOrEmpty(dsn))
|
||||
return "NOT CONFIGURED — errors will NOT be reported to GlitchTip";
|
||||
var atIndex = dsn.IndexOf('@');
|
||||
return $"configured ({dsn[..atIndex]}@...)";
|
||||
}
|
||||
|
||||
// Shared JWT validation parameters — single source of truth for auth.
|
||||
internal static TokenValidationParameters GetJwtValidationParameters(string key, string issuer, string audience) => new()
|
||||
{
|
||||
@@ -141,7 +165,7 @@ public partial class Program
|
||||
{
|
||||
migrationCt.ThrowIfCancellationRequested();
|
||||
logger.LogInformation("Applying database migrations (attempt {Attempt}/{MaxRetries})...", attempt, maxRetries);
|
||||
db.Database.Migrate();
|
||||
await db.Database.MigrateAsync(migrationCt);
|
||||
logger.LogInformation("Database migrations applied successfully");
|
||||
break;
|
||||
}
|
||||
@@ -178,7 +202,19 @@ public partial class Program
|
||||
.GetRequiredService<Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Domain.Entities.AppRole>>();
|
||||
var userManager = seedScope.ServiceProvider
|
||||
.GetRequiredService<Microsoft.AspNetCore.Identity.UserManager<Heimdall.Domain.Entities.AppUser>>();
|
||||
var groupDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
|
||||
await SeedRolesAsync(roleManager);
|
||||
await SeedGroupsAsync(groupDb);
|
||||
var existingKeys = await GetExistingSettingKeysAsync(groupDb);
|
||||
await SeedStorageSettingsAsync(groupDb, existingKeys);
|
||||
await SeedIntegrationSettingsAsync(groupDb, existingKeys);
|
||||
await MigrateLegacySentryKeysAsync(groupDb);
|
||||
await SeedDemoDataAsync(configuration, userManager, groupDb);
|
||||
}
|
||||
|
||||
private static async Task SeedRolesAsync(Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Domain.Entities.AppRole> roleManager)
|
||||
{
|
||||
foreach (var roleName in AppRoles.All)
|
||||
{
|
||||
if (!await roleManager.RoleExistsAsync(roleName))
|
||||
@@ -186,9 +222,10 @@ public partial class Program
|
||||
await roleManager.CreateAsync(new Heimdall.Domain.Entities.AppRole(roleName));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Seed default groups (idempotent)
|
||||
var groupDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
private static async Task SeedGroupsAsync(AppDbContext groupDb)
|
||||
{
|
||||
var defaultGroups = new[] { "Administrateurs", "Superviseurs", "Visiteurs", "Techniciens" };
|
||||
foreach (var groupName in defaultGroups)
|
||||
{
|
||||
@@ -206,10 +243,16 @@ public partial class Program
|
||||
}
|
||||
}
|
||||
await groupDb.SaveChangesWithRetryAsync();
|
||||
}
|
||||
|
||||
// Seed des paramètres de stockage (idempotent) — source de vérité DB,
|
||||
// valeur initiale depuis env pour migration douce (ticket #78/#80).
|
||||
var storageDefaults = new Dictionary<string, string?>
|
||||
private static async Task<HashSet<string>> GetExistingSettingKeysAsync(AppDbContext groupDb) =>
|
||||
new(
|
||||
await groupDb.AppSettings.Select(s => s.Key).ToListAsync(),
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private static async Task SeedStorageSettingsAsync(AppDbContext groupDb, HashSet<string> existingKeys)
|
||||
{
|
||||
var defaults = new Dictionary<string, string?>
|
||||
{
|
||||
["storage.provider"] = Environment.GetEnvironmentVariable("STORAGE__PROVIDER") ?? "Local",
|
||||
["storage.local.path"] = Environment.GetEnvironmentVariable("STORAGE__LOCAL__PATH") ?? "./data/storage",
|
||||
@@ -220,17 +263,9 @@ public partial class Program
|
||||
["storage.s3.secretKey"] = Environment.GetEnvironmentVariable("S3_SECRET_KEY"),
|
||||
["storage.s3.region"] = Environment.GetEnvironmentVariable("S3_REGION") ?? "us-east-1",
|
||||
};
|
||||
// Clés existantes en mémoire (casse ignorée) — le constructeur
|
||||
// AppSetting lower-case les clés (accessKey → accesskey), et
|
||||
// string.Equals(OrdinalIgnoreCase) n'est pas traduisible par EF :
|
||||
// le check idempotent se fait donc côté client sur un HashSet.
|
||||
var existingAppSettingKeys = new HashSet<string>(
|
||||
await groupDb.AppSettings.Select(s => s.Key).ToListAsync(),
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var (key, value) in storageDefaults)
|
||||
foreach (var (key, value) in defaults)
|
||||
{
|
||||
if (existingAppSettingKeys.Contains(key))
|
||||
continue;
|
||||
if (existingKeys.Contains(key)) continue;
|
||||
groupDb.AppSettings.Add(new Heimdall.Domain.Entities.AppSetting(
|
||||
key, value ?? string.Empty, "storage",
|
||||
key switch
|
||||
@@ -247,10 +282,11 @@ public partial class Program
|
||||
agentScoped: false));
|
||||
}
|
||||
await groupDb.SaveChangesWithRetryAsync();
|
||||
}
|
||||
|
||||
// Seed des paramètres d'intégration (idempotent) — source de vérité DB,
|
||||
// valeur initiale depuis env pour migration douce (ticket #80).
|
||||
var integrationDefaults = new Dictionary<string, string?>
|
||||
private static async Task SeedIntegrationSettingsAsync(AppDbContext groupDb, HashSet<string> existingKeys)
|
||||
{
|
||||
var defaults = new Dictionary<string, string?>
|
||||
{
|
||||
["ntfy.baseUrl"] = Environment.GetEnvironmentVariable("NTFY__BASE_URL") ?? "https://ntfy.sh",
|
||||
["ntfy.token"] = Environment.GetEnvironmentVariable("NTFY__TOKEN"),
|
||||
@@ -269,19 +305,16 @@ public partial class Program
|
||||
["heartbeat.interval.seconds"] = Environment.GetEnvironmentVariable("HEARTBEAT__INTERVAL_SECONDS") ?? "30",
|
||||
["sentry.enabled"] = "true",
|
||||
};
|
||||
foreach (var (key, value) in integrationDefaults)
|
||||
foreach (var (key, value) in defaults)
|
||||
{
|
||||
if (existingAppSettingKeys.Contains(key))
|
||||
continue;
|
||||
// SMTP/ntfy/Sentry = paramètres GLOBAUX (jamais poussés aux agents) ;
|
||||
// ai.*, log.*, heartbeat.* restent des défauts applicables aux agents.
|
||||
if (existingKeys.Contains(key)) continue;
|
||||
var agentScoped = !(key.StartsWith("ntfy.", StringComparison.Ordinal)
|
||||
|| key.StartsWith("email.", StringComparison.Ordinal)
|
||||
|| key.StartsWith("sentry.", StringComparison.Ordinal));
|
||||
var category = ResolveCategory(key);
|
||||
groupDb.AppSettings.Add(new Heimdall.Domain.Entities.AppSetting(
|
||||
key, value ?? string.Empty,
|
||||
key.StartsWith("ntfy.", StringComparison.Ordinal) || key.StartsWith("email.", StringComparison.Ordinal)
|
||||
? "integrations" : key.StartsWith("ai.", StringComparison.Ordinal) ? "ai" : "agent",
|
||||
category,
|
||||
key switch
|
||||
{
|
||||
"ntfy.baseUrl" => "Serveur ntfy (URL de base)",
|
||||
@@ -305,11 +338,10 @@ public partial class Program
|
||||
agentScoped));
|
||||
}
|
||||
await groupDb.SaveChangesWithRetryAsync();
|
||||
}
|
||||
|
||||
// Migration douce (#106) : les clés d'intégration déjà présentes en base
|
||||
// (créées avant ce changement avec agentScoped=true) doivent passer en
|
||||
// GLOBAL — jamais exposées aux agents. sentry.dsn n'a plus de rôle
|
||||
// (DSN fixes en appsettings) → suppression.
|
||||
private static async Task MigrateLegacySentryKeysAsync(AppDbContext groupDb)
|
||||
{
|
||||
await groupDb.AppSettings
|
||||
.Where(s => s.Key.StartsWith("ntfy.") || s.Key.StartsWith("email.")
|
||||
|| s.Key.StartsWith("storage.") || s.Key.StartsWith("sentry."))
|
||||
@@ -319,38 +351,43 @@ public partial class Program
|
||||
if (legacySentryDsn is not null)
|
||||
groupDb.AppSettings.Remove(legacySentryDsn);
|
||||
await groupDb.SaveChangesWithRetryAsync();
|
||||
}
|
||||
|
||||
// Seed demo admin + demo site when explicitly enabled (dev & E2E hosts)
|
||||
if (configuration.GetValue<bool>("Seed:DemoOnStartup", false))
|
||||
private static async Task SeedDemoDataAsync(
|
||||
IConfiguration configuration,
|
||||
Microsoft.AspNetCore.Identity.UserManager<Heimdall.Domain.Entities.AppUser> userManager,
|
||||
AppDbContext groupDb)
|
||||
{
|
||||
if (!configuration.GetValue<bool>("Seed:DemoOnStartup", false))
|
||||
return;
|
||||
|
||||
var adminLogin = configuration.GetValue<string>("Seed:AdminLogin")
|
||||
?? Environment.GetEnvironmentVariable("SEED__ADMIN_LOGIN")
|
||||
?? "admin@heimdall.test";
|
||||
var testAdmin = await userManager.FindByEmailAsync(adminLogin);
|
||||
if (testAdmin is null)
|
||||
{
|
||||
var adminLogin = configuration.GetValue<string>("Seed:AdminLogin")
|
||||
?? Environment.GetEnvironmentVariable("SEED__ADMIN_LOGIN")
|
||||
?? "admin@heimdall.test";
|
||||
var testAdmin = await userManager.FindByEmailAsync(adminLogin);
|
||||
if (testAdmin is null)
|
||||
testAdmin = new Heimdall.Domain.Entities.AppUser
|
||||
{
|
||||
testAdmin = new Heimdall.Domain.Entities.AppUser
|
||||
{
|
||||
UserName = adminLogin,
|
||||
Email = adminLogin,
|
||||
DisplayName = configuration.GetValue<string>("Seed:AdminDisplayName")
|
||||
?? Environment.GetEnvironmentVariable("SEED__ADMIN_DISPLAYNAME")
|
||||
?? "Admin"
|
||||
};
|
||||
var adminPassword = configuration["Seed:AdminPassword"]
|
||||
?? Environment.GetEnvironmentVariable("SEED__ADMIN_PASSWORD")
|
||||
?? throw new InvalidOperationException("Seed:AdminPassword is required in config or SEED__ADMIN_PASSWORD env var. Set this env var to create the demo admin on startup.");
|
||||
await userManager.CreateAsync(testAdmin, adminPassword);
|
||||
await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin);
|
||||
}
|
||||
UserName = adminLogin,
|
||||
Email = adminLogin,
|
||||
DisplayName = configuration.GetValue<string>("Seed:AdminDisplayName")
|
||||
?? Environment.GetEnvironmentVariable("SEED__ADMIN_DISPLAYNAME")
|
||||
?? "Admin"
|
||||
};
|
||||
var adminPassword = configuration["Seed:AdminPassword"]
|
||||
?? Environment.GetEnvironmentVariable("SEED__ADMIN_PASSWORD")
|
||||
?? throw new InvalidOperationException("Seed:AdminPassword is required in config or SEED__ADMIN_PASSWORD env var. Set this env var to create the demo admin on startup.");
|
||||
await userManager.CreateAsync(testAdmin, adminPassword);
|
||||
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();
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -362,11 +399,128 @@ public partial class Program
|
||||
|
||||
builder.Services.AddRazorComponents()
|
||||
.AddInteractiveServerComponents();
|
||||
|
||||
// In-memory cache — required by INotificationRateLimiter (singleton)
|
||||
builder.Services.AddMemoryCache();
|
||||
|
||||
// ── Authentication ──────────────────────────────────────────────
|
||||
ConfigureAuthentication(builder);
|
||||
ConfigureMudAndRateLimiting(builder);
|
||||
ConfigureControllers(builder);
|
||||
ConfigureSignalR(builder);
|
||||
|
||||
builder.Services.AddApplication();
|
||||
builder.Services.AddInfrastructure(builder.Configuration);
|
||||
ConfigureSentry(builder);
|
||||
ConfigureAuthScheme(builder);
|
||||
ConfigureBackgroundJobs(builder);
|
||||
ConfigureHttpClients(builder);
|
||||
|
||||
builder.Services.AddScoped<AuthState>();
|
||||
}
|
||||
|
||||
private static void ConfigureMudAndRateLimiting(WebApplicationBuilder builder)
|
||||
{
|
||||
builder.Services.AddMudServices(config =>
|
||||
{
|
||||
config.SnackbarConfiguration.PositionClass = "mud-alert-center-top";
|
||||
config.SnackbarConfiguration.PreventDuplicates = true;
|
||||
config.SnackbarConfiguration.ShowCloseIcon = true;
|
||||
config.SnackbarConfiguration.VisibleStateDuration = 4000;
|
||||
});
|
||||
|
||||
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; });
|
||||
options.AddFixedWindowLimiter("TwoFactor", opt => { opt.PermitLimit = 5; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; });
|
||||
});
|
||||
}
|
||||
|
||||
private static void ConfigureControllers(WebApplicationBuilder builder)
|
||||
{
|
||||
builder.Services.AddControllers(options =>
|
||||
options.Filters.Add<Heimdall.Api.Filters.ExceptionFilter>())
|
||||
.AddJsonOptions(options =>
|
||||
{
|
||||
options.JsonSerializerOptions.Converters.Add(
|
||||
new System.Text.Json.Serialization.JsonStringEnumConverter());
|
||||
})
|
||||
.AddApplicationPart(typeof(Program).Assembly);
|
||||
builder.Services.AddFluentValidationAutoValidation();
|
||||
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(opts =>
|
||||
opts.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter()));
|
||||
builder.Services.AddOpenApi();
|
||||
}
|
||||
|
||||
private static void ConfigureSignalR(WebApplicationBuilder builder)
|
||||
{
|
||||
builder.Services.AddSignalR();
|
||||
builder.Services.AddScoped<IEventBroadcastService, EventBroadcastService>();
|
||||
builder.Services.AddScoped<IConfigBroadcastService, ConfigBroadcastService>();
|
||||
builder.Services.AddScoped<IMonitoringBroadcastService, MonitoringBroadcastService>();
|
||||
builder.Services.AddScoped<INotificationBroadcastService, NotificationBroadcastService>();
|
||||
builder.Services.AddScoped<IAdminBroadcastService, AdminBroadcastService>();
|
||||
}
|
||||
|
||||
private static void ConfigureAuthScheme(WebApplicationBuilder builder)
|
||||
{
|
||||
builder.Services.Configure<Microsoft.AspNetCore.Authentication.AuthenticationOptions>(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||
});
|
||||
|
||||
builder.Services.ConfigureApplicationCookie(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.SameAsRequest;
|
||||
options.ExpireTimeSpan = TimeSpan.FromDays(7);
|
||||
options.SlidingExpiration = true;
|
||||
});
|
||||
}
|
||||
|
||||
private static void ConfigureBackgroundJobs(WebApplicationBuilder builder)
|
||||
{
|
||||
var isTesting = builder.Environment.IsEnvironment(TestingEnvironment);
|
||||
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
|
||||
?? builder.Configuration.GetConnectionString("Default");
|
||||
if (!isTesting && !string.IsNullOrEmpty(connectionString))
|
||||
builder.Services.AddBackgroundJobs(builder.Configuration);
|
||||
}
|
||||
|
||||
private static void ConfigureHttpClients(WebApplicationBuilder builder)
|
||||
{
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddScoped<HeimdallApiClient>();
|
||||
builder.Services.AddScoped<NotificationsHubClient>();
|
||||
builder.Services.AddTransient<TokenRefreshHandler>();
|
||||
builder.Services.AddTransient<SameOriginHttpMessageHandler>();
|
||||
|
||||
var apiBaseUrlConfigured = ApiBaseUrlResolver.IsConfigured(builder.Configuration);
|
||||
var apiBaseUrl = apiBaseUrlConfigured
|
||||
? ApiBaseUrlResolver.ResolveConfigured(builder.Configuration)!
|
||||
: ApiBaseUrlResolver.PlaceholderBase;
|
||||
builder.Services.AddHttpClient("HeimdallApi", client =>
|
||||
{
|
||||
var baseUrl = apiBaseUrl.EndsWith('/') ? apiBaseUrl : apiBaseUrl + "/";
|
||||
client.BaseAddress = new Uri(baseUrl);
|
||||
client.Timeout = TimeSpan.FromSeconds(30);
|
||||
})
|
||||
.AddHttpMessageHandler<TokenRefreshHandler>()
|
||||
.AddHttpMessageHandler<SameOriginHttpMessageHandler>();
|
||||
|
||||
if (apiBaseUrlConfigured)
|
||||
Console.WriteLine($"[DIAG] ApiBaseUrl: {apiBaseUrl} (explicit)");
|
||||
else
|
||||
Console.WriteLine("[DIAG] ApiBaseUrl: same-origin (no explicit config)");
|
||||
}
|
||||
private static void ConfigureAuthentication(WebApplicationBuilder builder)
|
||||
{
|
||||
var jwtKey = builder.Configuration["Jwt:Key"]
|
||||
?? Environment.GetEnvironmentVariable("JWT__KEY")
|
||||
?? throw new InvalidOperationException("JWT:Key is not configured");
|
||||
@@ -460,201 +614,60 @@ public partial class Program
|
||||
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 ───────────────────────────────────────────────
|
||||
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; });
|
||||
// 2FA codes are high-value, low-volume: tighter limit than the login endpoint.
|
||||
options.AddFixedWindowLimiter("TwoFactor", opt => { opt.PermitLimit = 5; opt.Window = TimeSpan.FromMinutes(1); opt.QueueLimit = 0; });
|
||||
});
|
||||
|
||||
// ── Controllers (REST API) ────────────────────────────────────────
|
||||
builder.Services.AddControllers(options =>
|
||||
options.Filters.Add<Heimdall.Api.Filters.ExceptionFilter>())
|
||||
.AddJsonOptions(options =>
|
||||
{
|
||||
// Serialize enums as strings in API responses (e.g. Agent.Status,
|
||||
// Camera.Status) — otherwise the Blazor client fails to parse
|
||||
// numeric enum values into its string-typed models.
|
||||
options.JsonSerializerOptions.Converters.Add(
|
||||
new System.Text.Json.Serialization.JsonStringEnumConverter());
|
||||
})
|
||||
// Explicitly register the Web assembly as an application part.
|
||||
// AddMvcCore only auto-discovers Assembly.GetEntryAssembly(), which is
|
||||
// the test host ("testhost") when CreateTestApplication runs under
|
||||
// xUnit — without this, no /api/* controller is ever mapped in E2E.
|
||||
.AddApplicationPart(typeof(Program).Assembly);
|
||||
builder.Services.AddFluentValidationAutoValidation();
|
||||
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.AddScoped<IMonitoringBroadcastService, MonitoringBroadcastService>();
|
||||
builder.Services.AddScoped<INotificationBroadcastService, NotificationBroadcastService>();
|
||||
builder.Services.AddScoped<IAdminBroadcastService, AdminBroadcastService>();
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
// ── Application & Infrastructure layers ──────────────────────────
|
||||
builder.Services.AddApplication();
|
||||
builder.Services.AddInfrastructure(builder.Configuration);
|
||||
|
||||
// ── Sentry (GlitchTip) — DSN fixe (appsettings), toggle global ──
|
||||
// Le toggle sentry.enabled est lu en base (après AddInfrastructure) :
|
||||
// false -> SDK non initialisé (redémarrage requis pour changer).
|
||||
// Table absente au 1er boot / DB indisponible -> défaut activé.
|
||||
// SKIP en Testing : pas de table app_settings avant les migrations.
|
||||
private static void ConfigureSentry(WebApplicationBuilder builder)
|
||||
{
|
||||
var sentryDsn = builder.Configuration["Sentry:Dsn"]
|
||||
?? Environment.GetEnvironmentVariable("SENTRY_DSN");
|
||||
var isTestingEnv = builder.Environment.IsEnvironment("Testing");
|
||||
var isTestingEnv = builder.Environment.IsEnvironment(TestingEnvironment);
|
||||
var sentryEnabled = !isTestingEnv && IsSentryEnabledFromDb(builder.Services);
|
||||
if (sentryEnabled && !string.IsNullOrEmpty(sentryDsn))
|
||||
{
|
||||
builder.WebHost.UseSentry((SentryAspNetCoreOptions options) =>
|
||||
{
|
||||
options.Dsn = sentryDsn;
|
||||
|
||||
// ── Env & Release ────────────────────────────────────────
|
||||
options.Release = builder.Configuration["Sentry:Release"]
|
||||
?? Environment.GetEnvironmentVariable("SENTRY_RELEASE");
|
||||
|
||||
// ── Error sampling ──────────────────────────────────────
|
||||
options.SampleRate = 1.0f;
|
||||
options.AttachStacktrace = true;
|
||||
options.MaxBreadcrumbs = 100;
|
||||
options.MinimumBreadcrumbLevel = LogLevel.Debug;
|
||||
options.MinimumEventLevel = LogLevel.Error;
|
||||
|
||||
// ── Tracing (Performance) ───────────────────────────────
|
||||
options.TracesSampleRate = double.Parse(
|
||||
builder.Configuration["Sentry:TracesSampleRate"] ?? "0.05",
|
||||
System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
// ── Request body capture ────────────────────────────────
|
||||
options.MaxRequestBodySize = Sentry.Extensibility.RequestSize.Small;
|
||||
|
||||
// ── Structured logs (v5.14+) ────────────────────────────
|
||||
options.EnableLogs = true;
|
||||
|
||||
// ── GlitchTip-specific: disable unsupported features ────
|
||||
options.AutoSessionTracking = false;
|
||||
|
||||
// ── PII & GDPR ──────────────────────────────────────────
|
||||
options.SendDefaultPii = false;
|
||||
options.ServerName = null;
|
||||
|
||||
// ── Enhanced diagnostics ────────────────────────────────
|
||||
options.CaptureBlockingCalls = true;
|
||||
options.CaptureFailedRequests = true;
|
||||
options.IncludeActivityData = true;
|
||||
|
||||
// ── Stack traces ────────────────────────────────────────
|
||||
options.StackTraceMode = Sentry.StackTraceMode.Enhanced;
|
||||
|
||||
// ── BeforeSend — scrub PII before it leaves the SDK ────
|
||||
options.SetBeforeSend((sentryEvent, hint) =>
|
||||
{
|
||||
sentryEvent.ServerName = null;
|
||||
if (sentryEvent.Extra?.ContainsKey("password") == true)
|
||||
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("password");
|
||||
if (sentryEvent.Extra?.ContainsKey("token") == true)
|
||||
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("token");
|
||||
if (sentryEvent.Extra?.ContainsKey("secret") == true)
|
||||
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("secret");
|
||||
|
||||
return sentryEvent;
|
||||
});
|
||||
|
||||
// ── BeforeBreadcrumb — filter noisy breadcrumbs ────────
|
||||
options.SetBeforeBreadcrumb(breadcrumb
|
||||
=> breadcrumb.Category == "Microsoft.AspNetCore.RateLimiting"
|
||||
? null
|
||||
: breadcrumb);
|
||||
});
|
||||
builder.WebHost.UseSentry((SentryAspNetCoreOptions options) => ConfigureSentryOptions(options, builder, sentryDsn));
|
||||
}
|
||||
|
||||
var sentryStatus = !sentryEnabled
|
||||
? "DISABLED (toggle sentry.enabled=false — redémarrage requis)"
|
||||
: string.IsNullOrEmpty(sentryDsn)
|
||||
? "NOT CONFIGURED — errors will NOT be reported to GlitchTip"
|
||||
: "configured (" + sentryDsn[..sentryDsn.IndexOf('@')] + "@...)";
|
||||
var sentryStatus = FormatSentryStatus(sentryEnabled, sentryDsn);
|
||||
Console.WriteLine($"[DIAG] Sentry/GlitchTip DSN: {sentryStatus}");
|
||||
}
|
||||
|
||||
|
||||
// AddIdentity (inside AddInfrastructure) sets Identity.Application as the
|
||||
// default authenticate/challenge scheme. But /_auth/signin signs the
|
||||
// ".Heimdall.Auth" cookie with the "Cookies" scheme. If the default stays
|
||||
// on Identity.Application, UseAuthentication tries to validate the ticket
|
||||
// with a DIFFERENT Data Protection purpose -> the cookie is never accepted
|
||||
// and full page reloads always bounce back to /login.
|
||||
builder.Services.Configure<Microsoft.AspNetCore.Authentication.AuthenticationOptions>(options =>
|
||||
private static void ConfigureSentryOptions(SentryAspNetCoreOptions options, WebApplicationBuilder builder, string sentryDsn)
|
||||
{
|
||||
options.Dsn = sentryDsn;
|
||||
options.Release = builder.Configuration["Sentry:Release"]
|
||||
?? Environment.GetEnvironmentVariable("SENTRY_RELEASE");
|
||||
options.SampleRate = 1.0f;
|
||||
options.AttachStacktrace = true;
|
||||
options.MaxBreadcrumbs = 100;
|
||||
options.MinimumBreadcrumbLevel = LogLevel.Debug;
|
||||
options.MinimumEventLevel = LogLevel.Error;
|
||||
options.TracesSampleRate = double.Parse(
|
||||
builder.Configuration["Sentry:TracesSampleRate"] ?? "0.05",
|
||||
System.Globalization.CultureInfo.InvariantCulture);
|
||||
options.MaxRequestBodySize = Sentry.Extensibility.RequestSize.Small;
|
||||
options.EnableLogs = true;
|
||||
options.AutoSessionTracking = false;
|
||||
options.SendDefaultPii = false;
|
||||
options.ServerName = null;
|
||||
options.CaptureBlockingCalls = true;
|
||||
options.CaptureFailedRequests = true;
|
||||
options.IncludeActivityData = true;
|
||||
options.StackTraceMode = Sentry.StackTraceMode.Enhanced;
|
||||
options.SetBeforeSend(static (sentryEvent, _) =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||
sentryEvent.ServerName = null;
|
||||
if (sentryEvent.Extra?.ContainsKey("password") == true)
|
||||
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("password");
|
||||
if (sentryEvent.Extra?.ContainsKey("token") == true)
|
||||
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("token");
|
||||
if (sentryEvent.Extra?.ContainsKey("secret") == true)
|
||||
(sentryEvent.Extra as IDictionary<string, object?>)?.Remove("secret");
|
||||
return sentryEvent;
|
||||
});
|
||||
|
||||
// Configure Identity cookie AFTER AddInfrastructure (which calls AddIdentity)
|
||||
// AddIdentity sets default paths (/Account/Login) that must be overridden
|
||||
builder.Services.ConfigureApplicationCookie(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.SameAsRequest;
|
||||
options.ExpireTimeSpan = TimeSpan.FromDays(7);
|
||||
options.SlidingExpiration = true;
|
||||
});
|
||||
|
||||
// ── Background jobs (skipped in Testing) ────────────────────────
|
||||
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 ──────────────────────────────────────────────────
|
||||
// Blazor Server monolith: the UI and the API run in the same process,
|
||||
// so requests target the SAME origin as the browser by default. An
|
||||
// explicit ApiBaseUrl (config/env) overrides that for external APIs.
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddScoped<HeimdallApiClient>();
|
||||
builder.Services.AddScoped<NotificationsHubClient>();
|
||||
builder.Services.AddTransient<TokenRefreshHandler>();
|
||||
builder.Services.AddTransient<SameOriginHttpMessageHandler>();
|
||||
var apiBaseUrlConfigured = ApiBaseUrlResolver.IsConfigured(builder.Configuration);
|
||||
var apiBaseUrl = apiBaseUrlConfigured
|
||||
? ApiBaseUrlResolver.ResolveConfigured(builder.Configuration)!
|
||||
: ApiBaseUrlResolver.PlaceholderBase;
|
||||
builder.Services.AddHttpClient("HeimdallApi", client =>
|
||||
{
|
||||
var baseUrl = apiBaseUrl.EndsWith('/') ? apiBaseUrl : apiBaseUrl + "/";
|
||||
client.BaseAddress = new Uri(baseUrl);
|
||||
client.Timeout = TimeSpan.FromSeconds(30);
|
||||
})
|
||||
.AddHttpMessageHandler<TokenRefreshHandler>()
|
||||
.AddHttpMessageHandler<SameOriginHttpMessageHandler>();
|
||||
if (apiBaseUrlConfigured)
|
||||
Console.WriteLine($"[DIAG] ApiBaseUrl: {apiBaseUrl} (explicit)");
|
||||
else
|
||||
Console.WriteLine("[DIAG] ApiBaseUrl: same-origin (no explicit config)");
|
||||
|
||||
builder.Services.AddScoped<AuthState>();
|
||||
options.SetBeforeBreadcrumb(breadcrumb
|
||||
=> breadcrumb.Category == "Microsoft.AspNetCore.RateLimiting"
|
||||
? null
|
||||
: breadcrumb);
|
||||
}
|
||||
|
||||
internal static void ConfigureMiddleware(WebApplication app)
|
||||
@@ -685,7 +698,7 @@ public partial class Program
|
||||
// MapHangfireDashboard est utilisé car UseHangfireDashboard avec
|
||||
// DashboardOptions.Authorization n'existe pas pour les policies ASP.NET.
|
||||
// Skip en Testing : Hangfire y est désactivé (pas de AddHangfire).
|
||||
if (!app.Environment.IsEnvironment("Testing"))
|
||||
if (!app.Environment.IsEnvironment(TestingEnvironment))
|
||||
{
|
||||
app.MapHangfireDashboard("/hangfire", new DashboardOptions
|
||||
{
|
||||
@@ -705,7 +718,7 @@ public partial class Program
|
||||
app.MapHub<AdminHub>("/hubs/admin");
|
||||
|
||||
// Diagnostic: log all mapped endpoints so E2E host mapping issues are visible.
|
||||
if (app.Environment.IsEnvironment("Testing"))
|
||||
if (app.Environment.IsEnvironment(TestingEnvironment))
|
||||
{
|
||||
var dataSource = app.Services.GetRequiredService<Microsoft.AspNetCore.Routing.EndpointDataSource>();
|
||||
var endpoints = dataSource.Endpoints
|
||||
|
||||
Reference in new issue
Block a user