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:
1 parent
85bfdac7ee
commit
dc8a24918d
25 files changed
+2485
-153
No files matched your search
@@ -15,6 +15,6 @@
|
||||
// Sentry/GlitchTip — DSN is read from Sentry:Dsn (or env Sentry__Dsn / legacy SENTRY_DSN)
|
||||
// When null/empty, Sentry SDK is not initialized (graceful no-op).
|
||||
"Sentry": {
|
||||
"Dsn": ""
|
||||
"Dsn": "https://5ff158606c674ba8bb59c1b11d2aa04a@glitchtip.tordais.cc/7"
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ public record SiteResponse(
|
||||
string Name,
|
||||
string? Address,
|
||||
string Timezone,
|
||||
string? NtfyTopic,
|
||||
bool Enabled,
|
||||
DateTime CreatedAt);
|
||||
|
||||
|
||||
@@ -4,4 +4,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Commands.CreateSite;
|
||||
|
||||
public record CreateSiteCommand(string Name, string? Address, string? Timezone) : IRequest<ServiceResult<SiteWithTokenResponse>>;
|
||||
public record CreateSiteCommand(string Name, string? Address, string? Timezone, string? NtfyTopic = null) : IRequest<ServiceResult<SiteWithTokenResponse>>;
|
||||
@@ -19,7 +19,7 @@ public class CreateSiteHandler : IRequestHandler<CreateSiteCommand, ServiceResul
|
||||
if (existing)
|
||||
return ServiceResult<SiteWithTokenResponse>.Conflict("A site with this name already exists");
|
||||
|
||||
var site = new Site(request.Name, request.Address, request.Timezone);
|
||||
var site = new Site(request.Name, request.Address, request.Timezone, request.NtfyTopic);
|
||||
|
||||
// Generate a registration token at creation so the UI can show it
|
||||
// immediately (POST /api/sites returns SiteWithTokenResponse).
|
||||
|
||||
@@ -4,4 +4,4 @@ using MediatR;
|
||||
|
||||
namespace Heimdall.Application.Sites.Commands.UpdateSite;
|
||||
|
||||
public record UpdateSiteCommand(Guid Id, string Name, string? Address, string? Timezone) : IRequest<ServiceResult<SiteResponse>>;
|
||||
public record UpdateSiteCommand(Guid Id, string Name, string? Address, string? Timezone, string? NtfyTopic = null) : IRequest<ServiceResult<SiteResponse>>;
|
||||
@@ -16,10 +16,10 @@ public class UpdateSiteHandler : IRequestHandler<UpdateSiteCommand, ServiceResul
|
||||
if (site is null)
|
||||
return ServiceResult<SiteResponse>.NotFound("Site not found");
|
||||
|
||||
site.Update(request.Name, request.Address, request.Timezone);
|
||||
site.Update(request.Name, request.Address, request.Timezone, request.NtfyTopic);
|
||||
await _context.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult<SiteResponse>.Success(new SiteResponse(
|
||||
site.Id, site.Name, site.Address, site.Timezone, site.Enabled, site.CreatedAt));
|
||||
site.Id, site.Name, site.Address, site.Timezone, site.NtfyTopic, site.Enabled, site.CreatedAt));
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,6 @@ public class GetSiteHandler : IRequestHandler<GetSiteQuery, ServiceResult<SiteRe
|
||||
return ServiceResult<SiteResponse>.NotFound("Site not found");
|
||||
|
||||
return ServiceResult<SiteResponse>.Success(new SiteResponse(
|
||||
site.Id, site.Name, site.Address, site.Timezone, site.Enabled, site.CreatedAt));
|
||||
site.Id, site.Name, site.Address, site.Timezone, site.NtfyTopic, site.Enabled, site.CreatedAt));
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ public class GetSitesHandler : IRequestHandler<GetSitesQuery, ServiceResult<Page
|
||||
.Skip((request.Page - 1) * request.PageSize)
|
||||
.Take(request.PageSize)
|
||||
.Select(s => new SiteResponse(
|
||||
s.Id, s.Name, s.Address, s.Timezone, s.Enabled, s.CreatedAt))
|
||||
s.Id, s.Name, s.Address, s.Timezone, s.NtfyTopic, s.Enabled, s.CreatedAt))
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return ServiceResult<PagedResult<SiteResponse>>.Success(
|
||||
|
||||
@@ -9,6 +9,9 @@ public class Site : Entity<Guid>, IAuditableEntity, ISoftDeletable
|
||||
public string Timezone { get; private set; } = "UTC";
|
||||
public bool Enabled { get; private set; } = true;
|
||||
|
||||
/// <summary>Topic ntfy dédié pour les notifications de ce site (null → topic personnel utilisateur).</summary>
|
||||
public string? NtfyTopic { get; private set; }
|
||||
|
||||
/// <summary>Hashed registration token (SHA256) for agent enrollment.</summary>
|
||||
public string? RegistrationTokenHash { get; private set; }
|
||||
|
||||
@@ -36,19 +39,21 @@ public class Site : Entity<Guid>, IAuditableEntity, ISoftDeletable
|
||||
|
||||
private Site() { } // EF Core
|
||||
|
||||
public Site(string name, string? address = null, string? timezone = null)
|
||||
public Site(string name, string? address = null, string? timezone = null, string? ntfyTopic = null)
|
||||
: base(Guid.NewGuid())
|
||||
{
|
||||
Name = name;
|
||||
Address = address;
|
||||
Timezone = timezone ?? "UTC";
|
||||
NtfyTopic = ntfyTopic;
|
||||
}
|
||||
|
||||
public void Update(string name, string? address, string? timezone)
|
||||
public void Update(string name, string? address, string? timezone, string? ntfyTopic = null)
|
||||
{
|
||||
Name = name;
|
||||
Address = address;
|
||||
Timezone = timezone ?? Timezone;
|
||||
NtfyTopic = ntfyTopic;
|
||||
}
|
||||
|
||||
public void GenerateRegistrationToken(string tokenHash, DateTime expiresAt)
|
||||
|
||||
+2217
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,28 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Heimdall.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddSiteNtfyTopic : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "NtfyTopic",
|
||||
table: "sites",
|
||||
type: "text",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "NtfyTopic",
|
||||
table: "sites");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1453,6 +1453,9 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<string>("NtfyTopic")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("RegistrationTokenHash")
|
||||
.HasMaxLength(128)
|
||||
.IsUnicode(false)
|
||||
|
||||
@@ -111,7 +111,7 @@ public class NotificationService : INotificationService
|
||||
|
||||
if (config.NtfyEnabled)
|
||||
{
|
||||
var topic = $"heimdall_{userId}";
|
||||
var topic = await ResolveNtfyTopicAsync(notification, userId, ct);
|
||||
await _ntfyService.SendNotificationAsync(
|
||||
topic,
|
||||
notification.Title,
|
||||
@@ -125,6 +125,26 @@ public class NotificationService : INotificationService
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Résout le topic ntfy cible d'une notification (ticket #105) :
|
||||
/// topic du site si défini, sinon topic personnel <c>heimdall_{userId}</c>.
|
||||
/// </summary>
|
||||
private async Task<string> ResolveNtfyTopicAsync(Notification notification, Guid userId, CancellationToken ct)
|
||||
{
|
||||
if (notification.SiteId is { } siteId)
|
||||
{
|
||||
var siteTopic = await _context.Sites
|
||||
.AsNoTracking()
|
||||
.Where(s => s.Id == siteId)
|
||||
.Select(s => s.NtfyTopic)
|
||||
.FirstOrDefaultAsync(ct);
|
||||
if (!string.IsNullOrWhiteSpace(siteTopic))
|
||||
return siteTopic;
|
||||
}
|
||||
|
||||
return $"heimdall_{userId}";
|
||||
}
|
||||
|
||||
public async Task<int> GetUnreadCountAsync(Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
return await _context.Notifications
|
||||
|
||||
@@ -80,6 +80,8 @@ else
|
||||
<MudTextField @bind-Value="_newAddress" Label="Adresse" Variant="Variant.Outlined" Class="mb-4" />
|
||||
<TimezoneAutocomplete @bind-Value="_newTimezone" Class="mb-4"
|
||||
HelperText="Recherche par ville ou identifiant (défaut: UTC)" />
|
||||
<MudTextField @bind-Value="_newNtfyTopic" Label="Topic ntfy (optionnel)" Variant="Variant.Outlined" Class="mb-4"
|
||||
HelperText="Topic dédié pour les notifications de ce site. Vide = topic personnel de l'utilisateur." />
|
||||
@if (!string.IsNullOrEmpty(_creationError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_creationError</MudAlert>
|
||||
@@ -130,6 +132,8 @@ else
|
||||
<MudTextField @bind-Value="_editAddress" Label="Adresse" Variant="Variant.Outlined" Class="mb-4" />
|
||||
<TimezoneAutocomplete @bind-Value="_editTimezone" Class="mb-4"
|
||||
HelperText="Recherche par ville ou identifiant (défaut: UTC)" />
|
||||
<MudTextField @bind-Value="_editNtfyTopic" Label="Topic ntfy (optionnel)" Variant="Variant.Outlined" Class="mb-4"
|
||||
HelperText="Topic dédié pour les notifications de ce site. Vide = topic personnel de l'utilisateur." />
|
||||
@if (!string.IsNullOrEmpty(_editError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_editError</MudAlert>
|
||||
@@ -227,6 +231,7 @@ else
|
||||
private string _newName = "";
|
||||
private string? _newAddress;
|
||||
private string? _newTimezone;
|
||||
private string? _newNtfyTopic;
|
||||
private string _creationError = "";
|
||||
private string _createdToken = "";
|
||||
private bool IsCreateDisabled => _saving || !string.IsNullOrEmpty(_createdToken);
|
||||
@@ -247,6 +252,7 @@ else
|
||||
private string _editName = "";
|
||||
private string? _editAddress;
|
||||
private string? _editTimezone;
|
||||
private string? _editNtfyTopic;
|
||||
private string _editError = "";
|
||||
|
||||
/// <summary>URL publique du serveur Heimdall (utilisée dans le compose généré).</summary>
|
||||
@@ -305,6 +311,7 @@ else
|
||||
_newName = "";
|
||||
_newAddress = null;
|
||||
_newTimezone = null;
|
||||
_newNtfyTopic = null;
|
||||
}
|
||||
|
||||
private async Task ConfirmCreate()
|
||||
@@ -314,7 +321,7 @@ else
|
||||
_creationError = "";
|
||||
try
|
||||
{
|
||||
var result = await Api.CreateSiteAsync(_newName, _newAddress, _newTimezone);
|
||||
var result = await Api.CreateSiteAsync(_newName, _newAddress, _newTimezone, _newNtfyTopic);
|
||||
if (result is null) { _creationError = "Erreur lors de la création"; return; }
|
||||
_createdToken = result.RegistrationToken ?? "Token non disponible";
|
||||
Snackbar.Add("Site créé avec succès", Severity.Success);
|
||||
@@ -362,6 +369,7 @@ else
|
||||
_editName = site.Name;
|
||||
_editAddress = site.Address;
|
||||
_editTimezone = site.Timezone;
|
||||
_editNtfyTopic = site.NtfyTopic;
|
||||
_editError = "";
|
||||
_showEdit = true;
|
||||
}
|
||||
@@ -373,7 +381,7 @@ else
|
||||
_editError = "";
|
||||
try
|
||||
{
|
||||
var ok = await Api.UpdateSiteAsync(_editId, _editName, _editAddress, _editTimezone);
|
||||
var ok = await Api.UpdateSiteAsync(_editId, _editName, _editAddress, _editTimezone, _editNtfyTopic);
|
||||
if (!ok) { _editError = "Erreur lors de la mise à jour"; return; }
|
||||
Snackbar.Add("Site modifié avec succès", Severity.Success);
|
||||
_showEdit = false;
|
||||
|
||||
@@ -31,11 +31,10 @@
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" md="6">
|
||||
<MudTextField T="string" Label="Rétention des logs agents (jours)" Variant="Variant.Outlined"
|
||||
Type="InputType.Number"
|
||||
Value="@GetValue("log.retentiondays")"
|
||||
ValueChanged="OnRetentionChanged"
|
||||
HelperText="Durée de conservation des logs remontés par les agents." />
|
||||
<MudNumericField T="int?" Label="Rétention des logs agents (jours)" Variant="Variant.Outlined"
|
||||
Value="@(int.TryParse(GetValue("log.retentiondays"), out var r) ? r : null)"
|
||||
ValueChanged="OnRetentionChanged" Min="1" Max="3650"
|
||||
HelperText="Durée de conservation des logs remontés par les agents." />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
@@ -44,11 +43,10 @@
|
||||
</MudText>
|
||||
<MudGrid>
|
||||
<MudItem xs="12" md="6">
|
||||
<MudTextField T="string" Label="Intervalle de heartbeat (secondes)" Variant="Variant.Outlined"
|
||||
Type="InputType.Number"
|
||||
Value="@GetValue("heartbeat.interval.seconds")"
|
||||
ValueChanged="OnHeartbeatChanged"
|
||||
HelperText="Fréquence de la remontée d'état des agents vers le central." />
|
||||
<MudNumericField T="int?" Label="Intervalle de heartbeat (secondes)" Variant="Variant.Outlined"
|
||||
Value="@(int.TryParse(GetValue("heartbeat.interval.seconds"), out var h) ? h : null)"
|
||||
ValueChanged="OnHeartbeatChanged" Min="5" Max="3600"
|
||||
HelperText="Fréquence de la remontée d'état des agents vers le central." />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
@@ -56,13 +54,13 @@
|
||||
<i class="fas fa-bug mr-1" style="color: var(--mud-palette-primary);"></i> Diagnostic
|
||||
</MudText>
|
||||
<MudGrid>
|
||||
<MudItem xs="12" md="6">
|
||||
<MudTextField T="string" Label="DSN Sentry / GlitchTip" Variant="Variant.Outlined"
|
||||
Type="InputType.Password"
|
||||
Value="@SecretValue("sentry.dsn")"
|
||||
ValueChanged="OnSentryDsnChanged"
|
||||
Placeholder="•••••••• (déjà configuré)"
|
||||
HelperText="Endpoint de remontée d'erreurs. Nécessite un redémarrage pour être pris en compte." />
|
||||
<MudItem xs="12">
|
||||
<MudSwitch T="bool"
|
||||
Value="@(GetValue("sentry.enabled")?.Equals("true", StringComparison.OrdinalIgnoreCase) == true)"
|
||||
ValueChanged="OnSentryEnabledChanged"
|
||||
Color="Color.Primary"
|
||||
Label="Envoyer les erreurs vers GlitchTip"
|
||||
HelperText="Le DSN est fixe (configuré par l'application). Nécessite un redémarrage pour être pris en compte." />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
</MudPaper>
|
||||
@@ -85,16 +83,10 @@
|
||||
private string? GetValue(string key)
|
||||
=> _settings.FirstOrDefault(s => s.Key == key)?.Value;
|
||||
|
||||
private string SecretValue(string key)
|
||||
{
|
||||
var v = GetValue(key);
|
||||
return v is null or "" or "***REDACTED***" ? string.Empty : v;
|
||||
}
|
||||
|
||||
private Task OnLogLevelChanged(string v) => SaveValueAsync("log.level", v);
|
||||
private Task OnRetentionChanged(string v) => SaveValueAsync("log.retentiondays", v);
|
||||
private Task OnHeartbeatChanged(string v) => SaveValueAsync("heartbeat.interval.seconds", v);
|
||||
private Task OnSentryDsnChanged(string v) => SaveValueAsync("sentry.dsn", v);
|
||||
private Task OnRetentionChanged(int? v) => SaveValueAsync("log.retentiondays", v?.ToString() ?? "");
|
||||
private Task OnHeartbeatChanged(int? v) => SaveValueAsync("heartbeat.interval.seconds", v?.ToString() ?? "");
|
||||
private Task OnSentryEnabledChanged(bool v) => SaveValueAsync("sentry.enabled", v ? "true" : "false");
|
||||
|
||||
private async Task SaveValueAsync(string key, string? value)
|
||||
{
|
||||
|
||||
@@ -56,10 +56,9 @@
|
||||
HelperText="Ex : smtp.gmail.com" />
|
||||
</MudItem>
|
||||
<MudItem xs="6" md="2">
|
||||
<MudTextField T="string" Label="Port SMTP" Variant="Variant.Outlined"
|
||||
Type="InputType.Number"
|
||||
Value="@GetValue("email.smtpport")"
|
||||
ValueChanged="OnSmtpPortChanged" />
|
||||
<MudNumericField T="int?" Label="Port SMTP" Variant="Variant.Outlined"
|
||||
Value="@(int.TryParse(GetValue("email.smtpport"), out var p) ? p : null)"
|
||||
ValueChanged="OnSmtpPortChanged" Min="1" Max="65535" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" md="3">
|
||||
<MudTextField T="string" Label="Utilisateur SMTP" Variant="Variant.Outlined"
|
||||
@@ -135,7 +134,7 @@
|
||||
private Task OnFromAddressChanged(string v) => SaveValueAsync("email.fromaddress", v);
|
||||
private Task OnFromNameChanged(string v) => SaveValueAsync("email.fromname", v);
|
||||
private Task OnSmtpHostChanged(string v) => SaveValueAsync("email.smtphost", v);
|
||||
private Task OnSmtpPortChanged(string v) => SaveValueAsync("email.smtpport", v);
|
||||
private Task OnSmtpPortChanged(int? v) => SaveValueAsync("email.smtpport", v?.ToString() ?? "");
|
||||
private Task OnUsernameChanged(string v) => SaveValueAsync("email.username", v);
|
||||
private Task OnPasswordChanged(string v) => SaveValueAsync("email.password", v);
|
||||
private Task OnUseSslChanged(bool v) => SaveValueAsync("email.usessl", v ? "true" : "false");
|
||||
@@ -187,7 +186,7 @@
|
||||
await Api.CreateSettingAsync(new CreateAppSettingRequest(
|
||||
Key: key, Value: value,
|
||||
Category: "integrations",
|
||||
Description: key, ValueType: "string", AllowedValues: null, AgentScoped: true));
|
||||
Description: key, ValueType: "string", AllowedValues: null, AgentScoped: false));
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -125,7 +125,7 @@
|
||||
Key: key, Value: value, Category: "storage",
|
||||
Description: key.StartsWith("storage.s3.secretKey", StringComparison.Ordinal)
|
||||
? "Clé secrète S3" : key,
|
||||
ValueType: "string", AllowedValues: null, AgentScoped: true));
|
||||
ValueType: "string", AllowedValues: null, AgentScoped: false));
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
+126
-90
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -96,6 +96,7 @@ public record SiteItem(
|
||||
[property: JsonPropertyName("name")] string Name,
|
||||
[property: JsonPropertyName("address")] string? Address,
|
||||
[property: JsonPropertyName("timezone")] string Timezone,
|
||||
[property: JsonPropertyName("ntfyTopic")] string? NtfyTopic,
|
||||
[property: JsonPropertyName("enabled")] bool Enabled,
|
||||
[property: JsonPropertyName("createdAt")] DateTime CreatedAt);
|
||||
|
||||
|
||||
@@ -265,20 +265,20 @@ public class HeimdallApiClient
|
||||
return await client.GetFromJsonAsync<SiteItem>($"api/sites/{id}", Json);
|
||||
}
|
||||
|
||||
public async Task<SiteWithTokenResult?> CreateSiteAsync(string name, string? address, string? timezone)
|
||||
public async Task<SiteWithTokenResult?> CreateSiteAsync(string name, string? address, string? timezone, string? ntfyTopic = null)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/sites",
|
||||
new { name, address, timezone }, Json);
|
||||
new { name, address, timezone, ntfyTopic }, Json);
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
return await response.Content.ReadFromJsonAsync<SiteWithTokenResult>(Json);
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateSiteAsync(Guid id, string name, string? address, string? timezone)
|
||||
public async Task<bool> UpdateSiteAsync(Guid id, string name, string? address, string? timezone, string? ntfyTopic = null)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PutAsJsonAsync($"api/sites/{id}",
|
||||
new { name, address, timezone }, Json);
|
||||
new { name, address, timezone, ntfyTopic }, Json);
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,6 @@
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"Sentry": {
|
||||
"Dsn": ""
|
||||
"Dsn": "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6"
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ public class DashboardTests : PageTestBase
|
||||
DateTime.UtcNow));
|
||||
|
||||
Handler.OnGet("api/sites", new PagedData<SiteItem>(
|
||||
[new SiteItem(SiteId, "Site Principal", "12 rue des Caméras", "Europe/Paris", true, DateTime.UtcNow.AddDays(-10))],
|
||||
[new SiteItem(SiteId, "Site Principal", "12 rue des Caméras", "Europe/Paris", null, true, DateTime.UtcNow.AddDays(-10))],
|
||||
1, 1, 5));
|
||||
|
||||
Handler.OnGet("api/agents", new PagedData<AgentItem>(
|
||||
|
||||
@@ -16,7 +16,7 @@ public class SiteDetailTests : PageTestBase
|
||||
public void SiteDetail_AfficheInformations()
|
||||
{
|
||||
Handler.OnGet("api/sites/", new SiteItem(
|
||||
SiteId, "Site Principal", "12 rue des Caméras", "Europe/Paris", true, DateTime.UtcNow.AddDays(-10)));
|
||||
SiteId, "Site Principal", "12 rue des Caméras", "Europe/Paris", null, true, DateTime.UtcNow.AddDays(-10)));
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<SiteDetail>(p => p.Add(x => x.Id, SiteId));
|
||||
@@ -45,7 +45,7 @@ public class SiteDetailTests : PageTestBase
|
||||
public void SiteDetail_GenererToken_AfficheDockerCompose()
|
||||
{
|
||||
Handler.OnGet("api/sites/", new SiteItem(
|
||||
SiteId, "Site Principal", null, "UTC", true, DateTime.UtcNow.AddDays(-10)));
|
||||
SiteId, "Site Principal", null, "UTC", null, true, DateTime.UtcNow.AddDays(-10)));
|
||||
Handler.On(HttpMethod.Post, "api/sites/", new TokenResult("tok-detail-42", DateTime.UtcNow.AddHours(24)));
|
||||
LoginAs();
|
||||
|
||||
@@ -67,7 +67,7 @@ public class SiteDetailTests : PageTestBase
|
||||
public void SiteDetail_CopierDockerCompose_AppellePressePapier()
|
||||
{
|
||||
Handler.OnGet("api/sites/", new SiteItem(
|
||||
SiteId, "Site Principal", null, "UTC", true, DateTime.UtcNow.AddDays(-10)));
|
||||
SiteId, "Site Principal", null, "UTC", null, true, DateTime.UtcNow.AddDays(-10)));
|
||||
Handler.On(HttpMethod.Post, "api/sites/", new TokenResult("tok-detail-42", DateTime.UtcNow.AddHours(24)));
|
||||
JSInterop.SetupVoid("navigator.clipboard.writeText", _ => true).SetVoidResult();
|
||||
LoginAs();
|
||||
@@ -91,7 +91,7 @@ public class SiteDetailTests : PageTestBase
|
||||
public void SiteDetail_NavigationCameras_Redirige()
|
||||
{
|
||||
Handler.OnGet("api/sites/", new SiteItem(
|
||||
SiteId, "Site Principal", null, "UTC", true, DateTime.UtcNow.AddDays(-10)));
|
||||
SiteId, "Site Principal", null, "UTC", null, true, DateTime.UtcNow.AddDays(-10)));
|
||||
LoginAs();
|
||||
|
||||
var nav = Services.GetRequiredService<BunitNavigationManager>();
|
||||
@@ -123,7 +123,7 @@ public class SiteDetailTests : PageTestBase
|
||||
// Routes spécifiques AVANT la route générique (le handler matche par substring).
|
||||
Handler.OnGet($"api/sites/{SiteId}/credentials", Array.Empty<SiteCredentialItem>());
|
||||
Handler.OnGet("api/sites/", new SiteItem(
|
||||
SiteId, "Site Principal", null, "UTC", true, DateTime.UtcNow.AddDays(-10)));
|
||||
SiteId, "Site Principal", null, "UTC", null, true, DateTime.UtcNow.AddDays(-10)));
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<SiteDetail>(p => p.Add(x => x.Id, SiteId));
|
||||
@@ -141,7 +141,7 @@ public class SiteDetailTests : PageTestBase
|
||||
Credential("compte NVR", "nvr", DateTime.UtcNow.AddHours(-1)),
|
||||
});
|
||||
Handler.OnGet("api/sites/", new SiteItem(
|
||||
SiteId, "Site Principal", null, "UTC", true, DateTime.UtcNow.AddDays(-10)));
|
||||
SiteId, "Site Principal", null, "UTC", null, true, DateTime.UtcNow.AddDays(-10)));
|
||||
LoginAs();
|
||||
|
||||
var cut = RenderPage<SiteDetail>(p => p.Add(x => x.Id, SiteId));
|
||||
@@ -161,7 +161,7 @@ public class SiteDetailTests : PageTestBase
|
||||
{
|
||||
Handler.OnGet($"api/sites/{SiteId}/credentials", new List<SiteCredentialItem>());
|
||||
Handler.OnGet("api/sites/", new SiteItem(
|
||||
SiteId, "Site Principal", null, "UTC", true, DateTime.UtcNow.AddDays(-10)));
|
||||
SiteId, "Site Principal", null, "UTC", null, true, DateTime.UtcNow.AddDays(-10)));
|
||||
Handler.On(HttpMethod.Post, $"api/sites/{SiteId}/credentials",
|
||||
Credential("admin principal", "admin"));
|
||||
LoginAs();
|
||||
@@ -203,7 +203,7 @@ public class SiteDetailTests : PageTestBase
|
||||
var cred = Credential("admin principal", "admin");
|
||||
Handler.OnGet($"api/sites/{SiteId}/credentials", new List<SiteCredentialItem> { cred });
|
||||
Handler.OnGet("api/sites/", new SiteItem(
|
||||
SiteId, "Site Principal", null, "UTC", true, DateTime.UtcNow.AddDays(-10)));
|
||||
SiteId, "Site Principal", null, "UTC", null, true, DateTime.UtcNow.AddDays(-10)));
|
||||
Handler.On(HttpMethod.Delete, $"api/sites/{SiteId}/credentials/{cred.Id}", System.Net.HttpStatusCode.NoContent);
|
||||
LoginAs();
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ public class SitesPageTests : PageTestBase
|
||||
private static readonly Guid SiteId = Guid.NewGuid();
|
||||
|
||||
private static SiteItem Site(string name = "Site Alpha") =>
|
||||
new(SiteId, name, "1 rue de la Surveillance", "Europe/Paris", true, DateTime.UtcNow.AddDays(-5));
|
||||
new(SiteId, name, "1 rue de la Surveillance", "Europe/Paris", null, true, DateTime.UtcNow.AddDays(-5));
|
||||
|
||||
[Fact]
|
||||
public void SitesPage_AfficheListeDesSites()
|
||||
|
||||
@@ -21,7 +21,7 @@ public class AgentDefaultsSectionTests : PageTestBase
|
||||
Setting("log.level", "info"),
|
||||
Setting("log.retentiondays", "7"),
|
||||
Setting("heartbeat.interval.seconds", "30"),
|
||||
Setting("sentry.dsn", "***REDACTED***"),
|
||||
Setting("sentry.enabled", "true"),
|
||||
});
|
||||
LoginAs();
|
||||
|
||||
@@ -32,7 +32,7 @@ public class AgentDefaultsSectionTests : PageTestBase
|
||||
cut.Markup.ShouldContain("Niveau de log global");
|
||||
cut.Markup.ShouldContain("Rétention des logs agents");
|
||||
cut.Markup.ShouldContain("Intervalle de heartbeat");
|
||||
cut.Markup.ShouldContain("DSN Sentry / GlitchTip");
|
||||
cut.Markup.ShouldContain("Envoyer les erreurs vers GlitchTip");
|
||||
});
|
||||
}
|
||||
|
||||
@@ -76,4 +76,26 @@ public class AgentDefaultsSectionTests : PageTestBase
|
||||
r.RequestUri!.AbsolutePath.Contains("heartbeat.interval.seconds", StringComparison.OrdinalIgnoreCase));
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AgentDefaults_ToggleSentry_AppellePutAvecBonneCle()
|
||||
{
|
||||
Handler.OnGet("api/settings", new List<AppSettingItem> { Setting("sentry.enabled", "false") });
|
||||
Handler.On(HttpMethod.Put, "api/settings/sentry.enabled", System.Net.HttpStatusCode.OK);
|
||||
LoginAs();
|
||||
|
||||
var cut = Render<AgentDefaultsSection>();
|
||||
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Envoyer les erreurs vers GlitchTip"));
|
||||
|
||||
// Le switch sentry.enabled est le seul input[type=checkbox] de la section
|
||||
// (MudSwitch déclenche onchange, pas onclick)
|
||||
cut.FindAll("input[type=checkbox]")[0].Change(true);
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
Handler.Requests.ShouldContain(r =>
|
||||
r.Method == HttpMethod.Put &&
|
||||
r.RequestUri!.AbsolutePath.Contains("sentry.enabled", StringComparison.OrdinalIgnoreCase));
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user