feat(settings): topic ntfy par site, SMTP/ntfy/S3 globaux, DSN GlitchTip fixe + toggle (Fixes #105 #106 #107 #108)

#105 — Topic ntfy cible par site :
- Site.NtfyTopic (migration AddSiteNtfyTopic), UI création/édition SitesPage
- NotificationService.ResolveNtfyTopicAsync : topic du site sinon heimdall_{userId}

#106 — Paramètres SMTP/ntfy/S3 GLOBAUX :
- Seed + sections UI : agentScoped=false pour ntfy.*/email.*/storage.*/sentry.*
- Migration douce au démarrage : UPDATE des clés existantes en base

#107 — GlitchTip : DSN fixes (central projet 6, agent projet 7) dans appsettings,
- plus de champ DSN éditable en UI → switch sentry.enabled (nécessite redémarrage)
- Init Sentry déplacé après AddInfrastructure, lit sentry.enabled en base (fallback true)

#108 — Composants typés : MudNumericField borné (port SMTP, rétention, heartbeat),
- switch pour booléens, select pour log.level — pas de saisie libre
This commit is contained in:
Arnaud Dartois committed 2026-08-12 12:18:52 +02:00
1 parent 85bfdac7ee
commit dc8a24918d
25 files changed
+2485 -153

No files matched your search

+126 -90
View File
@@ -242,7 +242,8 @@ public partial class Program {
"storage.s3.secretKey" => "Clé secrète S3",
"storage.s3.region" => "Région S3",
_ => key
}));
},
agentScoped: false));
}
await groupDb.SaveChangesWithRetryAsync();
@@ -265,12 +266,17 @@ public partial class Program {
["log.level"] = Environment.GetEnvironmentVariable("LOG__LEVEL") ?? "info",
["log.retentionDays"] = Environment.GetEnvironmentVariable("LOG__RETENTION_DAYS") ?? "7",
["heartbeat.interval.seconds"] = Environment.GetEnvironmentVariable("HEARTBEAT__INTERVAL_SECONDS") ?? "30",
["sentry.dsn"] = Environment.GetEnvironmentVariable("SENTRY_DSN"),
["sentry.enabled"] = "true",
};
foreach (var (key, value) in integrationDefaults)
{
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.
var agentScoped = !(key.StartsWith("ntfy.", StringComparison.Ordinal)
|| key.StartsWith("email.", StringComparison.Ordinal)
|| key.StartsWith("sentry.", StringComparison.Ordinal));
groupDb.AppSettings.Add(new Heimdall.Domain.Entities.AppSetting(
key, value ?? string.Empty,
key.StartsWith("ntfy.", StringComparison.Ordinal) || key.StartsWith("email.", StringComparison.Ordinal)
@@ -292,12 +298,27 @@ public partial class Program {
"log.level" => "Niveau de log global (agents + central)",
"log.retentionDays" => "Rétention des logs agents (jours)",
"heartbeat.interval.seconds" => "Intervalle de heartbeat des agents (secondes)",
"sentry.dsn" => "DSN Sentry/GlitchTip (diagnostic)",
"sentry.enabled" => "Autoriser l'envoi des erreurs vers GlitchTip (nécessite un redémarrage)",
_ => key
}));
},
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.
await groupDb.AppSettings
.Where(s => s.Key.StartsWith("ntfy.") || s.Key.StartsWith("email.")
|| s.Key.StartsWith("storage.") || s.Key.StartsWith("sentry."))
.ExecuteUpdateAsync(s => s.SetProperty(x => x.AgentScoped, false));
var legacySentryDsn = await groupDb.AppSettings
.FirstOrDefaultAsync(s => s.Key == "sentry.dsn");
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))
{
@@ -334,92 +355,6 @@ public partial class Program {
internal static void ConfigureServices(WebApplicationBuilder builder)
{
// ── Sentry (GlitchTip) — error tracking, performance & structured logs ──
// Primary: Sentry:Dsn from appsettings.json or env var Sentry__Dsn
// Fallback: legacy SENTRY_DSN env var (Docker backward compat)
// Neither set → DSN is null → Sentry SDK no-ops gracefully
var sentryDsn = builder.Configuration["Sentry:Dsn"]
?? Environment.GetEnvironmentVariable("SENTRY_DSN");
if (!string.IsNullOrEmpty(sentryDsn))
{
builder.WebHost.UseSentry((SentryAspNetCoreOptions options) =>
{
options.Dsn = sentryDsn;
// ── Env & Release ────────────────────────────────────────
// Environment is auto-read from IHostingEnvironment
// Release should be explicitly set (e.g. "heimdall@1.2.3")
options.Release = builder.Configuration["Sentry:Release"]
?? Environment.GetEnvironmentVariable("SENTRY_RELEASE");
// ── Error sampling ──────────────────────────────────────
options.SampleRate = 1.0f; // 100% errors (adjust if volume too high)
options.AttachStacktrace = true; // Stack traces even on CaptureMessage
options.MaxBreadcrumbs = 100; // Breadcrumb buffer size
options.MinimumBreadcrumbLevel = LogLevel.Debug;
options.MinimumEventLevel = LogLevel.Error;
// ── Tracing (Performance) ───────────────────────────────
// GlitchTip counts every transaction as an event.
// 0.05 = 5% sample = good signal-to-noise in production.
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+) ────────────────────────────
// Enables SentrySdk.Logger.LogInfo() etc.
options.EnableLogs = true;
// ── GlitchTip-specific: disable unsupported features ────
// Release Health / Sessions are NOT supported by GlitchTip
options.AutoSessionTracking = false;
// ── PII & GDPR ──────────────────────────────────────────
options.SendDefaultPii = false; // Explicit RGPD-safe default
options.ServerName = null; // Never send hostname
// ── Enhanced diagnostics ────────────────────────────────
options.CaptureBlockingCalls = true; // Detect .Result / .Wait()
options.CaptureFailedRequests = true; // Capture HttpClient 4xx/5xx
options.IncludeActivityData = true; // DiagnosticSource Activity
// ── Stack traces ────────────────────────────────────────
options.StackTraceMode = Sentry.StackTraceMode.Enhanced;
// ── BeforeSend — scrub PII before it leaves the SDK ────
options.SetBeforeSend((sentryEvent, hint) =>
{
// Never send server name (already null above, belt-and-suspenders)
sentryEvent.ServerName = null;
// Remove sensitive extras
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);
});
}
// ── Startup diagnostics ────────────────────────────────────────
var sentryStatus = string.IsNullOrEmpty(sentryDsn)
? "NOT CONFIGURED — errors will NOT be reported to GlitchTip"
: "configured (" + sentryDsn[..sentryDsn.IndexOf('@')] + "@...)";
Console.WriteLine($"[DIAG] Sentry/GlitchTip DSN: {sentryStatus}");
Console.WriteLine($"[DIAG] Environment: {builder.Environment.EnvironmentName}");
Console.WriteLine($"[DIAG] Data Protection keys dir: /var/lib/heimdall/dp-keys");
Console.WriteLine($"[DIAG] Demo seeding: {(builder.Configuration.GetValue<bool>("Seed:DemoOnStartup", false) ? "enabled" : "disabled (set Seed:DemoOnStartup=true to enable)")}");
@@ -575,6 +510,86 @@ public partial class Program {
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é.
var sentryDsn = builder.Configuration["Sentry:Dsn"]
?? Environment.GetEnvironmentVariable("SENTRY_DSN");
var sentryEnabled = 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);
});
}
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('@')] + "@...)";
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
@@ -783,4 +798,25 @@ public partial class Program {
var accept = request.Headers.Accept.ToString();
return accept.Contains("application/json", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Lit le toggle global sentry.enabled en base (défaut true). Table absente
/// au premier démarrage ou DB indisponible -> activé (comportement sûr).
/// </summary>
private static bool IsSentryEnabledFromDb(IServiceCollection services)
{
try
{
using var sp = services.BuildServiceProvider();
using var scope = sp.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<Heimdall.Infrastructure.Data.AppDbContext>();
return db.AppSettings.AsNoTracking()
.FirstOrDefault(s => s.Key == "sentry.enabled")?.Value != "false";
}
catch
{
return true;
}
}
}