diff --git a/Heimdall.slnx b/Heimdall.slnx index 2115356..9b1e549 100644 --- a/Heimdall.slnx +++ b/Heimdall.slnx @@ -1,7 +1,6 @@ - diff --git a/src/Heimdall.Api/Controllers/AgentsController.cs b/src/Heimdall.Api/Controllers/AgentsController.cs deleted file mode 100644 index ed1bf6f..0000000 --- a/src/Heimdall.Api/Controllers/AgentsController.cs +++ /dev/null @@ -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; - - /// Register an agent using a site registration token. - [AllowAnonymous] - [HttpPost("register")] - [ProducesResponseType(typeof(RegisterAgentResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - public async Task 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 }); - } - - /// Send heartbeat from agent (API Key auth). - [Authorize(AuthenticationSchemes = "ApiKey")] - [HttpPost("{id:guid}/heartbeat")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Get agent details (JWT auth). - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] - [HttpGet("{id:guid}")] - [ProducesResponseType(typeof(AgentResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task GetById(Guid id, CancellationToken ct) - { - var result = await _agentService.GetByIdAsync(id, ct); - return result.IsSuccess - ? Ok(result.Data) - : NotFound(new { error = result.Error }); - } - - /// List agents for a site. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] - [HttpGet("by-site/{siteId:guid}")] - [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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); - } - - /// List all agents across all sites. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] - [HttpGet] - [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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); - } -} diff --git a/src/Heimdall.Api/Controllers/AssignmentsController.cs b/src/Heimdall.Api/Controllers/AssignmentsController.cs deleted file mode 100644 index 3191108..0000000 --- a/src/Heimdall.Api/Controllers/AssignmentsController.cs +++ /dev/null @@ -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; - -/// -/// 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. -/// -[ApiController] -[Route("api/assignments")] -[EnableRateLimiting("Api")] -[Authorize(AuthenticationSchemes = "JwtBearer")] -public class AssignmentsController : ControllerBase -{ - private readonly ICameraAssignmentService _assignmentService; - - public AssignmentsController(ICameraAssignmentService assignmentService) - { - _assignmentService = assignmentService; - } - - /// Assign a single camera to a specific agent. - [HttpPost] - [Authorize(Policy = AppPermissions.CameraWrite)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task 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 }); - } - - /// Assign all cameras in a site using a strategy. - [HttpPost("site/{siteId:guid}")] - [Authorize(Policy = AppPermissions.CameraWrite)] - [ProducesResponseType(typeof(AssignmentResult), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task AssignSiteCameras(Guid siteId, [FromQuery] string strategy = "RoundRobin", CancellationToken ct = default) - { - if (!Enum.TryParse(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 }); - } - - /// Trigger failover for an offline agent — reassign its cameras. - [HttpPost("failover/{agentId:guid}")] - [Authorize(Policy = AppPermissions.CameraWrite)] - [ProducesResponseType(typeof(FailoverResult), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task 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 }); - } - - /// Get the active assignment for a camera. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] - [HttpGet("camera/{cameraId:guid}")] - [ProducesResponseType(typeof(AssignmentResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task 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)); - } - - /// Get all active assignments (workload) for an agent. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] - [HttpGet("agent/{agentId:guid}")] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - public async Task 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()); - } - - /// Get assignment history for a camera. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] - [HttpGet("camera/{cameraId:guid}/history")] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - public async Task 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()); - } - - /// Release a camera from its current agent. - [HttpDelete("camera/{cameraId:guid}")] - [Authorize(Policy = AppPermissions.CameraWrite)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task ReleaseCamera(Guid cameraId, CancellationToken ct) - { - var result = await _assignmentService.ReleaseCameraAsync(cameraId, ct); - return result.IsSuccess - ? Ok() - : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); - } -} diff --git a/src/Heimdall.Api/Controllers/AuditLogsController.cs b/src/Heimdall.Api/Controllers/AuditLogsController.cs deleted file mode 100644 index 7b9659f..0000000 --- a/src/Heimdall.Api/Controllers/AuditLogsController.cs +++ /dev/null @@ -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; - - /// List audit log entries with optional filtering. - [HttpGet] - [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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); - } -} diff --git a/src/Heimdall.Api/Controllers/AuthController.cs b/src/Heimdall.Api/Controllers/AuthController.cs deleted file mode 100644 index 02ca8d2..0000000 --- a/src/Heimdall.Api/Controllers/AuthController.cs +++ /dev/null @@ -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; - } - - /// Register a new user. - [AllowAnonymous] - [HttpPost("register")] - [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Authenticate a user. - [AllowAnonymous] - [HttpPost("login")] - [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - public async Task 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 }); - } - - /// Verify a 2FA code. - [AllowAnonymous] - [HttpPost("2fa/verify")] - [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - public async Task 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 }); - } - - /// Refresh an authentication token. - [AllowAnonymous] - [HttpPost("refresh")] - [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - public async Task 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 }); - } - - /// Change the current user's password. - [Authorize] - [HttpPost("change-password")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - public async Task 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 }); - } - - /// Test/Dev-only: register a user with Admin role (bypasses chicken-and-egg). - [AllowAnonymous] - [HttpPost("register-admin")] - [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - [ProducesResponseType(StatusCodes.Status404NotFound)] - public async Task 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 }); - } - - /// Logout — revoke the current refresh token. - [Authorize] - [HttpPost("logout")] - [ProducesResponseType(StatusCodes.Status200OK)] - public async Task 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(); - } -} diff --git a/src/Heimdall.Api/Controllers/CamerasController.cs b/src/Heimdall.Api/Controllers/CamerasController.cs deleted file mode 100644 index 2111a8e..0000000 --- a/src/Heimdall.Api/Controllers/CamerasController.cs +++ /dev/null @@ -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; - - /// Create a new camera. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] - [HttpPost] - [ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Get a camera by ID. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] - [HttpGet("{id:guid}")] - [ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task GetById(Guid id, CancellationToken ct) - { - var result = await _cameraService.GetByIdAsync(id, ct); - return result.IsSuccess - ? Ok(result.Data) - : NotFound(new { error = result.Error }); - } - - /// List cameras by site. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] - [HttpGet("by-site/{siteId:guid}")] - [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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); - } - - /// Update a camera. - [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 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 }); - } - - /// Delete a camera. - [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 Delete(Guid id, CancellationToken ct) - { - var result = await _cameraService.DeleteAsync(id, ct); - return result.IsSuccess - ? NoContent() - : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); - } -} diff --git a/src/Heimdall.Api/Controllers/DiscoveryController.cs b/src/Heimdall.Api/Controllers/DiscoveryController.cs deleted file mode 100644 index f19a33b..0000000 --- a/src/Heimdall.Api/Controllers/DiscoveryController.cs +++ /dev/null @@ -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; - -/// -/// Camera discovery endpoints. -/// Provides network probing, camera database search, stream URL building, -/// stream testing, and discovery confirmation. -/// -[ApiController] -[Route("api/discovery")] -[EnableRateLimiting("Api")] -public class DiscoveryController : ControllerBase -{ - private readonly ICameraDiscoveryService _discoveryService; - - public DiscoveryController(ICameraDiscoveryService discoveryService) - { - _discoveryService = discoveryService; - } - - /// Probe a single IP address for camera services. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] - [HttpPost("probe")] - [ProducesResponseType(typeof(ProbeResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Scan a subnet for camera devices. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] - [HttpPost("scan")] - [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Search the built-in camera database by brand, model, or preset. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] - [HttpGet("search")] - [ProducesResponseType(typeof(SearchResponse), StatusCodes.Status200OK)] - public async Task SearchDatabase([FromQuery] string? q, CancellationToken ct) - { - var result = await _discoveryService.SearchDatabaseAsync(q ?? "", ct); - return Ok(result.Data); - } - - /// Build stream URLs from camera database entries. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] - [HttpPost("build-urls")] - [ProducesResponseType(typeof(StreamBuildResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Test stream URLs. Returns a session ID for polling. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] - [HttpPost("test-streams")] - [ProducesResponseType(typeof(StreamTestSession), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Poll a stream test session for updated results. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] - [HttpGet("test/{sessionId:guid}")] - [ProducesResponseType(typeof(StreamTestSession), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task 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 }); - } - - /// Get a screenshot from a stream test session. - [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 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"); - } - - /// Cancel a running stream test session. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] - [HttpPost("test/{sessionId:guid}/cancel")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task CancelTestSession(Guid sessionId, CancellationToken ct) - { - var result = await _discoveryService.CancelTestSessionAsync(sessionId, ct); - return result.IsSuccess - ? Ok() - : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); - } - - /// Check if a camera already exists for this IP/MAC (anti-duplication). - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] - [HttpPost("check")] - [ProducesResponseType(typeof(CameraCheckResponse), StatusCodes.Status200OK)] - public async Task CheckDuplicate([FromBody] CheckDuplicateRequest request, CancellationToken ct) - { - var result = await _discoveryService.CheckDuplicateAsync(request, ct); - return Ok(result.Data); - } - - /// Confirm a discovery result and create a Camera entity. - [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 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 }); - } -} diff --git a/src/Heimdall.Api/Controllers/EventsController.cs b/src/Heimdall.Api/Controllers/EventsController.cs deleted file mode 100644 index 9de7180..0000000 --- a/src/Heimdall.Api/Controllers/EventsController.cs +++ /dev/null @@ -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; - -/// -/// Camera detection events — motion, person, vehicle, face recognition, etc. -/// Agents POST events as they detect them; users GET filtered views. -/// -[ApiController] -[Route("api/events")] -[EnableRateLimiting("Api")] -public class EventsController : ControllerBase -{ - private readonly ICameraEventService _eventService; - - public EventsController(ICameraEventService eventService) => _eventService = eventService; - - /// Record a new detection event (called by agents). - [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] - [HttpPost] - [ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Get a single event by ID. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] - [HttpGet("{id:guid}")] - [ProducesResponseType(typeof(CameraEventResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task 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 }); - } - - /// Query events with filters. Supports pagination. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] - [HttpGet] - [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] - public async Task 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(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); - } - - /// Get recent events for a camera. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)] - [HttpGet("camera/{cameraId:guid}")] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - public async Task GetRecentByCamera(Guid cameraId, [FromQuery] int count = 20, CancellationToken ct = default) - { - var result = await _eventService.GetRecentByCameraAsync(cameraId, count, ct); - return Ok(result.Data); - } - - /// Attach a snapshot URL to an event (called by agents after upload). - [Authorize(AuthenticationSchemes = "ApiKey", Policy = AppPermissions.CameraWrite)] - [HttpPost("{id:guid}/snapshot")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task 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 }); - } - - /// Delete an event. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)] - [HttpDelete("{id:guid}")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task Delete(Guid id, CancellationToken ct) - { - var result = await _eventService.DeleteAsync(id, ct); - return result.IsSuccess - ? Ok() - : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); - } -} - - diff --git a/src/Heimdall.Api/Controllers/GroupsController.cs b/src/Heimdall.Api/Controllers/GroupsController.cs deleted file mode 100644 index e1deb52..0000000 --- a/src/Heimdall.Api/Controllers/GroupsController.cs +++ /dev/null @@ -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; - -/// -/// CRUD management for user groups and their members (Admin only). -/// -[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; - - /// List all groups (Admin only). - [HttpGet] - [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - public async Task 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); - } - - /// Get a group by ID. - [HttpGet("{id:guid}")] - [ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task GetById(Guid id, CancellationToken ct) - { - var result = await _groupService.GetByIdAsync(id, ct); - return result.IsSuccess - ? Ok(result.Data) - : NotFound(new { error = result.Error }); - } - - /// Create a new group (Admin only). - [HttpPost] - [ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Update a group (Admin only). - [HttpPut("{id:guid}")] - [ProducesResponseType(typeof(GroupResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task 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 }); - } - - /// Delete a group (soft-delete, Admin only). - [HttpDelete("{id:guid}")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task Delete(Guid id, CancellationToken ct) - { - var result = await _groupService.DeleteAsync(id, ct); - return result.IsSuccess - ? Ok() - : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); - } - - /// Add a user to a group (Admin only). - [HttpPost("{groupId:guid}/users/{userId:guid}")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task 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 }); - } - - /// Remove a user from a group (Admin only). - [HttpDelete("{groupId:guid}/users/{userId:guid}")] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task 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 }); - } - - /// Get all members of a group (Admin only). - [HttpGet("{groupId:guid}/users")] - [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task 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 }); - } -} diff --git a/src/Heimdall.Api/Controllers/HealthController.cs b/src/Heimdall.Api/Controllers/HealthController.cs deleted file mode 100644 index 5479fca..0000000 --- a/src/Heimdall.Api/Controllers/HealthController.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Diagnostics.HealthChecks; - -namespace Heimdall.Api.Controllers; - -[ApiController] -public class HealthController : ControllerBase -{ - /// - /// Liveness probe — always returns OK if the process is running. - /// - [HttpGet("/healthz")] - [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] - public IActionResult Health() => Ok(new { status = "healthy", timestamp = DateTime.UtcNow }); - - /// - /// Readiness probe — checks if the database is reachable. - /// Uses ASP.NET Core health checks infrastructure. - /// - [HttpGet("/readyz")] - [ProducesResponseType(typeof(void), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status503ServiceUnavailable)] - public async Task 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 }); - } -} diff --git a/src/Heimdall.Api/Controllers/PermissionsController.cs b/src/Heimdall.Api/Controllers/PermissionsController.cs deleted file mode 100644 index 095f3a0..0000000 --- a/src/Heimdall.Api/Controllers/PermissionsController.cs +++ /dev/null @@ -1,76 +0,0 @@ -using Heimdall.Infrastructure.Security; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.RateLimiting; - -namespace Heimdall.Api.Controllers; - -/// Response DTO for a single permission with its display name and category. -public record PermissionInfo(string Name, string DisplayName, string Category); - -/// Response DTO for a list of permissions. -public record PermissionsListResponse(IReadOnlyList Permissions); - -[ApiController] -[Route("api/permissions")] -[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] -[EnableRateLimiting("Api")] -public class PermissionsController : ControllerBase -{ - private static readonly Dictionary CategoryMap = new() - { - ["Site."] = "Sites", - ["Camera."] = "Caméras", - ["Event."] = "Événements", - ["Person."] = "Personnes", - ["Admin."] = "Administration", - }; - - private static readonly Dictionary 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", - }; - - /// Returns all available permissions grouped by category. - [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"; - } -} diff --git a/src/Heimdall.Api/Controllers/PersonsController.cs b/src/Heimdall.Api/Controllers/PersonsController.cs deleted file mode 100644 index e03b8cc..0000000 --- a/src/Heimdall.Api/Controllers/PersonsController.cs +++ /dev/null @@ -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 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 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 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 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 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 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 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 DeleteFace(Guid faceId, CancellationToken ct) - { - var result = await _personService.DeleteFaceAsync(faceId, ct); - return result.IsSuccess ? Ok() : StatusCode(result.StatusCode ?? 404, new { error = result.Error }); - } -} diff --git a/src/Heimdall.Api/Controllers/RolesController.cs b/src/Heimdall.Api/Controllers/RolesController.cs deleted file mode 100644 index f356e29..0000000 --- a/src/Heimdall.Api/Controllers/RolesController.cs +++ /dev/null @@ -1,45 +0,0 @@ -using Heimdall.Infrastructure.Security; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.RateLimiting; - -namespace Heimdall.Api.Controllers; - -/// Response DTO for a role with its permissions. -public record RoleResponse(string Name, IReadOnlyList Permissions); - -/// Response DTO for a list of roles. -public record RolesListResponse(IReadOnlyList Roles); - -[ApiController] -[Route("api/roles")] -[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] -[EnableRateLimiting("Api")] -public class RolesController : ControllerBase -{ - /// Returns all roles with their associated permissions. - [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)); - } - - /// Returns a single role with its permissions. - [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)); - } -} diff --git a/src/Heimdall.Api/Controllers/SettingsController.cs b/src/Heimdall.Api/Controllers/SettingsController.cs deleted file mode 100644 index 45a952f..0000000 --- a/src/Heimdall.Api/Controllers/SettingsController.cs +++ /dev/null @@ -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 _logger; - - public SettingsController( - ISettingService settingService, - IConfigBroadcastService broadcast, - ILogger logger) - { - _settingService = settingService; - _broadcast = broadcast; - _logger = logger; - } - - /// List all global settings (Admin only). - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] - [HttpGet] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - public async Task 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); - } - - /// Get a global setting by key (Admin only). - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] - [HttpGet("{key}")] - [ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task GetByKey(string key, CancellationToken ct) - { - var result = await _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); - } - - /// Create a new global setting (Admin only). - [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 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); - } - - /// Update a global setting (Admin only). Broadcasts the change to all agents. - [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 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); - } - - /// Delete a global setting (Admin only). Broadcasts the change to all agents. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] - [HttpDelete("{key}")] - [ProducesResponseType(StatusCodes.Status204NoContent)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task Delete(string key, CancellationToken ct) - { - var result = await _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(); - } - - /// - /// Get the effective configuration for an agent: global defaults merged with - /// per-agent overrides (Agent or Admin only). - /// - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] - [HttpGet("agent/{agentId:guid}")] - [ProducesResponseType(typeof(Dictionary), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task GetEffectiveConfig(Guid agentId, CancellationToken ct) - { - var result = await _settingService.GetEffectiveAgentConfigAsync(agentId, ct); - return result.IsSuccess - ? Ok(result.Data) - : NotFound(new { error = result.Error }); - } - - /// List all setting overrides for a specific agent (Admin only). - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] - [HttpGet("agent/{agentId:guid}/overrides")] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task ListAgentOverrides(Guid agentId, CancellationToken ct) - { - var result = await _settingService.GetAgentSettingsAsync(agentId, ct); - return result.IsSuccess - ? Ok(result.Data) - : NotFound(new { error = result.Error }); - } - - /// - /// Set (create or update) a per-agent setting override (Admin only). - /// Broadcasts the change to the affected agent in real-time. - /// - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] - [HttpPut("agent/{agentId:guid}/overrides")] - [ProducesResponseType(typeof(AgentSettingDto), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task SetAgentOverride( - Guid agentId, [FromBody] SetAgentSettingRequest request, CancellationToken ct) - { - var 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); - } - - /// - /// Remove a per-agent setting override (Admin only). - /// Broadcasts a reload notification to the affected agent. - /// - [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 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(); - } - - /// - /// Broadcast a "ConfigReload" signal to all connected agents so they - /// re-fetch their full configuration (Admin only). - /// - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)] - [HttpPost("reload")] - [ProducesResponseType(StatusCodes.Status202Accepted)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - public async Task ReloadAllAgents(CancellationToken ct) - { - await _broadcast.NotifyAllAgentsReload(ct); - _logger.LogInformation("Broadcast ConfigReload to all agents"); - return Accepted(new { message = "Config reload broadcast to all connected agents" }); - } - - 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; - } -} diff --git a/src/Heimdall.Api/Controllers/SitesController.cs b/src/Heimdall.Api/Controllers/SitesController.cs deleted file mode 100644 index 86cc237..0000000 --- a/src/Heimdall.Api/Controllers/SitesController.cs +++ /dev/null @@ -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; - - /// Create a new site (Admin only). - [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 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 }); - } - - /// List all sites. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] - [HttpGet] - [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - public async Task 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); - } - - /// Get a site by ID. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] - [HttpGet("{id:guid}")] - [ProducesResponseType(typeof(SiteResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task GetById(Guid id, CancellationToken ct) - { - var result = await _siteService.GetByIdAsync(id, ct); - return result.IsSuccess - ? Ok(result.Data) - : NotFound(new { error = result.Error }); - } - - /// Update a site (Admin only). - [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 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 }); - } - - /// Delete a site (Admin only). - [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 Delete(Guid id, CancellationToken ct) - { - var result = await _siteService.DeleteAsync(id, ct); - return result.IsSuccess - ? NoContent() - : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); - } - - /// Generate a new agent registration token (Admin only). - [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 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 }); - } -} diff --git a/src/Heimdall.Api/Controllers/StatsController.cs b/src/Heimdall.Api/Controllers/StatsController.cs deleted file mode 100644 index a65087e..0000000 --- a/src/Heimdall.Api/Controllers/StatsController.cs +++ /dev/null @@ -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; - - /// Get system-wide statistics. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] - [HttpGet] - [ProducesResponseType(typeof(StatsResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Get agent-specific KPIs for the dashboard. - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)] - [HttpGet("agent-stats")] - [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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); - } -} diff --git a/src/Heimdall.Api/Controllers/UsersController.cs b/src/Heimdall.Api/Controllers/UsersController.cs deleted file mode 100644 index 5a08755..0000000 --- a/src/Heimdall.Api/Controllers/UsersController.cs +++ /dev/null @@ -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; - - /// List all users (Admin only). - [HttpGet] - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] - [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - public async Task 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); - } - - /// Get the current user's profile. - [HttpGet("me")] - [Authorize(AuthenticationSchemes = "JwtBearer")] - [ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - public async Task 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 }); - } - - /// Update the current user's own profile. - [HttpPut("me")] - [Authorize(AuthenticationSchemes = "JwtBearer")] - [ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] - public async Task 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 }); - } - - /// Get a user by ID (Admin only). - [HttpGet("{id:guid}")] - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] - [ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] - public async Task GetById(Guid id, CancellationToken ct) - { - var result = await _userService.GetByIdAsync(id, ct); - return result.IsSuccess - ? Ok(result.Data) - : NotFound(new { error = result.Error }); - } - - /// Create a new user (Admin only). - [HttpPost] - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] - [ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Update a user (Admin only). - [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 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 }); - } - - /// Assign roles to a user (Admin only). - [HttpPut("{id:guid}/roles")] - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Assign sites to a user (Admin only). - [HttpPut("{id:guid}/sites")] - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Reset a user's password (Admin only). - [HttpPost("{id:guid}/reset-password")] - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] - [ProducesResponseType(typeof(ResetPasswordResponse), StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task 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 }); - } - - /// Delete a user account (Admin only). Self-deletion is forbidden. - /// Cannot delete the last administrator. - [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 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 }); - } - - /// Lock a user account (Admin only). - [HttpPost("{id:guid}/lock")] - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task Lock(Guid id, CancellationToken ct) - { - var result = await _userService.LockAsync(id, ct); - return result.IsSuccess - ? Ok() - : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); - } - - /// Unlock a user account (Admin only). - [HttpPost("{id:guid}/unlock")] - [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] - public async Task Unlock(Guid id, CancellationToken ct) - { - var result = await _userService.UnlockAsync(id, ct); - return result.IsSuccess - ? Ok() - : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); - } -} diff --git a/src/Heimdall.Api/Filters/ExceptionFilter.cs b/src/Heimdall.Api/Filters/ExceptionFilter.cs deleted file mode 100644 index 2bfcd16..0000000 --- a/src/Heimdall.Api/Filters/ExceptionFilter.cs +++ /dev/null @@ -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 _logger; - - public ExceptionFilter(ILogger 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; - } -} diff --git a/src/Heimdall.Api/Heimdall.Api.csproj b/src/Heimdall.Api/Heimdall.Api.csproj deleted file mode 100644 index 64e4515..0000000 --- a/src/Heimdall.Api/Heimdall.Api.csproj +++ /dev/null @@ -1,31 +0,0 @@ - - - - net10.0 - enable - enable - - - - - - - - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - - - - - - - - - - diff --git a/src/Heimdall.Api/Heimdall.Api.http b/src/Heimdall.Api/Heimdall.Api.http deleted file mode 100644 index c406c55..0000000 --- a/src/Heimdall.Api/Heimdall.Api.http +++ /dev/null @@ -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 diff --git a/src/Heimdall.Api/Hubs/ConfigHub.cs b/src/Heimdall.Api/Hubs/ConfigHub.cs deleted file mode 100644 index fb6a398..0000000 --- a/src/Heimdall.Api/Hubs/ConfigHub.cs +++ /dev/null @@ -1,96 +0,0 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.SignalR; -using Heimdall.Application.Services; - -namespace Heimdall.Api.Hubs; - -/// -/// SignalR hub for real-time configuration push to agents. -/// Agents connect and receive config updates instantly when settings change. -/// -[Authorize(AuthenticationSchemes = "ApiKey")] -public class ConfigHub : Hub -{ - private readonly ILogger _logger; - - public ConfigHub(ILogger logger) - { - _logger = logger; - } - - /// - /// Agents call this on connect to join their personal config channel. - /// The agentId comes from the authenticated API key's associated agent. - /// - 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); - } -} - -/// -/// Service that broadcasts config changes to connected agents via SignalR. -/// Called by the SettingService after any setting change. -/// -public interface IConfigBroadcastService -{ - /// Notify all connected agents that a global setting changed. - Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default); - - /// Notify a specific agent that one of its overrides changed. - Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default); - - /// Notify all agents to reload their full configuration. - Task NotifyAllAgentsReload(CancellationToken ct = default); -} - -/// -/// 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. -/// -public class ConfigBroadcastService : IConfigBroadcastService -{ - private readonly IHubContext _hubContext; - private readonly ILogger _logger; - - public ConfigBroadcastService(IHubContext hubContext, ILogger logger) - { - _hubContext = hubContext; - _logger = logger; - } - - /// - 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); - } - - /// - 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); - } - - /// - public async Task NotifyAllAgentsReload(CancellationToken ct = default) - { - _logger.LogInformation("Broadcasting full config reload to all agents"); - await _hubContext.Clients.All.SendAsync("ConfigReload", ct); - } -} diff --git a/src/Heimdall.Api/Hubs/EventsHub.cs b/src/Heimdall.Api/Hubs/EventsHub.cs deleted file mode 100644 index 7e0296d..0000000 --- a/src/Heimdall.Api/Hubs/EventsHub.cs +++ /dev/null @@ -1,76 +0,0 @@ -using Heimdall.Application.DTOs; -using Heimdall.Application.Services; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.SignalR; - -namespace Heimdall.Api.Hubs; - -/// -/// SignalR hub for real-time camera events pushed to the web UI. -/// Connected clients receive new events instantly (motion, person, vehicle, etc.) -/// without polling. -/// -[Authorize(AuthenticationSchemes = "JwtBearer")] -public class EventsHub : Hub -{ - private readonly ILogger _logger; - - public EventsHub(ILogger logger) => _logger = logger; - - /// - /// Clients call this to join a group-filtered event feed (e.g., per site). - /// - 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); - } - - /// - /// Clients call this to leave a group-filtered event feed. - /// - 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); - } -} - -/// -/// Sends SignalR notifications when new camera events are created. -/// Uses IHubContext for thread-safe broadcasting outside of hub connections. -/// -public class EventBroadcastService : IEventBroadcastService -{ - private readonly IHubContext _hubContext; - private readonly ILogger _logger; - - public EventBroadcastService(IHubContext hubContext, ILogger 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); - } -} diff --git a/src/Heimdall.Api/Program.cs b/src/Heimdall.Api/Program.cs deleted file mode 100644 index 7ae1623..0000000 --- a/src/Heimdall.Api/Program.cs +++ /dev/null @@ -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(); - }); -} -else -{ - builder.Services.AddControllers(); -} - -// Auto-validation with FluentValidation -builder.Services.AddFluentValidationAutoValidation(); - -// Global JSON serialization — string enums for API responses -builder.Services.Configure(opts => -{ - opts.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter()); -}); - -builder.Services.AddSignalR(); -builder.Services.AddScoped(); -builder.Services.AddScoped(); - -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("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>(); - var db = migrationScope.ServiceProvider.GetRequiredService(); - - 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>(); - var userManager = seedScope.ServiceProvider - .GetRequiredService>(); - - 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(); - 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(); - 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("/hubs/config"); -app.MapHub("/hubs/events"); - -app.Run(); diff --git a/src/Heimdall.Api/Properties/launchSettings.json b/src/Heimdall.Api/Properties/launchSettings.json deleted file mode 100644 index 5ccbc0a..0000000 --- a/src/Heimdall.Api/Properties/launchSettings.json +++ /dev/null @@ -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" - } - } - } -} diff --git a/src/Heimdall.Api/appsettings.Development.json b/src/Heimdall.Api/appsettings.Development.json deleted file mode 100644 index 0c208ae..0000000 --- a/src/Heimdall.Api/appsettings.Development.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/src/Heimdall.Api/appsettings.json b/src/Heimdall.Api/appsettings.json deleted file mode 100644 index 10f68b8..0000000 --- a/src/Heimdall.Api/appsettings.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/src/Heimdall.Web/Heimdall.Web.csproj b/src/Heimdall.Web/Heimdall.Web.csproj index 4f264b9..096b0ce 100644 --- a/src/Heimdall.Web/Heimdall.Web.csproj +++ b/src/Heimdall.Web/Heimdall.Web.csproj @@ -6,8 +6,11 @@ + + + diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 587d2a8..61592cd 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -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("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(); +}); + +// Auto-validation with FluentValidation +builder.Services.AddFluentValidationAutoValidation(); + +// Global JSON serialization — string enums for API responses +builder.Services.Configure(opts => +{ + opts.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter()); +}); + +builder.Services.AddSignalR(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +builder.Services.AddOpenApi(); + // ── Application layer ───────────────────────────────────────────── builder.Services.AddApplication(); @@ -155,6 +241,42 @@ app.UseAuthorization(); app.MapRazorComponents() .AddInteractiveServerRenderMode(); +// ── REST API controllers & SignalR hubs ─────────────────────────── +app.MapControllers(); +app.MapHub("/hubs/config"); +app.MapHub("/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 logger) => { if (string.IsNullOrEmpty(request.AccessToken))