feat(api-keys): API key management endpoint + admin UI (#149)

## Summary

Adds API key management functionality to Heimdall:

- **CQRS Handlers**: CreateApiKey, ListApiKeys, RevokeApiKey
- **Controller**: ApiKeysController with admin authorization (Admin.ApiKeys policy)
- **UI**: ApiKeysPage.razor admin page with create, list, and revoke
- **Auth**: Updated ApiKeyAuthenticationHandler to reject expired keys
- **Tests**: 10 unit tests for all handlers

## Changes

- `src/Heimdall.Application/ApiKeys/` — New CQRS handlers and DTOs
- `src/Heimdall.Web/Controllers/ApiKeysController.cs` — Admin API endpoints
- `src/Heimdall.Web/Components/Pages/Admin/ApiKeysPage.razor` — Admin UI
- `src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs` — Expiry check
- `src/Heimdall.Web/Services/HeimdallApiClient.cs` — API client methods
- `tests/Heimdall.Application.Tests/Handlers/ApiKeys/` — Unit tests

## Acceptance Criteria

- [x] POST /api/api-keys → key created (plain shown once, hash in DB)
- [x] GET /api/api-keys → prefix only (never the full key)
- [x] DELETE /api/api-keys/{id} → key revoked immediately
- [x] Expired keys rejected by auth handler
- [x] Admin UI with create, list, and revoke functionality
- [x] All tests passing (10 new tests)

Closes #10

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/149
This commit is contained in:
Arnaud Dartois authored and Arnaud Dartois committed 2026-08-19 22:47:22 +02:00
1 parent f54bb596af
commit b0cfd50c3f
11 files changed
+843 -26

No files matched your search

@@ -0,0 +1,85 @@
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<ApiKeysController> _logger;
public ApiKeysController(IMediator mediator, ILogger<ApiKeysController> logger)
{
_mediator = mediator;
_logger = logger;
}
/// <summary>
/// List all API keys (prefix only, never the full key). Admin only.
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminApiKeys)]
[HttpGet]
[ProducesResponseType(typeof(List<ApiKeyDto>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> 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 });
}
/// <summary>
/// Create a new API key. The plain key is returned only once. Admin only.
/// </summary>
[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<IActionResult> 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);
}
/// <summary>
/// Revoke (disable) an API key immediately. Admin only.
/// </summary>
[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<IActionResult> 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();
}
}