feat(settings): boutons Tester email/ntfy/IA + clés techniques masquées (partiel #80)
- Endpoints POST api/settings/{email,ntfy,ai}/test (Admin) :
- email : envoi réel via EmailService vers l'expéditeur configuré
- ntfy : SendTestAsync (nouvelle méthode INtfyService, retour HTTP 2xx)
- ai : ping CodeProject.AI/Ollama via AiHealthCheck
- Client API : TestEmailAsync/TestNtfyAsync/TestAiAsync + record TestActionResult
- UI : boutons Tester dans NotificationSettingsSection (ntfy + email) et
AiSettingsSection (moteurs IA) avec résultat inline
- AgentDetail : la clé brute n'est plus affichée (libellé global/surchargé)
- Tests bUnit : 3 nouveaux (POST par endpoint + affichage résultat) — 224 verts
This commit is contained in:
1 parent
574f242ff0
commit
85bfdac7ee
9 files changed
+304
-20
No files matched your search
@@ -3,4 +3,7 @@ namespace Heimdall.Application.Services;
|
||||
public interface INtfyService
|
||||
{
|
||||
Task SendNotificationAsync(string topic, string title, string message, int priority = 3, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Envoie une notification de test et indique si le serveur a accepté (retour HTTP 2xx).</summary>
|
||||
Task<bool> SendTestAsync(string topic, string title, string message, CancellationToken ct = default);
|
||||
}
|
||||
@@ -30,24 +30,7 @@ public class NtfyService : INtfyService
|
||||
{
|
||||
try
|
||||
{
|
||||
var (baseUrl, authToken) = await ResolveConfigAsync(ct).ConfigureAwait(false);
|
||||
|
||||
var client = _httpClientFactory.CreateClient("Ntfy");
|
||||
var requestUrl = $"{baseUrl.TrimEnd('/')}/{topic}";
|
||||
var payload = new { topic, title, message, priority };
|
||||
var json = JsonSerializer.Serialize(payload);
|
||||
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
|
||||
if (!string.IsNullOrEmpty(authToken))
|
||||
client.DefaultRequestHeaders.Authorization =
|
||||
new AuthenticationHeaderValue("Bearer", authToken);
|
||||
|
||||
var response = await client.PostAsync(requestUrl, content, ct).ConfigureAwait(false);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
var body = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
_logger.LogWarning("ntfy returned {StatusCode} for topic {Topic}: {Body}", response.StatusCode, topic, body);
|
||||
}
|
||||
await SendCoreAsync(topic, title, message, priority, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -55,6 +38,42 @@ public class NtfyService : INtfyService
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> SendTestAsync(string topic, string title, string message, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await SendCoreAsync(topic, title, message, 4, ct).ConfigureAwait(false);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
var body = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
_logger.LogWarning("ntfy test returned {StatusCode} for topic {Topic}: {Body}", response.StatusCode, topic, body);
|
||||
}
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "ntfy test failed for topic {Topic}", topic);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<HttpResponseMessage> SendCoreAsync(string topic, string title, string message, int priority, CancellationToken ct)
|
||||
{
|
||||
var (baseUrl, authToken) = await ResolveConfigAsync(ct).ConfigureAwait(false);
|
||||
|
||||
var client = _httpClientFactory.CreateClient("Ntfy");
|
||||
var requestUrl = $"{baseUrl.TrimEnd('/')}/{topic}";
|
||||
var payload = new { topic, title, message, priority };
|
||||
var json = JsonSerializer.Serialize(payload);
|
||||
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
|
||||
if (!string.IsNullOrEmpty(authToken))
|
||||
client.DefaultRequestHeaders.Authorization =
|
||||
new AuthenticationHeaderValue("Bearer", authToken);
|
||||
|
||||
return await client.PostAsync(requestUrl, content, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Source de vérité : AppSettings en base (ntfy.*), avec fallback
|
||||
/// config/appsettings puis env (migration douce, ticket #80). Relu à
|
||||
|
||||
@@ -149,8 +149,8 @@ else
|
||||
<MudText Typo="Typo.body1" Class="font-weight-medium settings-label">
|
||||
@(setting.Description ?? HumanizeAgentKey(setting.Key))
|
||||
</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="settings-key">
|
||||
@setting.Key
|
||||
<MudText Typo="Typo.caption" Color="Color.Secondary">
|
||||
@(overridden ? "Valeur surchargée pour cet agent" : "Valeur globale appliquée")
|
||||
</MudText>
|
||||
</div>
|
||||
@if (overridden)
|
||||
|
||||
@@ -36,10 +36,25 @@
|
||||
HelperText="Défaut global appliqué aux agents. Une modification nécessite le rechargement de la configuration des agents." />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex align-center mt-3">
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Info" StartIcon="@Icons.Material.Filled.Radar"
|
||||
OnClick="TestAiAsync" Disabled="@_testing">
|
||||
@(_testing ? "Test en cours…" : "Tester les moteurs IA")
|
||||
</MudButton>
|
||||
</div>
|
||||
@if (_testResult is not null)
|
||||
{
|
||||
<MudAlert Severity="@(_testResult.Success ? Severity.Success : Severity.Warning)" Class="mt-3" Variant="Variant.Outlined">
|
||||
<strong>@_testResult.Status</strong> — @_testResult.Message
|
||||
</MudAlert>
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
private List<AppSettingItem> _settings = [];
|
||||
private bool _testing;
|
||||
private TestActionResult? _testResult;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
@@ -60,6 +75,24 @@
|
||||
private Task OnOllamaUrlChanged(string v) => SaveValueAsync("ai.ollamaurl", v);
|
||||
private Task OnDetectionEnabledChanged(bool v) => SaveValueAsync("ai.detection.enabled", v ? "true" : "false");
|
||||
|
||||
private async Task TestAiAsync()
|
||||
{
|
||||
_testing = true;
|
||||
_testResult = null;
|
||||
try
|
||||
{
|
||||
_testResult = await Api.TestAiAsync() ?? new TestActionResult(false, "Test impossible (API indisponible).");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_testResult = new TestActionResult(false, $"Test impossible : {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
_testing = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveValueAsync(string key, string? value)
|
||||
{
|
||||
value ??= string.Empty;
|
||||
|
||||
@@ -82,10 +82,29 @@
|
||||
HelperText="Active le chiffrement TLS lors de la connexion SMTP." />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex align-center mt-3">
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Info" StartIcon="@Icons.Material.Filled.Send"
|
||||
OnClick="TestNtfyAsync" Disabled="@_testing">
|
||||
@(_testing ? "Test en cours…" : "Tester ntfy")
|
||||
</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Info" Class="ml-2" StartIcon="@Icons.Material.Filled.Email"
|
||||
OnClick="TestEmailAsync" Disabled="@_testing">
|
||||
@(_testing ? "Test en cours…" : "Tester l'envoi email")
|
||||
</MudButton>
|
||||
</div>
|
||||
@if (_testResult is not null)
|
||||
{
|
||||
<MudAlert Severity="@(_testResult.Success ? Severity.Success : Severity.Error)" Class="mt-3" Variant="Variant.Outlined">
|
||||
@_testResult.Message
|
||||
</MudAlert>
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
private List<AppSettingItem> _settings = [];
|
||||
private bool _testing;
|
||||
private TestActionResult? _testResult;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
@@ -121,6 +140,42 @@
|
||||
private Task OnPasswordChanged(string v) => SaveValueAsync("email.password", v);
|
||||
private Task OnUseSslChanged(bool v) => SaveValueAsync("email.usessl", v ? "true" : "false");
|
||||
|
||||
private async Task TestNtfyAsync()
|
||||
{
|
||||
_testing = true;
|
||||
_testResult = null;
|
||||
try
|
||||
{
|
||||
_testResult = await Api.TestNtfyAsync() ?? new TestActionResult(false, "Test impossible (API indisponible).");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_testResult = new TestActionResult(false, $"Test impossible : {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
_testing = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task TestEmailAsync()
|
||||
{
|
||||
_testing = true;
|
||||
_testResult = null;
|
||||
try
|
||||
{
|
||||
_testResult = await Api.TestEmailAsync() ?? new TestActionResult(false, "Test impossible (API indisponible).");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_testResult = new TestActionResult(false, $"Test impossible : {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
_testing = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveValueAsync(string key, string? value)
|
||||
{
|
||||
value ??= string.Empty;
|
||||
|
||||
@@ -249,6 +249,77 @@ public class SettingsController : ControllerBase
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Send a test email through the configured SMTP server (Admin only).
|
||||
/// </summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
||||
[HttpPost("email/test")]
|
||||
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(typeof(object), StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> TestEmail(
|
||||
[FromServices] IEmailService emailService,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var settings = await _mediator.Send(new GetSettingsQuery(), ct);
|
||||
if (!settings.IsSuccess)
|
||||
return StatusCode(settings.StatusCode ?? 400, new { error = settings.Error });
|
||||
|
||||
var fromAddress = settings.Data!.FirstOrDefault(s => s.Key == "email.fromaddress")?.Value;
|
||||
if (string.IsNullOrWhiteSpace(fromAddress))
|
||||
return BadRequest(new { error = "Adresse expéditrice non configurée (email.fromaddress)." });
|
||||
|
||||
try
|
||||
{
|
||||
await emailService.SendEmailAsync(fromAddress, "Heimdall — test de configuration",
|
||||
"<h2>✅ Configuration email OK</h2><p>Ce message confirme que le serveur SMTP est joignable et que l'authentification fonctionne.</p>", ct);
|
||||
return Ok(new { success = true, message = $"Email de test envoyé à {fromAddress}" });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Ok(new { success = false, message = $"Échec de l'envoi : {ex.Message}" });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Send a test notification through the configured ntfy server (Admin only).
|
||||
/// </summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
||||
[HttpPost("ntfy/test")]
|
||||
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> TestNtfy(
|
||||
[FromServices] INtfyService ntfyService,
|
||||
[FromBody] TestNtfyRequest? request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var topic = string.IsNullOrWhiteSpace(request?.Topic) ? "heimdall-test" : request.Topic;
|
||||
var ok = await ntfyService.SendTestAsync(topic, "Heimdall — test de configuration",
|
||||
"✅ Notification ntfy reçue : le serveur est joignable et le token est accepté.", ct);
|
||||
return Ok(new { success = ok, message = ok
|
||||
? $"Notification test envoyée sur le topic « {topic} »"
|
||||
: "Échec de l'envoi ntfy (serveur injoignable ou rejet — voir les logs)." });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ping the configured AI backends (CodeProject.AI / Ollama) (Admin only).
|
||||
/// </summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
|
||||
[HttpPost("ai/test")]
|
||||
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> TestAi(
|
||||
[FromServices] Heimdall.Infrastructure.HealthChecks.AiHealthCheck aiHealthCheck,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var result = await aiHealthCheck.CheckHealthAsync(null!, ct);
|
||||
return Ok(new
|
||||
{
|
||||
success = result.Status == Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Healthy,
|
||||
status = result.Status.ToString(),
|
||||
message = result.Description,
|
||||
});
|
||||
}
|
||||
|
||||
public sealed record TestNtfyRequest(string? Topic);
|
||||
|
||||
/// <summary>
|
||||
/// Broadcast a "ConfigReload" signal to all connected agents so they
|
||||
/// re-fetch their full configuration (Admin only).
|
||||
|
||||
@@ -504,6 +504,36 @@ public class HeimdallApiClient
|
||||
return await response.Content.ReadFromJsonAsync<StorageTestResult>();
|
||||
}
|
||||
|
||||
/// <summary>Send a test email (POST /api/settings/email/test).</summary>
|
||||
public async Task<TestActionResult?> TestEmailAsync()
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsync("api/settings/email/test", null);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
return null;
|
||||
return await response.Content.ReadFromJsonAsync<TestActionResult>();
|
||||
}
|
||||
|
||||
/// <summary>Send a test ntfy notification (POST /api/settings/ntfy/test).</summary>
|
||||
public async Task<TestActionResult?> TestNtfyAsync()
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsync("api/settings/ntfy/test", null);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
return null;
|
||||
return await response.Content.ReadFromJsonAsync<TestActionResult>();
|
||||
}
|
||||
|
||||
/// <summary>Ping the AI backends (POST /api/settings/ai/test).</summary>
|
||||
public async Task<TestActionResult?> TestAiAsync()
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsync("api/settings/ai/test", null);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
return null;
|
||||
return await response.Content.ReadFromJsonAsync<TestActionResult>();
|
||||
}
|
||||
|
||||
public async Task<HttpResponseMessage> ReloadAllConfigAsync()
|
||||
{
|
||||
var client = CreateClient();
|
||||
@@ -706,6 +736,13 @@ public record StorageTestResult(
|
||||
[property: JsonPropertyName("healthy")] bool? Healthy
|
||||
);
|
||||
|
||||
/// <summary>Résultat d'un test d'intégration (email / ntfy / IA).</summary>
|
||||
public record TestActionResult(
|
||||
[property: JsonPropertyName("success")] bool Success,
|
||||
[property: JsonPropertyName("message")] string? Message,
|
||||
[property: JsonPropertyName("status")] string? Status = null
|
||||
);
|
||||
|
||||
// ─── Settings DTOs ─────────────────────────────────────────────────
|
||||
|
||||
public record AppSettingItem(
|
||||
|
||||
Reference in new issue
Block a user