refactor: remove Heimdall.Api, move all routes into Heimdall.Web

Heimdall.Api controllers/hubs/filters were exact duplicates of
files already in Heimdall.Web (same namespace, same content).
The Api project was a leftover from before the single-image merge.

Changes:
- Add missing registrations to Web/Program.cs (JWT Bearer auth,
  rate limiting, controllers with ExceptionFilter, FluentValidation,
  SignalR + broadcast services, OpenAPI/Scalar, CORS, hub mappings)
- Add FluentValidation.AspNetCore, Scalar.AspNetCore,
  Microsoft.AspNetCore.OpenApi NuGet packages to Web.csproj
- Remove Heimdall.Api from solution and delete the project
- All routes continue working at their existing paths
This commit is contained in:
Arnaud Dartois committed 2026-07-20 20:22:30 +00:00
1 parent 81da09c110
commit d9a3ea52ba
28 files changed
+126 -2272

No files matched your search

@@ -1,91 +0,0 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/agents")]
[EnableRateLimiting("Api")]
public class AgentsController : ControllerBase
{
private readonly IAgentService _agentService;
public AgentsController(IAgentService agentService) => _agentService = agentService;
/// <summary>Register an agent using a site registration token.</summary>
[AllowAnonymous]
[HttpPost("register")]
[ProducesResponseType(typeof(RegisterAgentResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
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 result = await _agentService.RegisterAsync(request, apiKey, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
}
/// <summary>Send heartbeat from agent (API Key auth).</summary>
[Authorize(AuthenticationSchemes = "ApiKey")]
[HttpPost("{id:guid}/heartbeat")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Heartbeat(
Guid id, [FromBody] AgentHeartbeatRequest request, CancellationToken ct)
{
var result = await _agentService.HeartbeatAsync(id, request, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Get agent details (JWT auth).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(AgentResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _agentService.GetByIdAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>List agents for a site.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet("by-site/{siteId:guid}")]
[ProducesResponseType(typeof(PagedResult<AgentResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ListBySite(
Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _agentService.ListBySiteAsync(siteId, page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
/// <summary>List all agents across all sites.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet]
[ProducesResponseType(typeof(PagedResult<AgentResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ListAll(
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _agentService.ListAllAsync(page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
}
@@ -1,127 +0,0 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
/// <summary>
/// Camera-to-agent assignment management.
/// Controls how cameras are distributed across agents in a site,
/// with support for manual assignment, strategy-based balancing,
/// and failover.
/// </summary>
[ApiController]
[Route("api/assignments")]
[EnableRateLimiting("Api")]
[Authorize(AuthenticationSchemes = "JwtBearer")]
public class AssignmentsController : ControllerBase
{
private readonly ICameraAssignmentService _assignmentService;
public AssignmentsController(ICameraAssignmentService assignmentService)
{
_assignmentService = assignmentService;
}
/// <summary>Assign a single camera to a specific agent.</summary>
[HttpPost]
[Authorize(Policy = AppPermissions.CameraWrite)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> AssignCamera([FromBody] AssignRequest request, CancellationToken ct)
{
var result = await _assignmentService.AssignCameraAsync(
request.CameraId, request.AgentId, request.Reason ?? "manual", ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Assign all cameras in a site using a strategy.</summary>
[HttpPost("site/{siteId:guid}")]
[Authorize(Policy = AppPermissions.CameraWrite)]
[ProducesResponseType(typeof(AssignmentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> AssignSiteCameras(Guid siteId, [FromQuery] string strategy = "RoundRobin", CancellationToken ct = default)
{
if (!Enum.TryParse<AssignmentStrategy>(strategy, true, out var parsed))
return BadRequest(new { error = $"Invalid strategy: {strategy}. Valid: RoundRobin, GpuPriority, LeastCameras" });
var result = await _assignmentService.AssignSiteCamerasAsync(siteId, parsed, ct);
var assignedCount = result.Data;
return result.IsSuccess
? Ok(new AssignmentResult(assignedCount))
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Trigger failover for an offline agent — reassign its cameras.</summary>
[HttpPost("failover/{agentId:guid}")]
[Authorize(Policy = AppPermissions.CameraWrite)]
[ProducesResponseType(typeof(FailoverResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> FailoverAgent(Guid agentId, CancellationToken ct)
{
var result = await _assignmentService.FailoverAgentAsync(agentId, ct);
return result.IsSuccess
? Ok(new FailoverResult(result.Data?.Count ?? 0))
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Get the active assignment for a camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("camera/{cameraId:guid}")]
[ProducesResponseType(typeof(AssignmentResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetCameraAssignment(Guid cameraId, CancellationToken ct)
{
var assignment = await _assignmentService.GetActiveAssignmentAsync(cameraId, ct);
if (assignment is null)
return NotFound(new { error = "Camera not assigned" });
return Ok(new AssignmentResponse(
assignment.CameraId,
assignment.AgentId,
assignment.Agent.Name,
assignment.Reason,
assignment.AssignedAt));
}
/// <summary>Get all active assignments (workload) for an agent.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("agent/{agentId:guid}")]
[ProducesResponseType(typeof(List<AssignmentResponse>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetAgentAssignments(Guid agentId, CancellationToken ct)
{
var assignments = await _assignmentService.GetAgentAssignmentsAsync(agentId, ct);
return Ok(assignments.Select(a => new AssignmentResponse(
a.CameraId, a.AgentId, a.Agent?.Name ?? "", a.Reason, a.AssignedAt)).ToList());
}
/// <summary>Get assignment history for a camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("camera/{cameraId:guid}/history")]
[ProducesResponseType(typeof(List<AssignmentResponse>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetCameraHistory(Guid cameraId, CancellationToken ct)
{
var history = await _assignmentService.GetCameraHistoryAsync(cameraId, ct);
return Ok(history.Select(a => new AssignmentResponse(
a.CameraId, a.AgentId, a.Agent?.Name ?? "", a.Reason, a.AssignedAt)).ToList());
}
/// <summary>Release a camera from its current agent.</summary>
[HttpDelete("camera/{cameraId:guid}")]
[Authorize(Policy = AppPermissions.CameraWrite)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> ReleaseCamera(Guid cameraId, CancellationToken ct)
{
var result = await _assignmentService.ReleaseCameraAsync(cameraId, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
}
@@ -1,36 +0,0 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/audit-logs")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[EnableRateLimiting("Api")]
public class AuditLogsController : ControllerBase
{
private readonly IAuditLogService _auditLogService;
public AuditLogsController(IAuditLogService auditLogService) => _auditLogService = auditLogService;
/// <summary>List audit log entries with optional filtering.</summary>
[HttpGet]
[ProducesResponseType(typeof(PagedResult<AuditLogResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> List(
[FromQuery] string? resourceType,
[FromQuery] string? action,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20,
CancellationToken ct = default)
{
var result = await _auditLogService.ListAsync(resourceType, action, page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
}
@@ -1,128 +0,0 @@
using System.Security.Claims;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/auth")]
[EnableRateLimiting("Auth")]
public class AuthController : ControllerBase
{
private readonly IAuthService _authService;
private readonly IWebHostEnvironment _env;
public AuthController(IAuthService authService, IWebHostEnvironment env)
{
_authService = authService;
_env = env;
}
/// <summary>Register a new user.</summary>
[AllowAnonymous]
[HttpPost("register")]
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Register([FromBody] RegisterRequest request, CancellationToken ct)
{
var result = await _authService.RegisterAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Authenticate a user.</summary>
[AllowAnonymous]
[HttpPost("login")]
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Login([FromBody] LoginRequest request, CancellationToken ct)
{
var result = await _authService.LoginAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
}
/// <summary>Verify a 2FA code.</summary>
[AllowAnonymous]
[HttpPost("2fa/verify")]
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Verify2fa([FromBody] Verify2faRequest request, CancellationToken ct)
{
var result = await _authService.Verify2faAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
}
/// <summary>Refresh an authentication token.</summary>
[AllowAnonymous]
[HttpPost("refresh")]
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Refresh([FromBody] RefreshTokenRequest request, CancellationToken ct)
{
var result = await _authService.RefreshTokenAsync(request.RefreshToken, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
}
/// <summary>Change the current user's password.</summary>
[Authorize]
[HttpPost("change-password")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> ChangePassword(
[FromBody] ChangePasswordRequest request, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
return Unauthorized();
var result = await _authService.ChangePasswordAsync(
userId, request.CurrentPassword, request.NewPassword, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Test/Dev-only: register a user with Admin role (bypasses chicken-and-egg).</summary>
[AllowAnonymous]
[HttpPost("register-admin")]
[ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> RegisterAdmin([FromBody] RegisterRequest request, CancellationToken ct)
{
if (!_env.IsEnvironment("Testing") && !_env.IsDevelopment())
return NotFound();
var result = await _authService.RegisterAdminAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Logout — revoke the current refresh token.</summary>
[Authorize]
[HttpPost("logout")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> Logout([FromBody] LogoutRequest request, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
return Unauthorized();
await _authService.LogoutAsync(userId, request.RefreshToken, ct);
return Ok();
}
}
@@ -1,86 +0,0 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/cameras")]
[EnableRateLimiting("Api")]
public class CamerasController : ControllerBase
{
private readonly ICameraService _cameraService;
public CamerasController(ICameraService cameraService) => _cameraService = cameraService;
/// <summary>Create a new camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPost]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create([FromBody] CreateCameraRequest request, CancellationToken ct)
{
var result = await _cameraService.CreateAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Get a camera by ID.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _cameraService.GetByIdAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>List cameras by site.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("by-site/{siteId:guid}")]
[ProducesResponseType(typeof(PagedResult<CameraResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ListBySite(
Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _cameraService.ListBySiteAsync(siteId, page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
/// <summary>Update a camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPut("{id:guid}")]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update(Guid id, [FromBody] UpdateCameraRequest request, CancellationToken ct)
{
var result = await _cameraService.UpdateAsync(id, request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Delete a camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var result = await _cameraService.DeleteAsync(id, ct);
return result.IsSuccess
? NoContent()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
}
@@ -1,152 +0,0 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
/// <summary>
/// Camera discovery endpoints.
/// Provides network probing, camera database search, stream URL building,
/// stream testing, and discovery confirmation.
/// </summary>
[ApiController]
[Route("api/discovery")]
[EnableRateLimiting("Api")]
public class DiscoveryController : ControllerBase
{
private readonly ICameraDiscoveryService _discoveryService;
public DiscoveryController(ICameraDiscoveryService discoveryService)
{
_discoveryService = discoveryService;
}
/// <summary>Probe a single IP address for camera services.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPost("probe")]
[ProducesResponseType(typeof(ProbeResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ProbeIp([FromBody] ProbeRequest request, CancellationToken ct)
{
var result = await _discoveryService.ProbeIpAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Scan a subnet for camera devices.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPost("scan")]
[ProducesResponseType(typeof(IReadOnlyList<ProbeResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ScanSubnet([FromBody] ScanRequest request, CancellationToken ct)
{
var result = await _discoveryService.ScanSubnetAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Search the built-in camera database by brand, model, or preset.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("search")]
[ProducesResponseType(typeof(SearchResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> SearchDatabase([FromQuery] string? q, CancellationToken ct)
{
var result = await _discoveryService.SearchDatabaseAsync(q ?? "", ct);
return Ok(result.Data);
}
/// <summary>Build stream URLs from camera database entries.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpPost("build-urls")]
[ProducesResponseType(typeof(StreamBuildResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> BuildStreamUrls([FromBody] StreamBuildRequest request, CancellationToken ct)
{
var result = await _discoveryService.BuildStreamUrlsAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Test stream URLs. Returns a session ID for polling.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPost("test-streams")]
[ProducesResponseType(typeof(StreamTestSession), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> TestStreams([FromBody] StreamTestRequest request, CancellationToken ct)
{
var result = await _discoveryService.TestStreamsAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Poll a stream test session for updated results.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("test/{sessionId:guid}")]
[ProducesResponseType(typeof(StreamTestSession), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetTestSession(Guid sessionId, CancellationToken ct)
{
var result = await _discoveryService.GetTestSessionAsync(sessionId, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Get a screenshot from a stream test session.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("test/{sessionId:guid}/screenshot/{index}")]
[ProducesResponseType(typeof(byte[]), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetScreenshot(Guid sessionId, int index, CancellationToken ct)
{
var screenshot = await _discoveryService.GetScreenshotAsync(sessionId, index, ct);
if (screenshot is null)
return NotFound(new { error = "Screenshot not available" });
return File(screenshot, "image/jpeg");
}
/// <summary>Cancel a running stream test session.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPost("test/{sessionId:guid}/cancel")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> CancelTestSession(Guid sessionId, CancellationToken ct)
{
var result = await _discoveryService.CancelTestSessionAsync(sessionId, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Check if a camera already exists for this IP/MAC (anti-duplication).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpPost("check")]
[ProducesResponseType(typeof(CameraCheckResponse), StatusCodes.Status200OK)]
public async Task<IActionResult> CheckDuplicate([FromBody] CheckDuplicateRequest request, CancellationToken ct)
{
var result = await _discoveryService.CheckDuplicateAsync(request, ct);
return Ok(result.Data);
}
/// <summary>Confirm a discovery result and create a Camera entity.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPost("confirm")]
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(CameraCheckResponse), StatusCodes.Status409Conflict)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ConfirmDiscovery([FromBody] ConfirmDiscoveryRequest request, CancellationToken ct)
{
var result = await _discoveryService.ConfirmDiscoveryAsync(request, ct);
if (result.IsSuccess)
return Ok(result.Data);
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
}
@@ -1,111 +0,0 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
/// <summary>
/// Camera detection events — motion, person, vehicle, face recognition, etc.
/// Agents POST events as they detect them; users GET filtered views.
/// </summary>
[ApiController]
[Route("api/events")]
[EnableRateLimiting("Api")]
public class EventsController : ControllerBase
{
private readonly ICameraEventService _eventService;
public EventsController(ICameraEventService eventService) => _eventService = eventService;
/// <summary>Record a new detection event (called by agents).</summary>
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
[HttpPost]
[ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create([FromBody] CreateCameraEventRequest request, CancellationToken ct)
{
var result = await _eventService.CreateAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Get a single event by ID.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _eventService.GetByIdAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Query events with filters. Supports pagination.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet]
[ProducesResponseType(typeof(PagedResult<CameraEventResponse>), StatusCodes.Status200OK)]
public async Task<IActionResult> Query(
[FromQuery] Guid? cameraId,
[FromQuery] Guid? siteId,
[FromQuery] string? type,
[FromQuery] DateTime? from,
[FromQuery] DateTime? to,
[FromQuery] double? minConfidence,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 50,
CancellationToken ct = default)
{
EventType? parsedType = null;
if (type is not null && Enum.TryParse<EventType>(type, true, out var t))
parsedType = t;
var filter = new CameraEventFilterRequest(cameraId, siteId, parsedType, from, to, minConfidence, page, pageSize);
var result = await _eventService.QueryAsync(filter, ct);
return Ok(result.Data);
}
/// <summary>Get recent events for a camera.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("camera/{cameraId:guid}")]
[ProducesResponseType(typeof(List<CameraEventResponse>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetRecentByCamera(Guid cameraId, [FromQuery] int count = 20, CancellationToken ct = default)
{
var result = await _eventService.GetRecentByCameraAsync(cameraId, count, ct);
return Ok(result.Data);
}
/// <summary>Attach a snapshot URL to an event (called by agents after upload).</summary>
[Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)]
[HttpPost("{id:guid}/snapshot")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> AttachSnapshot(Guid id, [FromBody] AttachSnapshotRequest request, CancellationToken ct)
{
var result = await _eventService.AttachSnapshotAsync(id, request.SnapshotUrl, request.ThumbUrl, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
/// <summary>Delete an event.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var result = await _eventService.DeleteAsync(id, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
}
@@ -1,123 +0,0 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
/// <summary>
/// CRUD management for user groups and their members (Admin only).
/// </summary>
[ApiController]
[Route("api/groups")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[EnableRateLimiting("Api")]
public class GroupsController : ControllerBase
{
private readonly IGroupService _groupService;
public GroupsController(IGroupService groupService) => _groupService = groupService;
/// <summary>List all groups (Admin only).</summary>
[HttpGet]
[ProducesResponseType(typeof(PagedResult<GroupResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> List(
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _groupService.ListAsync(page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
/// <summary>Get a group by ID.</summary>
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _groupService.GetByIdAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>Create a new group (Admin only).</summary>
[HttpPost]
[ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create([FromBody] CreateGroupRequest request, CancellationToken ct)
{
var result = await _groupService.CreateAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Update a group (Admin only).</summary>
[HttpPut("{id:guid}")]
[ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update(
Guid id, [FromBody] UpdateGroupRequest request, CancellationToken ct)
{
var result = await _groupService.UpdateAsync(id, request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Delete a group (soft-delete, Admin only).</summary>
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var result = await _groupService.DeleteAsync(id, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Add a user to a group (Admin only).</summary>
[HttpPost("{groupId:guid}/users/{userId:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> AddUser(Guid groupId, Guid userId, CancellationToken ct)
{
var result = await _groupService.AddUserAsync(groupId, userId, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Remove a user from a group (Admin only).</summary>
[HttpDelete("{groupId:guid}/users/{userId:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> RemoveUser(Guid groupId, Guid userId, CancellationToken ct)
{
var result = await _groupService.RemoveUserAsync(groupId, userId, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Get all members of a group (Admin only).</summary>
[HttpGet("{groupId:guid}/users")]
[ProducesResponseType(typeof(IReadOnlyList<GroupMemberResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetMembers(Guid groupId, CancellationToken ct)
{
var result = await _groupService.GetMembersAsync(groupId, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
}
@@ -1,34 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace Heimdall.Api.Controllers;
[ApiController]
public class HealthController : ControllerBase
{
/// <summary>
/// Liveness probe — always returns OK if the process is running.
/// </summary>
[HttpGet("/healthz")]
[ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
public IActionResult Health() => Ok(new { status = "healthy", timestamp = DateTime.UtcNow });
/// <summary>
/// Readiness probe — checks if the database is reachable.
/// Uses ASP.NET Core health checks infrastructure.
/// </summary>
[HttpGet("/readyz")]
[ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status503ServiceUnavailable)]
public async Task<IActionResult> Readiness(
[FromServices] HealthCheckService healthCheckService,
CancellationToken ct)
{
var report = await healthCheckService.CheckHealthAsync(
_ => true, ct);
return report.Status == HealthStatus.Healthy
? Ok(new { status = "healthy", timestamp = DateTime.UtcNow })
: StatusCode(503, new { status = "unhealthy", errors = report.Entries });
}
}
@@ -1,76 +0,0 @@
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
/// <summary>Response DTO for a single permission with its display name and category.</summary>
public record PermissionInfo(string Name, string DisplayName, string Category);
/// <summary>Response DTO for a list of permissions.</summary>
public record PermissionsListResponse(IReadOnlyList<PermissionInfo> Permissions);
[ApiController]
[Route("api/permissions")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[EnableRateLimiting("Api")]
public class PermissionsController : ControllerBase
{
private static readonly Dictionary<string, string> CategoryMap = new()
{
["Site."] = "Sites",
["Camera."] = "Caméras",
["Event."] = "Événements",
["Person."] = "Personnes",
["Admin."] = "Administration",
};
private static readonly Dictionary<string, string> DisplayNames = new()
{
[AppPermissions.SiteRead] = "Lecture des sites",
[AppPermissions.SiteWrite] = "Écriture des sites",
[AppPermissions.SiteDelete] = "Suppression des sites",
[AppPermissions.CameraRead] = "Lecture des caméras",
[AppPermissions.CameraWrite] = "Écriture des caméras",
[AppPermissions.CameraLive] = "Visionnage en direct",
[AppPermissions.CameraRecord] = "Enregistrement",
[AppPermissions.CameraSnapshot] = "Captures d'écran",
[AppPermissions.EventRead] = "Lecture des événements",
[AppPermissions.PersonRead] = "Lecture des personnes",
[AppPermissions.PersonWrite] = "Écriture des personnes",
[AppPermissions.AdminManage] = "Gestion de l'administration",
[AppPermissions.AdminUsers] = "Gestion des utilisateurs",
[AppPermissions.AdminApiKeys] = "Gestion des clés API",
[AppPermissions.AdminJobs] = "Gestion des tâches",
};
/// <summary>Returns all available permissions grouped by category.</summary>
[HttpGet]
[ProducesResponseType(typeof(PermissionsListResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public IActionResult List()
{
var allPermissions = AppPermissions.RolePermissions.Values
.SelectMany(p => p)
.Distinct()
.OrderBy(p => p)
.Select(p => new PermissionInfo(
p,
DisplayNames.GetValueOrDefault(p, p),
GetCategory(p)))
.ToList();
return Ok(new PermissionsListResponse(allPermissions));
}
private static string GetCategory(string permission)
{
foreach (var (prefix, category) in CategoryMap)
{
if (permission.StartsWith(prefix, StringComparison.Ordinal))
return category;
}
return "Autres";
}
}
@@ -1,82 +0,0 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/persons")]
[EnableRateLimiting("Api")]
public class PersonsController : ControllerBase
{
private readonly IPersonService _personService;
public PersonsController(IPersonService personService) => _personService = personService;
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)]
[HttpPost]
public async Task<IActionResult> Create([FromBody] CreatePersonRequest request, CancellationToken ct)
{
var result = await _personService.CreateAsync(request, ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)]
[HttpPut("{id:guid}")]
public async Task<IActionResult> Update(Guid id, [FromBody] UpdatePersonRequest request, CancellationToken ct)
{
var result = await _personService.UpdateAsync(id, request, ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonRead)]
[HttpGet("{id:guid}")]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _personService.GetByIdAsync(id, ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonRead)]
[HttpGet]
public async Task<IActionResult> GetAll([FromQuery] string? category, CancellationToken ct)
{
var result = await _personService.GetAllAsync(category, ct);
return Ok(result.Data);
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)]
[HttpDelete("{id:guid}")]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var result = await _personService.DeleteAsync(id, ct);
return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)]
[HttpPost("{personId:guid}/faces")]
public async Task<IActionResult> RegisterFace(Guid personId, [FromBody] RegisterFaceRequest request, CancellationToken ct)
{
var result = await _personService.RegisterFaceAsync(request with { PersonId = personId }, ct);
return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonRead)]
[HttpGet("{personId:guid}/faces")]
public async Task<IActionResult> GetFaces(Guid personId, CancellationToken ct)
{
var result = await _personService.GetFacesAsync(personId, ct);
return Ok(result.Data);
}
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.PersonWrite)]
[HttpDelete("faces/{faceId:guid}")]
public async Task<IActionResult> DeleteFace(Guid faceId, CancellationToken ct)
{
var result = await _personService.DeleteFaceAsync(faceId, ct);
return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
}
@@ -1,45 +0,0 @@
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
/// <summary>Response DTO for a role with its permissions.</summary>
public record RoleResponse(string Name, IReadOnlyList<string> Permissions);
/// <summary>Response DTO for a list of roles.</summary>
public record RolesListResponse(IReadOnlyList<RoleResponse> Roles);
[ApiController]
[Route("api/roles")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[EnableRateLimiting("Api")]
public class RolesController : ControllerBase
{
/// <summary>Returns all roles with their associated permissions.</summary>
[HttpGet]
[ProducesResponseType(typeof(RolesListResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public IActionResult List()
{
var roles = AppPermissions.RolePermissions
.Select(kvp => new RoleResponse(kvp.Key, kvp.Value))
.ToList();
return Ok(new RolesListResponse(roles));
}
/// <summary>Returns a single role with its permissions.</summary>
[HttpGet("{name}")]
[ProducesResponseType(typeof(RoleResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public IActionResult GetByName(string name)
{
if (!AppPermissions.RolePermissions.TryGetValue(name, out var permissions))
return NotFound(new { error = $"Role '{name}' not found" });
return Ok(new RoleResponse(name, permissions));
}
}
@@ -1,225 +0,0 @@
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Api.Hubs;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/settings")]
[Authorize]
[EnableRateLimiting("Api")]
public class SettingsController : ControllerBase
{
private readonly ISettingService _settingService;
private readonly IConfigBroadcastService _broadcast;
private readonly ILogger<SettingsController> _logger;
public SettingsController(
ISettingService settingService,
IConfigBroadcastService broadcast,
ILogger<SettingsController> logger)
{
_settingService = settingService;
_broadcast = broadcast;
_logger = logger;
}
/// <summary>List all global settings (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpGet]
[ProducesResponseType(typeof(List<AppSettingDto>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> ListAll(CancellationToken ct)
{
var result = await _settingService.GetAllSettingsAsync(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);
}
/// <summary>Get a global setting by key (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpGet("{key}")]
[ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetByKey(string key, CancellationToken ct)
{
var result = await _settingService.GetSettingByKeyAsync(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);
}
/// <summary>Create a new global setting (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpPost]
[ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> Create(
[FromBody] CreateAppSettingRequest request, CancellationToken ct)
{
var result = await _settingService.CreateSettingAsync(request, 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} = {Value}", result.Data.Key, RedactValue(result.Data.ValueType, result.Data.Value));
return Ok(result.Data);
}
/// <summary>Update a global setting (Admin only). Broadcasts the change to all agents.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpPut("{key}")]
[ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update(
string key, [FromBody] UpdateAppSettingRequest request, CancellationToken ct)
{
var result = await _settingService.UpdateSettingAsync(key, request, 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} = {Value}", result.Data.Key, RedactValue(result.Data.ValueType, result.Data.Value));
return Ok(result.Data);
}
/// <summary>Delete a global setting (Admin only). Broadcasts the change to all agents.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpDelete("{key}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(string key, CancellationToken ct)
{
var result = await _settingService.DeleteSettingAsync(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();
}
/// <summary>
/// Get the effective configuration for an agent: global defaults merged with
/// per-agent overrides (Agent or Admin only).
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpGet("agent/{agentId:guid}")]
[ProducesResponseType(typeof(Dictionary<string, string>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetEffectiveConfig(Guid agentId, CancellationToken ct)
{
var result = await _settingService.GetEffectiveAgentConfigAsync(agentId, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>List all setting overrides for a specific agent (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpGet("agent/{agentId:guid}/overrides")]
[ProducesResponseType(typeof(List<AgentSettingDto>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> ListAgentOverrides(Guid agentId, CancellationToken ct)
{
var result = await _settingService.GetAgentSettingsAsync(agentId, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>
/// Set (create or update) a per-agent setting override (Admin only).
/// Broadcasts the change to the affected agent in real-time.
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer", 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<IActionResult> SetAgentOverride(
Guid agentId, [FromBody] SetAgentSettingRequest request, CancellationToken ct)
{
var result = await _settingService.SetAgentSettingAsync(agentId, request, 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} = {Value}",
agentId, result.Data.Key, RedactValue(null, result.Data.Value, result.Data.Key));
return Ok(result.Data);
}
/// <summary>
/// Remove a per-agent setting override (Admin only).
/// Broadcasts a reload notification to the affected agent.
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer", 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<IActionResult> RemoveAgentOverride(Guid agentId, string key, CancellationToken ct)
{
var result = await _settingService.RemoveAgentSettingAsync(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();
}
/// <summary>
/// Broadcast a "ConfigReload" signal to all connected agents so they
/// re-fetch their full configuration (Admin only).
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
[HttpPost("reload")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> 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" });
}
private static string RedactValue(string? valueType, string value, string? key = null)
{
if (valueType is not null && valueType.Contains("password", StringComparison.OrdinalIgnoreCase))
return "***REDACTED***";
if (valueType is not null && valueType.Contains("token", StringComparison.OrdinalIgnoreCase))
return "***REDACTED***";
if (key is not null && key.Contains("password", StringComparison.OrdinalIgnoreCase))
return "***REDACTED***";
if (key is not null && key.Contains("token", StringComparison.OrdinalIgnoreCase))
return "***REDACTED***";
if (key is not null && key.Contains("secret", StringComparison.OrdinalIgnoreCase))
return "***REDACTED***";
return value;
}
}
@@ -1,108 +0,0 @@
using System.Security.Claims;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/sites")]
[EnableRateLimiting("Api")]
public class SitesController : ControllerBase
{
private readonly ISiteService _siteService;
public SitesController(ISiteService siteService) => _siteService = siteService;
/// <summary>Create a new site (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
[HttpPost]
[ProducesResponseType(typeof(SiteWithTokenResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create(
[FromBody] CreateSiteRequest request, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
return Unauthorized(new { error = "Invalid user identity" });
var result = await _siteService.CreateAsync(request, userId, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>List all sites.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet]
[ProducesResponseType(typeof(PagedResult<SiteResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> List(
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _siteService.ListAsync(page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
/// <summary>Get a site by ID.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(SiteResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _siteService.GetByIdAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>Update a site (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
[HttpPut("{id:guid}")]
[ProducesResponseType(typeof(SiteResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update(
Guid id, [FromBody] UpdateSiteRequest request, CancellationToken ct)
{
var result = await _siteService.UpdateAsync(id, request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Delete a site (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteDelete)]
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var result = await _siteService.DeleteAsync(id, ct);
return result.IsSuccess
? NoContent()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Generate a new agent registration token (Admin only).</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
[HttpPost("{id:guid}/tokens")]
[ProducesResponseType(typeof(RegistrationTokenResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GenerateToken(Guid id, CancellationToken ct)
{
var result = await _siteService.GenerateTokenAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
}
@@ -1,44 +0,0 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/stats")]
[EnableRateLimiting("Api")]
public class StatsController : ControllerBase
{
private readonly IStatsService _statsService;
public StatsController(IStatsService statsService) => _statsService = statsService;
/// <summary>Get system-wide statistics.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet]
[ProducesResponseType(typeof(StatsResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> GetStats(CancellationToken ct)
{
var result = await _statsService.GetStatsAsync(ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(new { data = result.Data, timestamp = DateTime.UtcNow });
}
/// <summary>Get agent-specific KPIs for the dashboard.</summary>
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet("agent-stats")]
[ProducesResponseType(typeof(List<AgentStatItem>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> GetAgentStats(CancellationToken ct)
{
var result = await _statsService.GetAgentStatsAsync(ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
}
@@ -1,197 +0,0 @@
using System.Security.Claims;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/users")]
[Authorize(AuthenticationSchemes = "JwtBearer")]
[EnableRateLimiting("Api")]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
public UsersController(IUserService userService) => _userService = userService;
/// <summary>List all users (Admin only).</summary>
[HttpGet]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(typeof(PagedResult<UserResponse>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> List(
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _userService.ListAsync(page, pageSize, ct);
if (!result.IsSuccess)
return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
/// <summary>Get the current user's profile.</summary>
[HttpGet("me")]
[Authorize(AuthenticationSchemes = "JwtBearer")]
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> GetMyProfile(CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
return Unauthorized();
var result = await _userService.GetByIdAsync(userId, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>Update the current user's own profile.</summary>
[HttpPut("me")]
[Authorize(AuthenticationSchemes = "JwtBearer")]
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> UpdateMyProfile(
[FromBody] UpdateUserRequest request, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
return Unauthorized();
var result = await _userService.UpdateAsync(userId, request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Get a user by ID (Admin only).</summary>
[HttpGet("{id:guid}")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var result = await _userService.GetByIdAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: NotFound(new { error = result.Error });
}
/// <summary>Create a new user (Admin only).</summary>
[HttpPost]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create([FromBody] CreateUserRequest request, CancellationToken ct)
{
var result = await _userService.CreateAsync(request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Update a user (Admin only).</summary>
[HttpPut("{id:guid}")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update(
Guid id, [FromBody] UpdateUserRequest request, CancellationToken ct)
{
var result = await _userService.UpdateAsync(id, request, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Assign roles to a user (Admin only).</summary>
[HttpPut("{id:guid}/roles")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> AssignRoles(
Guid id, [FromBody] AssignRolesRequest request, CancellationToken ct)
{
var result = await _userService.AssignRolesAsync(id, request, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Assign sites to a user (Admin only).</summary>
[HttpPut("{id:guid}/sites")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> AssignSites(
Guid id, [FromBody] AssignSitesRequest request, CancellationToken ct)
{
var result = await _userService.AssignSitesAsync(id, request, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Reset a user's password (Admin only).</summary>
[HttpPost("{id:guid}/reset-password")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(typeof(ResetPasswordResponse), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> ResetPassword(Guid id, CancellationToken ct)
{
var result = await _userService.ResetPasswordAsync(id, ct);
return result.IsSuccess
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Delete a user account (Admin only). Self-deletion is forbidden.
/// Cannot delete the last administrator.</summary>
[HttpDelete("{id:guid}")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var currentUserId))
return Unauthorized();
var result = await _userService.DeleteAsync(id, currentUserId, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Lock a user account (Admin only).</summary>
[HttpPost("{id:guid}/lock")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Lock(Guid id, CancellationToken ct)
{
var result = await _userService.LockAsync(id, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Unlock a user account (Admin only).</summary>
[HttpPost("{id:guid}/unlock")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Unlock(Guid id, CancellationToken ct)
{
var result = await _userService.UnlockAsync(id, ct);
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
}
@@ -1,34 +0,0 @@
using System.Net;
using Heimdall.Application.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Heimdall.Api.Filters;
public class ExceptionFilter : IExceptionFilter
{
private readonly ILogger<ExceptionFilter> _logger;
public ExceptionFilter(ILogger<ExceptionFilter> logger) => _logger = logger;
public void OnException(ExceptionContext context)
{
_logger.LogError(context.Exception, "Unhandled exception: {Message}", context.Exception.Message);
var response = new
{
error = new
{
code = "InternalServerError",
message = "An unexpected error occurred"
}
};
context.Result = new ObjectResult(response)
{
StatusCode = (int)HttpStatusCode.InternalServerError
};
context.ExceptionHandled = true;
}
}
-31
View File
@@ -1,31 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="Heimdall.IntegrationTests" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.8" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.10">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Polly.RateLimiting" Version="8.5.2" />
<PackageReference Include="Scalar.AspNetCore" Version="2.0.2" />
<PackageReference Include="Sentry.AspNetCore" Version="6.7.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Heimdall.Application\Heimdall.Application.csproj" />
<ProjectReference Include="..\Heimdall.Infrastructure\Heimdall.Infrastructure.csproj" />
</ItemGroup>
</Project>
-24
View File
@@ -1,24 +0,0 @@
@Heimdall.Api_HostAddress = http://localhost:5240
### Health
GET {{Heimdall.Api_HostAddress}}/healthz
Accept: application/json
### Auth
POST {{Heimdall.Api_HostAddress}}/api/auth/login
Content-Type: application/json
{
"email": "admin@heimdall.test",
"password": "Admin123!Pass"
}
### Sites (requires JWT from /api/auth/login)
GET {{Heimdall.Api_HostAddress}}/api/sites?page=1&pageSize=10
Authorization: Bearer {{token}}
Accept: application/json
### Stats
GET {{Heimdall.Api_HostAddress}}/api/stats
Authorization: Bearer {{token}}
Accept: application/json
-96
View File
@@ -1,96 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Heimdall.Application.Services;
namespace Heimdall.Api.Hubs;
/// <summary>
/// SignalR hub for real-time configuration push to agents.
/// Agents connect and receive config updates instantly when settings change.
/// </summary>
[Authorize(AuthenticationSchemes = "ApiKey")]
public class ConfigHub : Hub
{
private readonly ILogger<ConfigHub> _logger;
public ConfigHub(ILogger<ConfigHub> logger)
{
_logger = logger;
}
/// <summary>
/// Agents call this on connect to join their personal config channel.
/// The agentId comes from the authenticated API key's associated agent.
/// </summary>
public async Task JoinAgentGroup(string agentId)
{
if (!Guid.TryParse(agentId, out var _))
{
await Clients.Caller.SendAsync("Error", "Invalid agentId format");
return;
}
await Groups.AddToGroupAsync(Context.ConnectionId, $"agent_{agentId}");
_logger.LogInformation("Agent {AgentId} joined config group", agentId);
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
_logger.LogInformation("Agent disconnected from config hub: {ConnectionId}", Context.ConnectionId);
await base.OnDisconnectedAsync(exception);
}
}
/// <summary>
/// Service that broadcasts config changes to connected agents via SignalR.
/// Called by the SettingService after any setting change.
/// </summary>
public interface IConfigBroadcastService
{
/// <summary>Notify all connected agents that a global setting changed.</summary>
Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default);
/// <summary>Notify a specific agent that one of its overrides changed.</summary>
Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default);
/// <summary>Notify all agents to reload their full configuration.</summary>
Task NotifyAllAgentsReload(CancellationToken ct = default);
}
/// <summary>
/// Broadcasts config changes to connected agents via SignalR.
/// Injected as a scoped service; the HubContext is a singleton so broadcasting
/// works safely across all connected clients.
/// </summary>
public class ConfigBroadcastService : IConfigBroadcastService
{
private readonly IHubContext<ConfigHub> _hubContext;
private readonly ILogger<ConfigBroadcastService> _logger;
public ConfigBroadcastService(IHubContext<ConfigHub> hubContext, ILogger<ConfigBroadcastService> logger)
{
_hubContext = hubContext;
_logger = logger;
}
/// <inheritdoc />
public async Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting global setting change: {Key} = {Value}", key, value);
await _hubContext.Clients.All.SendAsync("SettingChanged", key, value, ct);
}
/// <inheritdoc />
public async Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting agent setting change: Agent={AgentId}, {Key} = {Value}", agentId, key, value);
await _hubContext.Clients.Group($"agent_{agentId}").SendAsync("SettingChanged", key, value, ct);
}
/// <inheritdoc />
public async Task NotifyAllAgentsReload(CancellationToken ct = default)
{
_logger.LogInformation("Broadcasting full config reload to all agents");
await _hubContext.Clients.All.SendAsync("ConfigReload", ct);
}
}
-76
View File
@@ -1,76 +0,0 @@
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
namespace Heimdall.Api.Hubs;
/// <summary>
/// SignalR hub for real-time camera events pushed to the web UI.
/// Connected clients receive new events instantly (motion, person, vehicle, etc.)
/// without polling.
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer")]
public class EventsHub : Hub
{
private readonly ILogger<EventsHub> _logger;
public EventsHub(ILogger<EventsHub> logger) => _logger = logger;
/// <summary>
/// Clients call this to join a group-filtered event feed (e.g., per site).
/// </summary>
public async Task JoinSiteEvents(string siteId)
{
if (!Guid.TryParse(siteId, out _))
{
await Clients.Caller.SendAsync("Error", "Invalid siteId format");
return;
}
await Groups.AddToGroupAsync(Context.ConnectionId, $"site_{siteId}");
_logger.LogDebug("Client {ConnectionId} joined site events group {SiteId}", Context.ConnectionId, siteId);
}
/// <summary>
/// Clients call this to leave a group-filtered event feed.
/// </summary>
public async Task LeaveSiteEvents(string siteId)
{
if (!Guid.TryParse(siteId, out _)) return;
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"site_{siteId}");
}
public override async Task OnConnectedAsync()
{
_logger.LogDebug("Client connected to events hub: {ConnectionId}", Context.ConnectionId);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
_logger.LogDebug("Client disconnected from events hub: {ConnectionId}", Context.ConnectionId);
await base.OnDisconnectedAsync(exception);
}
}
/// <summary>
/// Sends SignalR notifications when new camera events are created.
/// Uses IHubContext for thread-safe broadcasting outside of hub connections.
/// </summary>
public class EventBroadcastService : IEventBroadcastService
{
private readonly IHubContext<EventsHub> _hubContext;
private readonly ILogger<EventBroadcastService> _logger;
public EventBroadcastService(IHubContext<EventsHub> hubContext, ILogger<EventBroadcastService> logger)
{
_hubContext = hubContext;
_logger = logger;
}
public async Task NotifyEventCreated(CameraEventResponse ev, CancellationToken ct = default)
{
_logger.LogDebug("Broadcasting new event: {EventId} type={Type} camera={CameraId}", ev.Id, ev.Type, ev.CameraId);
await _hubContext.Clients.Group($"site_{ev.SiteId}").SendAsync("EventCreated", ev, ct);
}
}
-298
View File
@@ -1,298 +0,0 @@
using System.Text;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.RateLimiting;
using Scalar.AspNetCore;
using Heimdall.Api.Filters;
using Heimdall.Application;
using Heimdall.Application.Services;
using Heimdall.Infrastructure;
using Heimdall.Api.Hubs;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
// ── Sentry (GlitchTip) — DSN from env var only ───────────────────
var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN");
var builder = WebApplication.CreateBuilder(args);
// ── Sentry ────────────────────────────────────────────────────────
if (sentryDsn is not null)
{
builder.WebHost.UseSentry(options =>
{
options.Dsn = sentryDsn;
options.MinimumBreadcrumbLevel = LogLevel.Debug;
options.MinimumEventLevel = LogLevel.Error;
options.TracesSampleRate = 0.1;
});
}
// ── Rate Limiting (Polly/System.Threading.RateLimiting) ───────────
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;
});
});
// ── Services ──────────────────────────────────────────────────────
if (!builder.Environment.IsEnvironment("Testing"))
{
builder.Services.AddControllers(options =>
{
options.Filters.Add<ExceptionFilter>();
});
}
else
{
builder.Services.AddControllers();
}
// Auto-validation with FluentValidation
builder.Services.AddFluentValidationAutoValidation();
// Global JSON serialization — string enums for API responses
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.AddOpenApi();
// ── Application layer ─────────────────────────────────────────────
builder.Services.AddApplication();
// ── Infrastructure layer ──────────────────────────────────────────
builder.Services.AddInfrastructure(builder.Configuration, builder.Environment.EnvironmentName);
// ── Authentication ────────────────────────────────────────────────
var jwtKey = builder.Configuration["Jwt:Key"]
?? Environment.GetEnvironmentVariable("JWT__KEY")
?? throw new InvalidOperationException("JWT:Key is not configured");
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall";
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api";
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer("JwtBearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
ValidateIssuer = true,
ValidIssuer = jwtIssuer,
ValidateAudience = true,
ValidAudience = jwtAudience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
// SignalR WebSocket transport sends JWT as access_token query parameter
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
path.StartsWithSegments("/hubs"))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
})
.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>("ApiKey", null);
// ── Authorization policies ───────────────────────────────────────
builder.Services.AddAuthorization(options =>
{
var allPermissions = AppPermissions.RolePermissions.Values
.SelectMany(p => p).Distinct();
foreach (var permission in allPermissions)
{
options.AddPolicy(permission, policy =>
policy.RequireClaim("permission", permission));
}
});
// ── CORS ──────────────────────────────────────────────────────────
var allowedOrigins = builder.Configuration["Cors:AllowedOrigins"]?.Split(',')
?? ["https://localhost:5001"];
builder.Services.AddCors(options =>
{
var isWildcard = allowedOrigins.Length == 1 && allowedOrigins[0] == "*";
if (isWildcard)
{
options.AddPolicy("ApiPolicy", policy =>
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
}
else
{
options.AddPolicy("ApiPolicy", policy =>
policy.WithOrigins(allowedOrigins)
.AllowCredentials()
.AllowAnyHeader()
.WithMethods("GET", "POST", "PUT", "DELETE", "PATCH"));
}
});
// ── Pipeline ──────────────────────────────────────────────────────
var app = builder.Build();
// ── Apply pending migrations before any database access ──────────────
// Migration runs inline (not as IHostedService) to guarantee the schema
// exists before Identity seeding below and before the web host starts
// serving requests. Using a separate scope keeps migration lifetime
// independent of the seeding scope.
// Retry with exponential backoff to handle container startup races where
// PostgreSQL accepts TCP connections but isn't ready to serve queries yet
// (see GlitchTip #538 — Failed executing DbCommand on __EFMigrationsHistory).
if (!app.Environment.IsEnvironment("Testing"))
{
using var migrationScope = app.Services.CreateScope();
var migrationLogger = migrationScope.ServiceProvider
.GetRequiredService<ILogger<Program>>();
var db = migrationScope.ServiceProvider.GetRequiredService<AppDbContext>();
var maxRetries = 5;
var retryDelay = TimeSpan.FromSeconds(2);
for (var attempt = 1; attempt <= maxRetries; attempt++)
{
try
{
migrationLogger.LogInformation("Applying pending database migrations (attempt {Attempt}/{MaxRetries})...", attempt, maxRetries);
await db.Database.MigrateAsync(CancellationToken.None);
migrationLogger.LogInformation("Database migrations applied successfully");
break;
}
catch (Exception ex) when (attempt < maxRetries)
{
migrationLogger.LogWarning(ex,
"Database migration attempt {Attempt}/{MaxRetries} failed. Retrying in {Delay}s...",
attempt, maxRetries, retryDelay.TotalSeconds);
await Task.Delay(retryDelay);
retryDelay = TimeSpan.FromSeconds(retryDelay.TotalSeconds * 2); // Exponential backoff
}
catch (Exception ex)
{
migrationLogger.LogCritical(ex, "Failed to apply database migrations after {MaxRetries} attempts. " +
"The application cannot start without a migrated database. " +
"Ensure the database server is running and accessible.", maxRetries);
throw;
}
}
}
// ── Seed Identity roles (requires roles table to exist) ──────────────
using var seedScope = app.Services.CreateScope();
{
var roleManager = seedScope.ServiceProvider
.GetRequiredService<Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Domain.Entities.AppRole>>();
var userManager = seedScope.ServiceProvider
.GetRequiredService<Microsoft.AspNetCore.Identity.UserManager<Heimdall.Domain.Entities.AppUser>>();
foreach (var roleName in AppRoles.All)
{
if (!await roleManager.RoleExistsAsync(roleName))
{
await roleManager.CreateAsync(new Heimdall.Domain.Entities.AppRole(roleName));
}
}
// Seed default groups
var groupDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
var defaultGroups = new[] { "Administrateurs", "Superviseurs", "Visiteurs", "Techniciens" };
foreach (var groupName in defaultGroups)
{
if (!await groupDb.Groups.AnyAsync(g => g.Name == groupName))
{
groupDb.Groups.Add(new Heimdall.Domain.Entities.Group(groupName,
groupName switch
{
"Administrateurs" => "Accès complet à toutes les fonctionnalités",
"Superviseurs" => "Gestion des sites, caméras et événements",
"Visiteurs" => "Consultation en lecture seule",
"Techniciens" => "Maintenance technique et support",
_ => null
}));
}
}
await groupDb.SaveChangesWithRetryAsync();
// Seed demo admin in Development (NOT Testing — tests create their own users)
if (app.Environment.IsDevelopment())
{
var testAdmin = await userManager.FindByEmailAsync("admin@heimdall.test");
if (testAdmin is null)
{
testAdmin = new Heimdall.Domain.Entities.AppUser
{
UserName = "admin@heimdall.test",
Email = "admin@heimdall.test",
DisplayName = "Admin"
};
await userManager.CreateAsync(testAdmin, "Admin123!Pass");
await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin);
}
var demoDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
var demoSite = await demoDb.Sites.FirstOrDefaultAsync(s => s.Name == "Site Démo");
if (demoSite is null)
{
demoSite = new Heimdall.Domain.Entities.Site("Site Démo", "Paris", "Europe/Paris");
demoDb.Sites.Add(demoSite);
await demoDb.SaveChangesWithRetryAsync();
}
}
}
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference(); // Beautiful API docs UI
}
app.UseCors("ApiPolicy");
app.UseHttpsRedirection();
app.UseRateLimiter();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapHub<ConfigHub>("/hubs/config");
app.MapHub<EventsHub>("/hubs/events");
app.Run();
@@ -1,23 +0,0 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5240",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7046;http://localhost:5240",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
@@ -1,8 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
-9
View File
@@ -1,9 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
+3
View File
@@ -6,8 +6,11 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.0" />
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.17" />
<PackageReference Include="Scalar.AspNetCore" Version="2.0.2" />
<PackageReference Include="Hangfire.PostgreSql" Version="1.20.10" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.8" />
<PackageReference Include="MudBlazor" Version="9.1.0" />
<PackageReference Include="Sentry.AspNetCore" Version="6.7.0" />
</ItemGroup>
+123 -7
View File
@@ -1,21 +1,27 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using FluentValidation.AspNetCore;
using Heimdall.Application;
using Heimdall.Application.Services;
using Heimdall.Infrastructure;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Jobs;
using Heimdall.Infrastructure.Security;
using Heimdall.Web.Components;
using Heimdall.Api.Hubs;
using Heimdall.Web.Services;
using Hangfire;
using Hangfire.PostgreSql;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using MudBlazor.Services;
using Scalar.AspNetCore;
// ── Sentry (GlitchTip) — DSN from env var only ───────────────────
var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN");
@@ -42,6 +48,12 @@ builder.Services.AddRazorComponents()
// At the ASP.NET Core middleware level, we use cookie authentication
// to persist the user session across requests.
// The cookie is created after successful API login (see /_auth/signin).
var jwtKey = builder.Configuration["Jwt:Key"]
?? Environment.GetEnvironmentVariable("JWT__KEY")
?? throw new InvalidOperationException("JWT:Key is not configured");
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall";
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api";
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
@@ -54,7 +66,40 @@ builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationSc
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.ExpireTimeSpan = TimeSpan.FromDays(7);
options.SlidingExpiration = true;
});
})
.AddJwtBearer("JwtBearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
ValidateIssuer = true,
ValidIssuer = jwtIssuer,
ValidateAudience = true,
ValidAudience = jwtAudience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
// SignalR WebSocket transport sends JWT as access_token query parameter
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
path.StartsWithSegments("/hubs"))
{
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
})
.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>("ApiKey", null);
builder.Services.AddAuthorizationCore(options =>
{
@@ -85,6 +130,47 @@ builder.Services.AddMudServices(config =>
config.SnackbarConfiguration.VisibleStateDuration = 4000;
});
// ── Rate Limiting (Polly/System.Threading.RateLimiting) ───────────
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;
});
});
// ── Controllers (REST API) ────────────────────────────────────────
builder.Services.AddControllers(options =>
{
options.Filters.Add<Heimdall.Api.Filters.ExceptionFilter>();
});
// Auto-validation with FluentValidation
builder.Services.AddFluentValidationAutoValidation();
// Global JSON serialization — string enums for API responses
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.AddOpenApi();
// ── Application layer ─────────────────────────────────────────────
builder.Services.AddApplication();
@@ -155,6 +241,42 @@ app.UseAuthorization();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
// ── REST API controllers & SignalR hubs ───────────────────────────
app.MapControllers();
app.MapHub<ConfigHub>("/hubs/config");
app.MapHub<EventsHub>("/hubs/events");
// ── OpenAPI / Scalar (dev only) ───────────────────────────────────
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference();
}
// ── CORS (for external agents and API clients) ────────────────────
var allowedOrigins = builder.Configuration["Cors:AllowedOrigins"]?.Split(',')
?? ["https://localhost:5001"];
app.UseCors(options =>
{
var isWildcard = allowedOrigins.Length == 1 && allowedOrigins[0] == "*";
if (isWildcard)
{
options.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
}
else
{
options.WithOrigins(allowedOrigins)
.AllowCredentials()
.AllowAnyHeader()
.WithMethods("GET", "POST", "PUT", "DELETE", "PATCH");
}
});
app.UseRateLimiter();
// ── Health check endpoints for Docker ─────────────────────────────
app.MapGet("/healthz", () =>
Results.Ok(new { status = "healthy", timestamp = DateTime.UtcNow }));
@@ -180,12 +302,6 @@ app.MapGet("/readyz", async (HttpContext context) =>
//
// IMPORTANT: The JWT is validated server-side — never trust client-supplied claims.
var jwtKey = builder.Configuration["Jwt:Key"]
?? Environment.GetEnvironmentVariable("JWT__KEY")
?? throw new InvalidOperationException("JWT:Key is not configured");
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall";
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api";
app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request, ILogger<Program> logger) =>
{
if (string.IsNullOrEmpty(request.AccessToken))