using Heimdall.Application.ApiKeys.Commands.CreateApiKey; using Heimdall.Application.ApiKeys.Commands.RevokeApiKey; using Heimdall.Application.ApiKeys.Queries.ListApiKeys; using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Infrastructure.Security; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; namespace Heimdall.Api.Controllers; [ApiController] [Route("api/api-keys")] [Authorize(AuthenticationSchemes = "JwtBearer,Cookies")] [EnableRateLimiting("Api")] public class ApiKeysController : ControllerBase { private readonly IMediator _mediator; private readonly ILogger _logger; public ApiKeysController(IMediator mediator, ILogger logger) { _mediator = mediator; _logger = logger; } /// /// List all API keys (prefix only, never the full key). Admin only. /// [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminApiKeys)] [HttpGet] [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task List(CancellationToken ct) { var result = await _mediator.Send(new ListApiKeysQuery(), ct); return result.IsSuccess ? Ok(result.Data) : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); } /// /// Create a new API key. The plain key is returned only once. Admin only. /// [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminApiKeys)] [HttpPost] [ProducesResponseType(typeof(CreateApiKeyResult), StatusCodes.Status200OK)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] public async Task Create( [FromBody] CreateApiKeyRequest request, CancellationToken ct) { var command = new CreateApiKeyCommand(request.SiteId, request.ExpiresAt); var result = await _mediator.Send(command, ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); _logger.LogInformation("API key created: prefix={Prefix}, site={SiteId}", result.Data!.KeyPrefix, result.Data.SiteId?.ToString() ?? "(global)"); return Ok(result.Data); } /// /// Revoke (disable) an API key immediately. Admin only. /// [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminApiKeys)] [HttpDelete("{id:guid}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)] public async Task Revoke(Guid id, CancellationToken ct) { var result = await _mediator.Send(new RevokeApiKeyCommand(id), ct); if (!result.IsSuccess) return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); _logger.LogInformation("API key revoked: {KeyId}", id); return NoContent(); } }