using Heimdall.Application.Agents.Queries.GetAgent; using Heimdall.Application.Agents.Commands.AcknowledgeCameraConfig; using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Application.Services; using Heimdall.Application.Settings.Commands.CreateAppSetting; using Heimdall.Application.Settings.Commands.UpdateAppSetting; using Heimdall.Application.Settings.Commands.DeleteAppSetting; using Heimdall.Application.Settings.Commands.SetAgentSetting; using Heimdall.Application.Settings.Commands.RemoveAgentSetting; using Heimdall.Application.Settings.Queries.GetSettings; using Heimdall.Application.Settings.Queries.GetSettingByKey; using Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig; using Heimdall.Application.Settings.Queries.GetAgentSettings; using Heimdall.Api.Hubs; using Heimdall.Infrastructure.Security; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; namespace Heimdall.Api.Controllers; [ApiController] [Route("api/settings")] [Authorize(AuthenticationSchemes = "JwtBearer,Cookies")] [EnableRateLimiting("Api")] public class SettingsController : ControllerBase { private readonly IMediator _mediator; private readonly IConfigBroadcastService _broadcast; private readonly ILogger _logger; public SettingsController( IMediator mediator, IConfigBroadcastService broadcast, ILogger logger) { _mediator = mediator; _broadcast = broadcast; _logger = logger; } /// List all global settings (Admin only). [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] [HttpGet] [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task ListAll(CancellationToken ct) { var result = await _mediator.Send(new GetSettingsQuery(), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); // Redact sensitive values before returning to client var redacted = result.Data!.Select(s => s with { Value = RedactValue(s.ValueType, s.Value, s.Key) }).ToList(); return Ok(redacted); } /// Get a global setting by key (Admin only). [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] [HttpGet("{key}")] [ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetByKey(string key, CancellationToken ct) { var result = await _mediator.Send(new GetSettingByKeyQuery(key), ct); if (!result.IsSuccess) return NotFound(new { error = result.Error }); // Redact sensitive values before returning to client var redacted = result.Data! with { Value = RedactValue(result.Data.ValueType, result.Data.Value, result.Data.Key) }; return Ok(redacted); } /// Create a new global setting (Admin only). [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] [HttpPost] [ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task Create( [FromBody] CreateAppSettingRequest request, CancellationToken ct) { var command = new CreateAppSettingCommand(request.Key, request.Value, request.Category, request.Description, request.ValueType, request.AllowedValues, request.AgentScoped); var result = await _mediator.Send(command, ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct); _logger.LogInformation("Created global setting {Key}", result.Data!.Key); return Ok(result.Data); } /// Update a global setting (Admin only). Broadcasts the change to all agents. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] [HttpPut("{key}")] [ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task Update( string key, [FromBody] UpdateAppSettingRequest request, CancellationToken ct) { var command = new UpdateAppSettingCommand(key, request.Value, request.Description, request.Category, request.ValueType, request.AllowedValues, request.AgentScoped); var result = await _mediator.Send(command, ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct); _logger.LogInformation("Updated global setting {Key}", result.Data!.Key); return Ok(result.Data); } /// Delete a global setting (Admin only). Broadcasts the change to all agents. [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] [HttpDelete("{key}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task Delete(string key, CancellationToken ct) { var result = await _mediator.Send(new DeleteAppSettingCommand(key), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); await _broadcast.NotifyAllAgentsReload(ct); _logger.LogInformation("Deleted global setting {Key}", key); return NoContent(); } /// /// Get the effective configuration for an agent: global defaults merged with /// per-agent overrides, plus the site's camera credential pool inside an /// encrypted envelope. Accessible by the agent itself (API key) /// or by an admin (JWT/Cookie). /// [Authorize(AuthenticationSchemes = "ApiKey,JwtBearer,Cookies")] [HttpGet("agent/{agentId:guid}")] [ProducesResponseType(typeof(Dictionary), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task GetEffectiveConfig(Guid agentId, CancellationToken ct) { // The API key is bound to exactly one agent. Same-site agents must not // be able to read each other's RTSP URLs or credential envelopes. var isApiKey = User.HasClaim(c => c.Type == "auth_method" && c.Value == "api_key"); if (isApiKey) { if (User.FindFirst("agent_id")?.Value != agentId.ToString()) return Forbid(); var siteClaim = User.FindFirst("site_id")?.Value; if (!Guid.TryParse(siteClaim, out var apiKeySiteId)) return Forbid(); var agentResult = await _mediator.Send(new GetAgentQuery(agentId), ct); if (!agentResult.IsSuccess || agentResult.Data is null) return Forbid(); if (agentResult.Data.SiteId != apiKeySiteId) return Forbid(); } else if (!User.HasClaim("permission", AppPermissions.AdminManage)) { return Forbid(); } var result = await _mediator.Send(new GetEffectiveAgentConfigQuery(agentId), ct); if (!result.IsSuccess || result.Data is null) return NotFound(new { error = result.Error }); Response.Headers["X-Camera-Config-Version"] = CameraConfigVersion.Compute(result.Data); return Ok(result.Data); } public sealed record CameraConfigAckRequest(string Version); /// Acknowledge the exact camera snapshot applied by this agent. [Authorize(AuthenticationSchemes = "ApiKey")] [HttpPost("agent/{agentId:guid}/camera-config-ack")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status409Conflict)] public async Task AcknowledgeCameraConfig(Guid agentId, [FromBody] CameraConfigAckRequest request, CancellationToken ct) { if (User.FindFirst("agent_id")?.Value != agentId.ToString()) return Forbid(); if (request.Version?.Length != 64 || !request.Version.All(Uri.IsHexDigit)) return BadRequest(new { error = "Invalid camera configuration version" }); var result = await _mediator.Send(new GetEffectiveAgentConfigQuery(agentId), ct); if (!result.IsSuccess || result.Data is null) return NotFound(new { error = result.Error }); if (!string.Equals(CameraConfigVersion.Compute(result.Data), request.Version, StringComparison.OrdinalIgnoreCase)) return Conflict(new { error = "Camera configuration changed before acknowledgement" }); if (!await _mediator.Send(new AcknowledgeCameraConfigCommand(agentId, request.Version), ct)) return NotFound(); _logger.LogInformation("Agent {AgentId} applied camera configuration {Version}", agentId, request.Version); return NoContent(); } /// List all setting overrides for a specific agent (Admin only). [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] [HttpGet("agent/{agentId:guid}/overrides")] [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task ListAgentOverrides(Guid agentId, CancellationToken ct) { var result = await _mediator.Send(new GetAgentSettingsQuery(agentId), ct); return result.IsSuccess ? Ok(result.Data) : NotFound(new { error = result.Error }); } /// /// Set (create or update) a per-agent setting override (Admin only). /// Broadcasts the change to the affected agent in real-time. /// [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] [HttpPut("agent/{agentId:guid}/overrides")] [ProducesResponseType(typeof(AgentSettingDto), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task SetAgentOverride( Guid agentId, [FromBody] SetAgentSettingRequest request, CancellationToken ct) { var command = new SetAgentSettingCommand(agentId, request.Key, request.Value); var result = await _mediator.Send(command, ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); await _broadcast.NotifyAgentSettingChanged(agentId, result.Data!.Key, result.Data.Value, ct); _logger.LogInformation("Set agent override Agent={AgentId}, {Key}", agentId, result.Data!.Key); return Ok(result.Data); } /// /// Remove a per-agent setting override (Admin only). /// Broadcasts a reload notification to the affected agent. /// [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] [HttpDelete("agent/{agentId:guid}/overrides/{key}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task RemoveAgentOverride(Guid agentId, string key, CancellationToken ct) { var result = await _mediator.Send(new RemoveAgentSettingCommand(agentId, key), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); await _broadcast.NotifyAgentSettingChanged(agentId, key, string.Empty, ct); _logger.LogInformation("Removed agent override Agent={AgentId}, {Key}", agentId, key); return NoContent(); } /// /// Test the active storage provider reachability (Admin only). /// Returns the resolved provider name and health status. /// [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] [HttpPost("storage/test")] [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task TestStorage( [FromServices] IStorageProvider storageProvider, CancellationToken ct) { var ok = await storageProvider.HealthCheckAsync(ct); return Ok(new { provider = storageProvider.Provider, configured = storageProvider.IsConfigured, healthy = ok, }); } /// /// Send a test email through the configured SMTP server (Admin only). /// [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] [HttpPost("email/test")] [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] [ProducesResponseType(typeof(object), StatusCodes.Status400BadRequest)] public async Task 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", "

✅ Configuration email OK

Ce message confirme que le serveur SMTP est joignable et que l'authentification fonctionne.

", 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}" }); } } /// /// Send a test notification through the configured ntfy server (Admin only). /// [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] [HttpPost("ntfy/test")] [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] public async Task 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é.", baseUrl: request?.BaseUrl, ct: ct); return Ok(new { success = ok, message = ok ? $"Notification test envoyée sur « {topic} » ({request?.BaseUrl ?? "serveur global"})" : "Échec de l'envoi ntfy (serveur injoignable ou rejet — voir les logs)." }); } /// /// Ping the configured AI backends (CodeProject.AI / Ollama) (Admin only). /// [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] [HttpPost("ai/test")] [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] public async Task 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, string? BaseUrl); /// /// Broadcast a "ConfigReload" signal to all connected agents so they /// re-fetch their full configuration (Admin only). /// [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] [HttpPost("reload")] [ProducesResponseType(StatusCodes.Status202Accepted)] [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task ReloadAllAgents(CancellationToken ct) { await _broadcast.NotifyAllAgentsReload(ct); _logger.LogInformation("Broadcast ConfigReload to all agents"); return Accepted(new { message = "Config reload broadcast to all connected agents" }); } /// /// Sensitive key patterns whose values must never be returned to the client. /// Centralized list — add new patterns here as needed. /// private static readonly string[] SensitiveKeyPatterns = ["password", "token", "secret", "apikey", "api_key", "credential", "jwt", "privatekey", "connectionstring"]; /// /// Sensitive value type patterns whose values must never be returned to the client. /// private static readonly string[] SensitiveValueTypePatterns = ["password", "token", "secret", "key", "credential"]; private static string RedactValue(string? valueType, string value, string? key = null) { if (key is not null && SensitiveKeyPatterns.Any(p => key.Contains(p, StringComparison.OrdinalIgnoreCase))) return "***REDACTED***"; if (valueType is not null && SensitiveValueTypePatterns.Any(p => valueType.Contains(p, StringComparison.OrdinalIgnoreCase))) return "***REDACTED***"; return value; } }