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:
Arnaud Dartois authored and Arnaud Dartois committed 2026-08-20 14:13:06 +02:00
1 parent f7e6b0cec3
commit 4792b69e46
63 files changed
+8711 -563

No files matched your search

@@ -4,7 +4,7 @@
@inject HeimdallApiClient Api
@inject ISnackbar Snackbar
@inject NavigationManager Nav
@implements IDisposable
@implements IAsyncDisposable
<MudText Typo="Typo.h1" Class="mb-6">
<MudIcon Icon="@Icons.Material.Filled.Dns" Class="mr-2" />
@@ -99,6 +99,363 @@ else
</MudItem>
</MudGrid>
@* ─── Hardware Inventory ─── *@
<MudGrid Class="mt-4">
@* ─── CPU Inventory ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Processeur" Icon="@Icons.Material.Filled.Memory" Elevation="2">
<MudGrid>
@if (_agent.CpuModel is not null)
{
<MudItem xs="12">
<MudText Typo="Typo.body2" Color="Color.Secondary">Modèle</MudText>
<MudText Typo="Typo.body1" Class="font-weight-medium">@_agent.CpuModel</MudText>
</MudItem>
}
@if (_agent.CpuVendor is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Fabricant</MudText>
<MudText Typo="Typo.body1">@_agent.CpuVendor</MudText>
</MudItem>
}
@if (_agent.CpuArchitecture is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Architecture</MudText>
<MudText Typo="Typo.body1">@_agent.CpuArchitecture</MudText>
</MudItem>
}
@if (_agent.PhysicalCores.HasValue)
{
<MudItem xs="4">
<MudText Typo="Typo.body2" Color="Color.Secondary">Cœurs physiques</MudText>
<MudText Typo="Typo.body1">@_agent.PhysicalCores</MudText>
</MudItem>
}
@if (_agent.LogicalCores.HasValue)
{
<MudItem xs="4">
<MudText Typo="Typo.body2" Color="Color.Secondary">Cœurs logiques</MudText>
<MudText Typo="Typo.body1">@_agent.LogicalCores</MudText>
</MudItem>
}
@if (_agent.ThreadsPerCore.HasValue)
{
<MudItem xs="4">
<MudText Typo="Typo.body2" Color="Color.Secondary">Threads/noyau</MudText>
<MudText Typo="Typo.body1">@_agent.ThreadsPerCore</MudText>
</MudItem>
}
@if (_agent.CpuFrequencyMhz.HasValue)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Fréquence</MudText>
<MudText Typo="Typo.body1">@($"{_agent.CpuFrequencyMhz:F0} MHz")</MudText>
</MudItem>
}
@if (_agent.CpuCacheBytes.HasValue && _agent.CpuCacheBytes > 0)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Cache</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.CpuCacheBytes.Value)</MudText>
</MudItem>
}
@if (!string.IsNullOrEmpty(_agent.CpuFlags))
{
<MudItem xs="12" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Instructions clés</MudText>
<div class="d-flex flex-wrap gap-1 mt-1">
@foreach (var flag in _agent.CpuFlags.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
<MudChip T="string" Size="Size.Small" Color="Color.Info" Variant="Variant.Outlined">@flag</MudChip>
}
</div>
</MudItem>
}
</MudGrid>
</SectionCard>
</MudItem>
@* ─── Memory & Disk Inventory ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Mémoire & Stockage" Icon="@Icons.Material.Filled.Storage" Elevation="2">
<MudGrid>
@if (_agent.MemTotalBytes.HasValue)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Mémoire totale</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.MemTotalBytes.Value)</MudText>
</MudItem>
}
@if (_agent.MemAvailableBytes.HasValue)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Mémoire dispo</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.MemAvailableBytes.Value)</MudText>
</MudItem>
}
@if (_agent.SwapTotalBytes.HasValue && _agent.SwapTotalBytes > 0)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Swap total</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.SwapTotalBytes.Value)</MudText>
</MudItem>
}
@if (_agent.SwapFreeBytes.HasValue && _agent.SwapTotalBytes is > 0)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Swap dispo</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.SwapFreeBytes.Value)</MudText>
</MudItem>
}
@if (_agent.ContainerMemoryLimitBytes.HasValue)
{
<MudItem xs="12" Class="mt-2">
<MudChip T="string" Size="Size.Small" Color="Color.Warning">
Limite conteneur : @FormatBytes(_agent.ContainerMemoryLimitBytes.Value)
</MudChip>
</MudItem>
}
@if (!string.IsNullOrEmpty(_agent.DiskInventoryJson))
{
<MudItem xs="12" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Disques</MudText>
@{
var disks = ParseDiskJson(_agent.DiskInventoryJson);
}
@if (disks.Count > 0)
{
<MudTable Items="@disks" Dense="true" Hover="true" Elevation="0" Class="mt-1">
<HeaderContent>
<MudTh>Point de montage</MudTh>
<MudTh>FS</MudTh>
<MudTh>Taille</MudTh>
<MudTh>Utilisé</MudTh>
<MudTh>Type</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Point de montage">
<MudText Typo="Typo.body2">@context.MountPoint</MudText>
</MudTd>
<MudTd DataLabel="FS">
<MudText Typo="Typo.body2">@context.FileSystem</MudText>
</MudTd>
<MudTd DataLabel="Taille">
<MudText Typo="Typo.body2">@(context.TotalBytes.HasValue ? FormatBytes(context.TotalBytes.Value) : "-")</MudText>
</MudTd>
<MudTd DataLabel="Utilisé">
<MudText Typo="Typo.body2">@(context.UsedBytes.HasValue ? FormatBytes(context.UsedBytes.Value) : "-")</MudText>
</MudTd>
<MudTd DataLabel="Type">
<MudChip T="string" Size="Size.Small"
Color="@(context.Type == "SSD" ? Color.Success : Color.Default)">
@context.Type
</MudChip>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-1">Aucun disque détecté</MudText>
}
</MudItem>
}
</MudGrid>
</SectionCard>
</MudItem>
</MudGrid>
<MudGrid Class="mt-4">
@* ─── GPU Inventory ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="GPU" Icon="@Icons.Material.Filled.Videocam" Elevation="2">
@{
var gpus = ParseGpuJson(_agent.GpuInventoryJson);
}
@if (gpus.Count > 0)
{
<MudTable Items="@gpus" Dense="true" Hover="true" Elevation="0">
<HeaderContent>
<MudTh>Modèle</MudTh>
<MudTh>Backend</MudTh>
<MudTh>VRAM</MudTh>
<MudTh>Temp</MudTh>
<MudTh>Utilisation</MudTh>
<MudTh>Driver</MudTh>
<MudTh>Encoder</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Modèle">
<MudText Typo="Typo.body2" Class="font-weight-medium">@(context.Model ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="Backend">
<MudChip T="string" Size="Size.Small" Color="Color.Info">@(context.Backend ?? "-")</MudChip>
</MudTd>
<MudTd DataLabel="VRAM">
<MudText Typo="Typo.body2">@(context.VramBytes.HasValue ? FormatBytes(context.VramBytes.Value) : "-")</MudText>
</MudTd>
<MudTd DataLabel="Temp">
<MudText Typo="Typo.body2">@(context.TemperatureCelsius.HasValue ? $"{context.TemperatureCelsius:F0}°C" : "-")</MudText>
</MudTd>
<MudTd DataLabel="Utilisation">
<MudText Typo="Typo.body2">@(context.UtilizationPercent.HasValue ? $"{context.UtilizationPercent:F0}%" : "-")</MudText>
</MudTd>
<MudTd DataLabel="Driver">
<MudText Typo="Typo.body2">@(context.DriverVersion ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="Encoder">
<MudText Typo="Typo.body2">@(context.EncoderSupport ?? "-")</MudText>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">Aucun GPU détecté</MudText>
}
</SectionCard>
</MudItem>
@* ─── Host & Container ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Système & Conteneur" Icon="@Icons.Material.Filled.Computer" Elevation="2">
<MudGrid>
@if (_agent.OsName is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">OS</MudText>
<MudText Typo="Typo.body1">@_agent.OsName</MudText>
</MudItem>
}
@if (_agent.KernelVersion is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">Noyau</MudText>
<MudText Typo="Typo.body1">@_agent.KernelVersion</MudText>
</MudItem>
}
@if (_agent.Arch is not null)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Architecture</MudText>
<MudText Typo="Typo.body1">@_agent.Arch</MudText>
</MudItem>
}
@if (_agent.UptimeMachineSeconds.HasValue)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">Uptime machine</MudText>
<MudText Typo="Typo.body1">@FormatUptime(_agent.UptimeMachineSeconds.Value)</MudText>
</MudItem>
}
@if (_agent.ContainerId is not null)
{
<MudItem xs="12" Class="mt-2">
<MudDivider Class="mb-2" />
<MudText Typo="Typo.body2" Color="Color.Secondary">Conteneur</MudText>
<MudText Typo="Typo.body1">
<MudIcon Icon="@Icons.Material.Filled.CheckCircle" Color="Color.Success" Size="Size.Small" Class="mr-1" />
@(_agent.ContainerImage ?? "Conteneur Docker")
</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary">ID: @_agent.ContainerId</MudText>
</MudItem>
}
@if (_agent.ContainerCpuLimit.HasValue)
{
<MudItem xs="6" Class="mt-2">
<MudChip T="string" Size="Size.Small" Color="Color.Warning">
CPU limite: @($"{_agent.ContainerCpuLimit.Value / 100.0:F1} cores")
</MudChip>
</MudItem>
}
</MudGrid>
</SectionCard>
</MudItem>
</MudGrid>
<MudGrid Class="mt-4">
@* ─── Network Interfaces ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Réseau" Icon="@Icons.Material.Filled.Wifi" Elevation="2">
@{
var interfaces = ParseNetworkJson(_agent.NetworkInterfacesJson);
}
@if (interfaces.Count > 0)
{
<MudTable Items="@interfaces" Dense="true" Hover="true" Elevation="0">
<HeaderContent>
<MudTh>Interface</MudTh>
<MudTh>Adresse IP</MudTh>
<MudTh>MAC</MudTh>
<MudTh>Débit</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Interface">
<MudText Typo="Typo.body2" Class="font-weight-medium">@context.Name</MudText>
</MudTd>
<MudTd DataLabel="Adresse IP">
<MudText Typo="Typo.body2">@(context.IpAddress ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="MAC">
<MudText Typo="Typo.body2">@(context.MacAddress ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="Débit">
<MudText Typo="Typo.body2">@(context.SpeedMbps.HasValue ? $"{context.SpeedMbps} Mbps" : "-")</MudText>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">Aucune interface réseau détectée</MudText>
}
</SectionCard>
</MudItem>
@* ─── Temperature ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="Températures" Icon="@Icons.Material.Filled.Thermostat" Elevation="2">
@{
var temps = ParseTemperatureJson(_agent.TemperatureJson);
}
@if (temps.Count > 0)
{
<MudTable Items="@temps" Dense="true" Hover="true" Elevation="0">
<HeaderContent>
<MudTh>Zone</MudTh>
<MudTh>Température</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Zone">
<MudText Typo="Typo.body2">@context.Zone</MudText>
</MudTd>
<MudTd DataLabel="Température">
@{
Color tempColor;
if (context.TemperatureCelsius > 70)
tempColor = Color.Error;
else if (context.TemperatureCelsius > 50)
tempColor = Color.Warning;
else
tempColor = Color.Default;
}
<MudText Typo="Typo.body2" Color="@tempColor">
@($"{context.TemperatureCelsius:F1}°C")
</MudText>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">Aucune sonde de température détectée</MudText>
}
</SectionCard>
</MudItem>
</MudGrid>
@* ─── Agent Settings (globals hérités + overrides) ─── *@
<SectionCard Title="Configuration"
Icon="@Icons.Material.Filled.Tune"
@@ -648,9 +1005,12 @@ else
private async Task ToggleAutoRefresh(bool enabled)
{
_autoRefresh = enabled;
_refreshCts?.Cancel();
_refreshCts?.Dispose();
_refreshCts = null;
if (_refreshCts is not null)
{
await _refreshCts.CancelAsync();
_refreshCts.Dispose();
_refreshCts = null;
}
if (enabled)
{
@@ -681,12 +1041,15 @@ else
_ => Color.Default
};
public void Dispose()
public async ValueTask DisposeAsync()
{
_disposed = true;
_refreshCts?.Cancel();
_refreshCts?.Dispose();
_refreshCts = null;
if (_refreshCts is not null)
{
await _refreshCts.CancelAsync();
_refreshCts.Dispose();
_refreshCts = null;
}
}
private static Color GetStatusColor(string status) => status switch
@@ -749,4 +1112,111 @@ else
? p.ToUpperInvariant()
: char.ToUpperInvariant(p[0]) + p[1..]));
}
// ─── Inventory helpers ─────────────────────────────────────────
private static string FormatBytes(long bytes) => bytes switch
{
>= 1_073_741_824L => $"{bytes / 1_073_741_824.0:F1} Go",
>= 1_048_576L => $"{bytes / 1_048_576.0:F1} Mo",
>= 1024L => $"{bytes / 1024.0:F1} Ko",
_ => $"{bytes} o"
};
private static string FormatUptime(long seconds) => seconds switch
{
>= 86400 => $"{seconds / 86400}j {seconds % 86400 / 3600}h",
>= 3600 => $"{seconds / 3600}h {seconds % 3600 / 60}m",
>= 60 => $"{seconds / 60}m {seconds % 60}s",
_ => $"{seconds}s"
};
private static List<DiskDto> ParseDiskJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<DiskDto>>(json) ?? [];
}
catch { return []; }
}
private static List<GpuDto> ParseGpuJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<GpuDto>>(json) ?? [];
}
catch { return []; }
}
private static List<NetworkDto> ParseNetworkJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<NetworkDto>>(json) ?? [];
}
catch { return []; }
}
private static List<TempDto> ParseTemperatureJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<TempDto>>(json) ?? [];
}
catch { return []; }
}
// DTOs for JSON deserialization
private sealed class DiskDto
{
public string MountPoint { get; init; } = "";
public string FileSystem { get; init; } = "";
public long? TotalBytes { get; init; } = null;
public long? UsedBytes { get; init; } = null;
public string Type { get; init; } = "Unknown";
}
[Serializable]
private sealed class GpuDto
{
[JsonPropertyName("model")]
public string? Model { get; init; }
[JsonPropertyName("vramBytes")]
public long? VramBytes { get; init; }
[JsonPropertyName("driverVersion")]
public string? DriverVersion { get; init; }
[JsonPropertyName("temperatureCelsius")]
public double? TemperatureCelsius { get; init; }
[JsonPropertyName("utilizationPercent")]
public double? UtilizationPercent { get; init; }
[JsonPropertyName("backend")]
public string? Backend { get; init; }
[JsonPropertyName("encoderSupport")]
public string? EncoderSupport { get; init; }
}
[Serializable]
private sealed class NetworkDto
{
public string Name { get; init; } = "";
[JsonPropertyName("ipAddress")]
public string? IpAddress { get; init; }
[JsonPropertyName("macAddress")]
public string? MacAddress { get; init; }
[JsonPropertyName("speedMbps")]
public long? SpeedMbps { get; init; }
}
[Serializable]
private sealed class TempDto
{
public string Zone { get; init; } = "";
[JsonPropertyName("temperatureCelsius")]
public double TemperatureCelsius { get; init; }
}
}
@@ -71,7 +71,7 @@
{
<MudChip T="string" Size="Size.Small" Class="ml-3"
Color="@(_testResult.Healthy == true ? Color.Success : Color.Error)" Variant="Variant.Outlined">
@(_testResult.Healthy == true ? "Opérationnel" : _testResult.Configured == false ? "Non configuré" : "Injoignable")
@GetStorageTestStatus()
</MudChip>
}
</div>
@@ -83,6 +83,13 @@
private bool _testing;
private StorageTestResult? _testResult;
private string GetStorageTestStatus()
{
if (_testResult?.Healthy is true) return "Opérationnel";
if (_testResult?.Configured is false) return "Non configuré";
return "Injoignable";
}
protected override async Task OnInitializedAsync()
{
try
@@ -7,6 +7,7 @@
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.JSInterop
@using MudBlazor
@using System.Text.Json.Serialization
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Heimdall.Web
@@ -23,6 +23,15 @@ namespace Heimdall.Api.Controllers;
[EnableRateLimiting("Api")]
public class AgentsController : ControllerBase
{
/// <summary>Query parameters for agent log retrieval.</summary>
public record AgentLogsQuery(
[FromQuery] int Page = 1,
[FromQuery] int PageSize = 50,
[FromQuery] string? Level = null,
[FromQuery] DateTime? From = null,
[FromQuery] DateTime? To = null,
[FromQuery] string? Search = null);
private readonly IMediator _mediator;
public AgentsController(IMediator mediator) => _mediator = mediator;
@@ -35,10 +44,6 @@ public class AgentsController : ControllerBase
public async Task<IActionResult> Register(
[FromBody] RegisterAgentRequest request, CancellationToken ct)
{
// Extract API key from header (may be empty for registration)
var apiKey = Request.Headers.Authorization.FirstOrDefault()
?.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase);
var command = new RegisterAgentCommand(request.Token, request.Hostname, request.Version, request.PublicIp);
var result = await _mediator.Send(command, ct);
return result.IsSuccess
@@ -66,7 +71,39 @@ public class AgentsController : ControllerBase
request.CpuUsagePercent,
request.MemoryUsageBytes,
request.DiskUsagePercent,
request.UptimeSeconds);
request.UptimeSeconds,
// CPU inventory
request.CpuVendor,
request.CpuModel,
request.CpuArchitecture,
request.PhysicalCores,
request.LogicalCores,
request.ThreadsPerCore,
request.CpuFrequencyMhz,
request.CpuFlags,
request.CpuCacheBytes,
request.ContainerCpuLimit,
// Memory inventory
request.MemTotalBytes,
request.MemAvailableBytes,
request.SwapTotalBytes,
request.SwapFreeBytes,
request.ContainerMemoryLimitBytes,
// Disk inventory
request.DiskInventoryJson,
// GPU inventory
request.GpuInventoryJson,
// Host info
request.OsName,
request.KernelVersion,
request.Arch,
request.UptimeMachineSeconds,
// Container info
request.ContainerId,
request.ContainerImage,
// Network & Temperature
request.NetworkInterfacesJson,
request.TemperatureJson);
var result = await _mediator.Send(command, ct);
return result.IsSuccess
? Ok()
@@ -167,16 +204,11 @@ public class AgentsController : ControllerBase
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> GetLogs(
Guid id,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 50,
[FromQuery] string? level = null,
[FromQuery] DateTime? from = null,
[FromQuery] DateTime? to = null,
[FromQuery] string? search = null,
CancellationToken ct = default)
AgentLogsQuery query,
CancellationToken ct)
{
var result = await _mediator.Send(
new GetAgentLogsQuery(id, page, pageSize, level, from, to, search), ct);
new GetAgentLogsQuery(id, query.Page, query.PageSize, query.Level, query.From, query.To, query.Search), ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
+261 -248
View File
@@ -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
+43 -20
View File
@@ -82,33 +82,24 @@ public class HeimdallApiClient
if (errors.Value.ValueKind != JsonValueKind.Object)
return Array.Empty<string>();
var messages = new List<string>();
foreach (var field in errors.Value.EnumerateObject())
{
if (field.Value.ValueKind != JsonValueKind.Array) continue;
messages.AddRange(field.Value.EnumerateArray()
return errors.Value.EnumerateObject()
.Where(field => field.Value.ValueKind == JsonValueKind.Array)
.SelectMany(field => field.Value.EnumerateArray()
.Where(item => item.ValueKind == JsonValueKind.String
&& !string.IsNullOrWhiteSpace(item.GetString()))
.Select(item => item.GetString()!));
}
return messages.ToArray();
.Select(item => item.GetString()!))
.ToArray();
}
private static string FallbackErrorMessage(HttpResponseMessage response)
=> $"Erreur du serveur (HTTP {(int)response.StatusCode})";
private static string? FindStringProperty(JsonElement obj, string name)
{
foreach (var prop in obj.EnumerateObject())
{
if (string.Equals(prop.Name, name, StringComparison.OrdinalIgnoreCase)
&& prop.Value.ValueKind == JsonValueKind.String)
return prop.Value.GetString();
}
return null;
}
private static string? FindStringProperty(JsonElement obj, string name) =>
obj.EnumerateObject()
.Where(prop => string.Equals(prop.Name, name, StringComparison.OrdinalIgnoreCase)
&& prop.Value.ValueKind == JsonValueKind.String)
.Select(prop => prop.Value.GetString())
.FirstOrDefault();
// ─── Profile ──────────────────────────────────────────────────
@@ -860,6 +851,38 @@ public class AgentItem
public long? MemoryUsageBytes { get; set; }
public double? DiskUsagePercent { get; set; }
public long? UptimeSeconds { get; set; }
// CPU inventory
public string? CpuVendor { get; set; }
public string? CpuModel { get; set; }
public string? CpuArchitecture { get; set; }
public int? PhysicalCores { get; set; }
public int? LogicalCores { get; set; }
public int? ThreadsPerCore { get; set; }
public double? CpuFrequencyMhz { get; set; }
public string? CpuFlags { get; set; }
public long? CpuCacheBytes { get; set; }
public long? ContainerCpuLimit { get; set; }
// Memory inventory
public long? MemTotalBytes { get; set; }
public long? MemAvailableBytes { get; set; }
public long? SwapTotalBytes { get; set; }
public long? SwapFreeBytes { get; set; }
public long? ContainerMemoryLimitBytes { get; set; }
// Disk inventory
public string? DiskInventoryJson { get; set; }
// GPU inventory
public string? GpuInventoryJson { get; set; }
// Host info
public string? OsName { get; set; }
public string? KernelVersion { get; set; }
public string? Arch { get; set; }
public long? UptimeMachineSeconds { get; set; }
// Container info
public string? ContainerId { get; set; }
public string? ContainerImage { get; set; }
// Network & Temperature
public string? NetworkInterfacesJson { get; set; }
public string? TemperatureJson { get; set; }
}
public class AgentLogItem