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:
1 parent
f54bb596af
commit
b0cfd50c3f
11 files changed
+843
-26
No files matched your search
@@ -0,0 +1,59 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Domain.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Heimdall.Application.ApiKeys.Commands.CreateApiKey;
|
||||
|
||||
public record CreateApiKeyCommand(
|
||||
Guid? SiteId,
|
||||
DateTime? ExpiresAt) : IRequest<ServiceResult<CreateApiKeyResult>>;
|
||||
|
||||
public class CreateApiKeyCommandHandler : IRequestHandler<CreateApiKeyCommand, ServiceResult<CreateApiKeyResult>>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
|
||||
public CreateApiKeyCommandHandler(IApplicationDbContext db) => _db = db;
|
||||
|
||||
public async Task<ServiceResult<CreateApiKeyResult>> Handle(CreateApiKeyCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Validate site exists if provided
|
||||
if (request.SiteId.HasValue)
|
||||
{
|
||||
var siteExists = await _db.Sites.AnyAsync(s => s.Id == request.SiteId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (!siteExists)
|
||||
return ServiceResult<CreateApiKeyResult>.NotFound($"Site '{request.SiteId}' not found");
|
||||
}
|
||||
|
||||
// Validate expiry is in the future
|
||||
if (request.ExpiresAt.HasValue && request.ExpiresAt.Value <= DateTime.UtcNow)
|
||||
return ServiceResult<CreateApiKeyResult>.Failure("Expiration date must be in the future");
|
||||
|
||||
// Generate key
|
||||
var (plainKey, prefix, hash) = GenerateApiKey();
|
||||
|
||||
var apiKey = new ApiKey(hash, prefix, request.SiteId);
|
||||
if (request.ExpiresAt.HasValue)
|
||||
apiKey.SetExpiry(request.ExpiresAt.Value);
|
||||
|
||||
_db.ApiKeys.Add(apiKey);
|
||||
await _db.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult<CreateApiKeyResult>.Success(
|
||||
new CreateApiKeyResult(apiKey.Id, plainKey, prefix, request.SiteId, request.ExpiresAt));
|
||||
}
|
||||
|
||||
/// <summary>Generate a new API key and return (plainKey, prefix, hash).</summary>
|
||||
private static (string plainKey, string prefix, string hash) GenerateApiKey()
|
||||
{
|
||||
var keyBytes = new byte[32];
|
||||
RandomNumberGenerator.Fill(keyBytes);
|
||||
var plainKey = Convert.ToHexString(keyBytes).ToLowerInvariant();
|
||||
var prefix = plainKey[..8];
|
||||
var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(plainKey))).ToLowerInvariant();
|
||||
return (plainKey, prefix, hash);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Heimdall.Application.Common;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.ApiKeys.Commands.RevokeApiKey;
|
||||
|
||||
public record RevokeApiKeyCommand(Guid Id) : IRequest<ServiceResult>;
|
||||
|
||||
public class RevokeApiKeyCommandHandler : IRequestHandler<RevokeApiKeyCommand, ServiceResult>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
|
||||
public RevokeApiKeyCommandHandler(IApplicationDbContext db) => _db = db;
|
||||
|
||||
public async Task<ServiceResult> Handle(RevokeApiKeyCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var apiKey = await _db.ApiKeys
|
||||
.FirstOrDefaultAsync(k => k.Id == request.Id, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (apiKey is null)
|
||||
return ServiceResult.NotFound($"API key '{request.Id}' not found");
|
||||
|
||||
if (!apiKey.Enabled)
|
||||
return ServiceResult.Failure("API key is already revoked");
|
||||
|
||||
apiKey.Disable();
|
||||
await _db.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.DTOs;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Heimdall.Application.ApiKeys.Queries.ListApiKeys;
|
||||
|
||||
public record ListApiKeysQuery : IRequest<ServiceResult<List<ApiKeyDto>>>;
|
||||
|
||||
public class ListApiKeysQueryHandler : IRequestHandler<ListApiKeysQuery, ServiceResult<List<ApiKeyDto>>>
|
||||
{
|
||||
private readonly IApplicationDbContext _db;
|
||||
|
||||
public ListApiKeysQueryHandler(IApplicationDbContext db) => _db = db;
|
||||
|
||||
public async Task<ServiceResult<List<ApiKeyDto>>> Handle(ListApiKeysQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var keys = await _db.ApiKeys
|
||||
.Include(k => k.Site)
|
||||
.OrderByDescending(k => k.CreatedAt)
|
||||
.Select(k => new ApiKeyDto(
|
||||
k.Id,
|
||||
k.KeyPrefix,
|
||||
k.SiteId,
|
||||
k.Site != null ? k.Site.Name : null,
|
||||
k.CreatedByUserId,
|
||||
null, // CreatedByUserName — join with Users if needed
|
||||
k.CreatedAt,
|
||||
k.ExpiresAt,
|
||||
k.Enabled,
|
||||
k.LastUsedAt))
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return ServiceResult<List<ApiKeyDto>>.Success(keys);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace Heimdall.Application.DTOs;
|
||||
|
||||
/// <summary>
|
||||
/// API key representation returned to the client (never includes the full key).
|
||||
/// </summary>
|
||||
public record ApiKeyDto(
|
||||
Guid Id,
|
||||
string KeyPrefix,
|
||||
Guid? SiteId,
|
||||
string? SiteName,
|
||||
Guid? CreatedByUserId,
|
||||
string? CreatedByUserName,
|
||||
DateTime CreatedAt,
|
||||
DateTime? ExpiresAt,
|
||||
bool Enabled,
|
||||
DateTime? LastUsedAt);
|
||||
|
||||
/// <summary>
|
||||
/// Response from POST /api/api-keys — the plain key is shown only once.
|
||||
/// </summary>
|
||||
public record CreateApiKeyResult(
|
||||
Guid Id,
|
||||
string PlainKey,
|
||||
string KeyPrefix,
|
||||
Guid? SiteId,
|
||||
DateTime? ExpiresAt);
|
||||
|
||||
/// <summary>
|
||||
/// Request body for creating a new API key.
|
||||
/// </summary>
|
||||
public record CreateApiKeyRequest(
|
||||
Guid? SiteId,
|
||||
DateTime? ExpiresAt);
|
||||
@@ -20,6 +20,8 @@ public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions { }
|
||||
/// </summary>
|
||||
public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
|
||||
{
|
||||
private const string BearerPrefix = "Bearer ";
|
||||
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
|
||||
public ApiKeyAuthenticationHandler(
|
||||
@@ -34,28 +36,7 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthentic
|
||||
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
// X-API-Key header only (pas de Bearer — réservé au handler JWT).
|
||||
// SignalR clients cannot set custom headers on WebSocket connections:
|
||||
// the .NET client sends the access token as `Authorization: Bearer`
|
||||
// on the HTTP negotiate POST, and browsers send it as the
|
||||
// `access_token` query string. Accept both on hub paths (same
|
||||
// convention as the JwtBearer handler's OnMessageReceived).
|
||||
var apiKey = Request.Headers["X-API-Key"].FirstOrDefault();
|
||||
|
||||
if (string.IsNullOrEmpty(apiKey))
|
||||
{
|
||||
var path = Request.Path;
|
||||
if (path.StartsWithSegments("/hubs"))
|
||||
{
|
||||
var queryToken = Request.Query["access_token"].FirstOrDefault();
|
||||
var bearer = Request.Headers.Authorization.FirstOrDefault();
|
||||
if (!string.IsNullOrEmpty(queryToken))
|
||||
apiKey = queryToken;
|
||||
else if (!string.IsNullOrEmpty(bearer) &&
|
||||
bearer.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
||||
apiKey = bearer["Bearer ".Length..].Trim();
|
||||
}
|
||||
}
|
||||
var apiKey = ResolveApiKeyFromRequest();
|
||||
|
||||
if (string.IsNullOrEmpty(apiKey) || apiKey.Length < 8)
|
||||
return AuthenticateResult.NoResult();
|
||||
@@ -71,11 +52,15 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthentic
|
||||
if (apiKeyEntity is null)
|
||||
return AuthenticateResult.Fail("Invalid API key");
|
||||
|
||||
// Reject expired keys
|
||||
if (apiKeyEntity.ExpiresAt.HasValue && apiKeyEntity.ExpiresAt.Value <= DateTime.UtcNow)
|
||||
return AuthenticateResult.Fail("API key has expired");
|
||||
|
||||
// Hash the incoming key and constant-time compare
|
||||
var incomingHash = SHA256.HashData(Encoding.UTF8.GetBytes(apiKey));
|
||||
var storedHash = Convert.FromHexString(apiKeyEntity.KeyHash);
|
||||
|
||||
if (!System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(incomingHash, storedHash))
|
||||
if (!CryptographicOperations.FixedTimeEquals(incomingHash, storedHash))
|
||||
return AuthenticateResult.Fail("Invalid API key");
|
||||
|
||||
apiKeyEntity.MarkUsed();
|
||||
@@ -84,9 +69,9 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthentic
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, apiKeyEntity.Id.ToString()),
|
||||
new("auth_method", "api_key"),
|
||||
new("api_key_prefix", prefix),
|
||||
new Claim(ClaimTypes.NameIdentifier, apiKeyEntity.Id.ToString()),
|
||||
new Claim("auth_method", "api_key"),
|
||||
new Claim("api_key_prefix", prefix),
|
||||
};
|
||||
|
||||
if (apiKeyEntity.SiteId.HasValue)
|
||||
@@ -107,6 +92,28 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthentic
|
||||
return AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name));
|
||||
}
|
||||
|
||||
/// <summary>Resolve the API key from X-API-Key header, query string, or Bearer token on hub paths.</summary>
|
||||
private string? ResolveApiKeyFromRequest()
|
||||
{
|
||||
var apiKey = Request.Headers["X-API-Key"].FirstOrDefault();
|
||||
if (!string.IsNullOrEmpty(apiKey))
|
||||
return apiKey;
|
||||
|
||||
if (!Request.Path.StartsWithSegments("/hubs"))
|
||||
return null;
|
||||
|
||||
var queryToken = Request.Query["access_token"].FirstOrDefault();
|
||||
if (!string.IsNullOrEmpty(queryToken))
|
||||
return queryToken;
|
||||
|
||||
var bearer = Request.Headers.Authorization.FirstOrDefault();
|
||||
if (!string.IsNullOrEmpty(bearer) &&
|
||||
bearer.StartsWith(BearerPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
return bearer[BearerPrefix.Length..].Trim();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Generate a new API key and return (plainKey, prefix, hash).</summary>
|
||||
public static (string plainKey, string prefix, string hash) GenerateApiKey()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
@page "/admin/api-keys"
|
||||
@attribute [Authorize(Policy = "Admin.ApiKeys")]
|
||||
@layout MainLayout
|
||||
@inject HeimdallApiClient Api
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudText Typo="Typo.h1" Class="mb-6">
|
||||
<i class="fas fa-key mr-2"></i>
|
||||
Clés API
|
||||
</MudText>
|
||||
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => _showCreate = true)" Class="mb-4">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Add" Class="mr-1" /> Créer une clé
|
||||
</MudButton>
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<MudProgressCircular Indeterminate="true" />
|
||||
}
|
||||
else if (_error)
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4" Variant="Variant.Filled">
|
||||
<MudText>Erreur lors du chargement des clés API.</MudText>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Inherit" OnClick="@LoadKeys" Class="mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> Réessayer
|
||||
</MudButton>
|
||||
</MudAlert>
|
||||
}
|
||||
else if (_keys is null || _keys.Count == 0)
|
||||
{
|
||||
<MudAlert Severity="Severity.Info" Class="mb-4">
|
||||
<MudText>Aucune clé API configurée. Créez une clé pour permettre aux agents de se connecter.</MudText>
|
||||
</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
@* KPI Cards *@
|
||||
<MudGrid Class="mb-6">
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudPaper Class="pa-4" Elevation="2" Style="border-radius: 12px;">
|
||||
<MudText Typo="Typo.h3" Color="Color.Primary">@_keys.Count(k => k.Enabled)</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Clés actives</MudText>
|
||||
</MudPaper>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudPaper Class="pa-4" Elevation="2" Style="border-radius: 12px;">
|
||||
<MudText Typo="Typo.h3" Color="Color.Warning">
|
||||
@(_keys.Any(k => k.Enabled && k.ExpiresAt.HasValue)
|
||||
? _keys.Where(k => k.Enabled && k.ExpiresAt.HasValue).Min(k => k.ExpiresAt!.Value).ToString("dd/MM/yyyy")
|
||||
: "—")
|
||||
</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Expiration la plus proche</MudText>
|
||||
</MudPaper>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudPaper Class="pa-4" Elevation="2" Style="border-radius: 12px;">
|
||||
<MudText Typo="Typo.h3" Color="Color.Error">@_keys.Count(k => !k.Enabled)</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary">Clés révoquées</MudText>
|
||||
</MudPaper>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
@* Table *@
|
||||
<MudTable Items="@_keys" Hover="true" Striped="true" Elevation="2">
|
||||
<HeaderContent>
|
||||
<MudTh>Préfixe</MudTh>
|
||||
<MudTh>Site</MudTh>
|
||||
<MudTh>Créée le</MudTh>
|
||||
<MudTh>Expire le</MudTh>
|
||||
<MudTh>Statut</MudTh>
|
||||
<MudTh>Dernière utilisation</MudTh>
|
||||
<MudTh>Actions</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd DataLabel="Préfixe">
|
||||
<MudChip T="string" Size="Size.Small" Color="Color.Default" Variant="Variant.Outlined">
|
||||
@context.KeyPrefix
|
||||
</MudChip>
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Site">@(context.SiteName ?? "—")</MudTd>
|
||||
<MudTd DataLabel="Créée le">@context.CreatedAt.ToString("g")</MudTd>
|
||||
<MudTd DataLabel="Expire le">@(context.ExpiresAt?.ToString("g") ?? "—")</MudTd>
|
||||
<MudTd DataLabel="Statut">
|
||||
@if (context.Enabled)
|
||||
{
|
||||
<MudChip T="string" Size="Size.Small" Color="Color.Success">Actif</MudChip>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudChip T="string" Size="Size.Small" Color="Color.Error">Révoquée</MudChip>
|
||||
}
|
||||
</MudTd>
|
||||
<MudTd DataLabel="Dernière utilisation">@(context.LastUsedAt?.ToString("g") ?? "Jamais")</MudTd>
|
||||
<MudTd DataLabel="Actions">
|
||||
@if (context.Enabled)
|
||||
{
|
||||
<MudTooltip Text="Révoquer cette clé">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Block" Size="Size.Small" Color="Color.Error"
|
||||
aria-label="Révoquer la clé"
|
||||
OnClick="@(() => OpenRevoke(context))" />
|
||||
</MudTooltip>
|
||||
}
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
<NoRecordsContent>
|
||||
<MudText Align="Align.Center" Class="py-4">Aucune clé API</MudText>
|
||||
</NoRecordsContent>
|
||||
</MudTable>
|
||||
}
|
||||
|
||||
@* Dialog: Créer une clé *@
|
||||
<MudOverlay Visible="@_showCreate" OnClick="@(() => _showCreate = false)" />
|
||||
<MudDialog @bind-Visible="_showCreate">
|
||||
<TitleContent><MudText Typo="Typo.h6">Créer une clé API</MudText></TitleContent>
|
||||
<DialogContent>
|
||||
<MudText Typo="Typo.body2" Color="Color.Warning" Class="mb-4">
|
||||
<i class="fas fa-exclamation-triangle mr-1"></i>
|
||||
La clé complète ne sera affichée qu'une seule fois. Copiez-la immédiatement.
|
||||
</MudText>
|
||||
|
||||
<MudTextField @bind-Value="_createSiteId" Label="Site ID (optionnel — laisser vide pour clé globale)"
|
||||
Variant="Variant.Outlined" Class="mb-4" Immediate="true"
|
||||
HelperText="Si spécifié, l'agent ne pourra accéder qu'à ce site." />
|
||||
|
||||
<MudTextField @bind-Value="_createExpiresAt" Label="Date d'expiration (optionnel — YYYY-MM-DD)"
|
||||
Variant="Variant.Outlined" Class="mb-4" Immediate="true"
|
||||
HelperText="Si vide, la clé n'expirera jamais." />
|
||||
|
||||
@if (!string.IsNullOrEmpty(_createError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_createError</MudAlert>
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _showCreate = false)">Annuler</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@CreateKey" Disabled="@_saving">
|
||||
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
Créer
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
|
||||
@* Dialog: Clé créée — affichage unique *@
|
||||
<MudOverlay Visible="@_showCreated" OnClick="@(() => _showCreated = false)" />
|
||||
<MudDialog @bind-Visible="_showCreated">
|
||||
<TitleContent><MudText Typo="Typo.h6">Clé créée avec succès</MudText></TitleContent>
|
||||
<DialogContent>
|
||||
<MudAlert Severity="Severity.Warning" Class="mb-4">
|
||||
<MudText Typo="Typo.body2">
|
||||
<strong>Copiez cette clé maintenant.</strong> Elle ne sera plus jamais affichée.
|
||||
</MudText>
|
||||
</MudAlert>
|
||||
<MudTextField Value="@_createdPlainKey" Label="Clé API" Variant="Variant.Outlined"
|
||||
ReadOnly="true" Adornment="Adornment.End"
|
||||
AdornmentIcon="@Icons.Material.Filled.ContentCopy"
|
||||
OnAdornmentClick="@CopyToClipboard" />
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-2">
|
||||
Préfixe : <strong>@_createdPrefix</strong>
|
||||
</MudText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => _showCreated = false)">
|
||||
J'ai copié la clé
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
|
||||
@* Dialog: Confirmer la révocation *@
|
||||
<MudOverlay Visible="@_showRevokeConfirm" OnClick="@(() => _showRevokeConfirm = false)" />
|
||||
<MudDialog @bind-Visible="_showRevokeConfirm">
|
||||
<TitleContent><MudText Typo="Typo.h6">Révoquer la clé API</MudText></TitleContent>
|
||||
<DialogContent>
|
||||
<MudText Typo="Typo.body1" Class="mb-2">
|
||||
Êtes-vous sûr de vouloir révoquer la clé <strong>@_revokeKey?.KeyPrefix</strong> ?
|
||||
</MudText>
|
||||
<MudText Typo="Typo.body2" Color="Color.Error">
|
||||
Cette action est immédiate et irréversible. L'agent associé ne pourra plus se connecter.
|
||||
</MudText>
|
||||
@if (!string.IsNullOrEmpty(_revokeError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mt-4">@_revokeError</MudAlert>
|
||||
}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton Variant="Variant.Text" OnClick="@(() => _showRevokeConfirm = false)">Annuler</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Error" OnClick="@RevokeKey" Disabled="@_saving">
|
||||
@if (_saving) { <MudProgressCircular Size="Size.Small" Class="mr-1" /> }
|
||||
Révoquer
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
|
||||
@code {
|
||||
private List<ApiKeyListItem>? _keys;
|
||||
private bool _loading = true;
|
||||
private bool _error;
|
||||
private bool _saving;
|
||||
|
||||
// Create dialog
|
||||
private bool _showCreate;
|
||||
private string _createSiteId = "";
|
||||
private string _createExpiresAt = "";
|
||||
private string _createError = "";
|
||||
|
||||
// Created dialog
|
||||
private bool _showCreated;
|
||||
private string _createdPlainKey = "";
|
||||
private string _createdPrefix = "";
|
||||
|
||||
// Revoke dialog
|
||||
private ApiKeyListItem? _revokeKey;
|
||||
private bool _showRevokeConfirm;
|
||||
private string _revokeError = "";
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadKeys();
|
||||
|
||||
private async Task LoadKeys()
|
||||
{
|
||||
_loading = true;
|
||||
_error = false;
|
||||
try
|
||||
{
|
||||
_keys = await Api.GetApiKeysAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_error = true;
|
||||
Snackbar.Add(UiErrors.OperationFailed(), Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Create ───────────────────────────────────────────────────
|
||||
|
||||
private async Task CreateKey()
|
||||
{
|
||||
_saving = true;
|
||||
_createError = "";
|
||||
try
|
||||
{
|
||||
Guid? siteId = null;
|
||||
if (!string.IsNullOrWhiteSpace(_createSiteId))
|
||||
{
|
||||
if (!Guid.TryParse(_createSiteId.Trim(), out var parsed))
|
||||
{
|
||||
_createError = "ID de site invalide";
|
||||
return;
|
||||
}
|
||||
siteId = parsed;
|
||||
}
|
||||
|
||||
DateTime? expiresAt = null;
|
||||
if (!string.IsNullOrWhiteSpace(_createExpiresAt))
|
||||
{
|
||||
if (!DateTime.TryParse(_createExpiresAt.Trim(), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var parsed))
|
||||
{
|
||||
_createError = "Date d'expiration invalide (format : YYYY-MM-DD)";
|
||||
return;
|
||||
}
|
||||
expiresAt = parsed;
|
||||
}
|
||||
|
||||
var result = await Api.CreateApiKeyAsync(siteId, expiresAt);
|
||||
if (result is null)
|
||||
{
|
||||
_createError = "Erreur lors de la création de la clé";
|
||||
return;
|
||||
}
|
||||
|
||||
_showCreate = false;
|
||||
_createSiteId = "";
|
||||
_createExpiresAt = "";
|
||||
|
||||
// Show the plain key once
|
||||
_createdPlainKey = result.PlainKey;
|
||||
_createdPrefix = result.KeyPrefix;
|
||||
_showCreated = true;
|
||||
|
||||
Snackbar.Add("Clé API créée avec succès", Severity.Success);
|
||||
await LoadKeys();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_createError = UiErrors.OperationFailed();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void CopyToClipboard()
|
||||
{
|
||||
// JS interop would be needed for clipboard — for now, user can select and copy
|
||||
Snackbar.Add("Sélectionnez et copiez la clé avec Ctrl+C", Severity.Info);
|
||||
}
|
||||
|
||||
// ─── Revoke ───────────────────────────────────────────────────
|
||||
|
||||
private void OpenRevoke(ApiKeyListItem key)
|
||||
{
|
||||
_revokeKey = key;
|
||||
_revokeError = "";
|
||||
_showRevokeConfirm = true;
|
||||
}
|
||||
|
||||
private async Task RevokeKey()
|
||||
{
|
||||
if (_revokeKey is null) return;
|
||||
_saving = true;
|
||||
_revokeError = "";
|
||||
try
|
||||
{
|
||||
var success = await Api.RevokeApiKeyAsync(_revokeKey.Id);
|
||||
if (!success)
|
||||
{
|
||||
_revokeError = "Erreur lors de la révocation";
|
||||
return;
|
||||
}
|
||||
_showRevokeConfirm = false;
|
||||
_revokeKey = null;
|
||||
Snackbar.Add("Clé API révoquée", Severity.Success);
|
||||
await LoadKeys();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_revokeError = UiErrors.OperationFailed();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_saving = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -671,6 +671,30 @@ public class HeimdallApiClient
|
||||
$"api/settings/agent/{agentId}") ?? [];
|
||||
}
|
||||
|
||||
// ─── API Keys ───────────────────────────────────────────────────
|
||||
|
||||
public async Task<List<ApiKeyListItem>> GetApiKeysAsync()
|
||||
{
|
||||
var client = CreateClient();
|
||||
return await client.GetFromJsonAsync<List<ApiKeyListItem>>("api/api-keys", Json) ?? [];
|
||||
}
|
||||
|
||||
public async Task<CreateApiKeyResult?> CreateApiKeyAsync(Guid? siteId, DateTime? expiresAt)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.PostAsJsonAsync("api/api-keys",
|
||||
new { siteId, expiresAt }, Json);
|
||||
if (!response.IsSuccessStatusCode) return null;
|
||||
return await response.Content.ReadFromJsonAsync<CreateApiKeyResult>(Json);
|
||||
}
|
||||
|
||||
public async Task<bool> RevokeApiKeyAsync(Guid id)
|
||||
{
|
||||
var client = CreateClient();
|
||||
var response = await client.DeleteAsync($"api/api-keys/{id}");
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
|
||||
// ─── Events ────────────────────────────────────────────────────────
|
||||
|
||||
public async Task<EventPageResult?> GetEventsAsync(Guid? cameraId, Guid? siteId, int page = 1, int pageSize = 50,
|
||||
@@ -981,3 +1005,22 @@ public record UpdateNotificationConfigRequest(
|
||||
bool? WeeklyDigest,
|
||||
List<string>? SubscribedEvents
|
||||
);
|
||||
|
||||
// ─── API Key DTOs ──────────────────────────────────────────────────
|
||||
|
||||
public record ApiKeyListItem(
|
||||
[property: JsonPropertyName("id")] Guid Id,
|
||||
[property: JsonPropertyName("keyPrefix")] string KeyPrefix,
|
||||
[property: JsonPropertyName("siteId")] Guid? SiteId,
|
||||
[property: JsonPropertyName("siteName")] string? SiteName,
|
||||
[property: JsonPropertyName("createdAt")] DateTime CreatedAt,
|
||||
[property: JsonPropertyName("expiresAt")] DateTime? ExpiresAt,
|
||||
[property: JsonPropertyName("enabled")] bool Enabled,
|
||||
[property: JsonPropertyName("lastUsedAt")] DateTime? LastUsedAt);
|
||||
|
||||
public record CreateApiKeyResult(
|
||||
[property: JsonPropertyName("id")] Guid Id,
|
||||
[property: JsonPropertyName("plainKey")] string PlainKey,
|
||||
[property: JsonPropertyName("keyPrefix")] string KeyPrefix,
|
||||
[property: JsonPropertyName("siteId")] Guid? SiteId,
|
||||
[property: JsonPropertyName("expiresAt")] DateTime? ExpiresAt);
|
||||
@@ -0,0 +1,91 @@
|
||||
using Heimdall.Application.ApiKeys.Commands.CreateApiKey;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Tests.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Heimdall.Application.Tests.Handlers.ApiKeys;
|
||||
|
||||
public class CreateApiKeyHandlerTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Create_api_key_should_return_success()
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.ApiKeys.Returns(MockDbSetHelper.CreateFor<ApiKey>());
|
||||
context.Sites.Returns(MockDbSetHelper.CreateFor<Site>());
|
||||
context.SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
var handler = new CreateApiKeyCommandHandler(context);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new CreateApiKeyCommand(null, null), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.PlainKey.ShouldNotBeNullOrEmpty();
|
||||
result.Data.KeyPrefix.ShouldBe(result.Data.PlainKey[..8]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_api_key_with_site_should_return_success()
|
||||
{
|
||||
var site = new Site("Test Site", "192.168.1.0/24");
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.ApiKeys.Returns(MockDbSetHelper.CreateFor<ApiKey>());
|
||||
context.Sites.Returns(MockDbSetHelper.CreateFor<Site>([site]));
|
||||
context.SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
var handler = new CreateApiKeyCommandHandler(context);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new CreateApiKeyCommand(site.Id, null), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data!.SiteId.ShouldBe(site.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_api_key_with_nonexistent_site_should_return_not_found()
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.ApiKeys.Returns(MockDbSetHelper.CreateFor<ApiKey>());
|
||||
context.Sites.Returns(MockDbSetHelper.CreateFor<Site>());
|
||||
var handler = new CreateApiKeyCommandHandler(context);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new CreateApiKeyCommand(Guid.NewGuid(), null), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(404);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_api_key_with_past_expiry_should_return_failure()
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.ApiKeys.Returns(MockDbSetHelper.CreateFor<ApiKey>());
|
||||
context.Sites.Returns(MockDbSetHelper.CreateFor<Site>());
|
||||
var handler = new CreateApiKeyCommandHandler(context);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new CreateApiKeyCommand(null, DateTime.UtcNow.AddDays(-1)), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(400);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_api_key_with_future_expiry_should_return_success()
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.ApiKeys.Returns(MockDbSetHelper.CreateFor<ApiKey>());
|
||||
context.Sites.Returns(MockDbSetHelper.CreateFor<Site>());
|
||||
context.SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
var handler = new CreateApiKeyCommandHandler(context);
|
||||
|
||||
var result = await handler.Handle(
|
||||
new CreateApiKeyCommand(null, DateTime.UtcNow.AddDays(30)), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data!.ExpiresAt.ShouldNotBeNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using Heimdall.Application.ApiKeys.Queries.ListApiKeys;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Tests.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Heimdall.Application.Tests.Handlers.ApiKeys;
|
||||
|
||||
public class ListApiKeysHandlerTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task List_api_keys_should_return_empty_when_no_keys()
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.ApiKeys.Returns(MockDbSetHelper.CreateFor<ApiKey>());
|
||||
var handler = new ListApiKeysQueryHandler(context);
|
||||
|
||||
var result = await handler.Handle(new ListApiKeysQuery(), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_api_keys_should_return_keys()
|
||||
{
|
||||
var site = new Site("Test Site", "192.168.1.0/24");
|
||||
var key1 = new ApiKey("hash1", "prefix1", site.Id);
|
||||
var key2 = new ApiKey("hash2", "prefix2");
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.ApiKeys.Returns(MockDbSetHelper.CreateFor<ApiKey>([key1, key2]));
|
||||
context.Sites.Returns(MockDbSetHelper.CreateFor<Site>([site]));
|
||||
var handler = new ListApiKeysQueryHandler(context);
|
||||
|
||||
var result = await handler.Handle(new ListApiKeysQuery(), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.Count.ShouldBe(2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using Heimdall.Application.ApiKeys.Commands.RevokeApiKey;
|
||||
using Heimdall.Application.Common;
|
||||
using Heimdall.Application.Tests.Common;
|
||||
using Heimdall.Domain.Entities;
|
||||
using NSubstitute;
|
||||
|
||||
namespace Heimdall.Application.Tests.Handlers.ApiKeys;
|
||||
|
||||
public class RevokeApiKeyHandlerTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Revoke_existing_key_should_return_success()
|
||||
{
|
||||
var key = new ApiKey("hash1", "prefix1");
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.ApiKeys.Returns(MockDbSetHelper.CreateFor<ApiKey>([key]));
|
||||
context.SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
var handler = new RevokeApiKeyCommandHandler(context);
|
||||
|
||||
var result = await handler.Handle(new RevokeApiKeyCommand(key.Id), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
key.Enabled.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Revoke_nonexistent_key_should_return_not_found()
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.ApiKeys.Returns(MockDbSetHelper.CreateFor<ApiKey>());
|
||||
var handler = new RevokeApiKeyCommandHandler(context);
|
||||
|
||||
var result = await handler.Handle(new RevokeApiKeyCommand(Guid.NewGuid()), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(404);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Revoke_already_revoked_key_should_return_failure()
|
||||
{
|
||||
var key = new ApiKey("hash1", "prefix1");
|
||||
key.Disable(); // Already revoked
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.ApiKeys.Returns(MockDbSetHelper.CreateFor<ApiKey>([key]));
|
||||
var handler = new RevokeApiKeyCommandHandler(context);
|
||||
|
||||
var result = await handler.Handle(new RevokeApiKeyCommand(key.Id), CancellationToken.None);
|
||||
|
||||
result.IsSuccess.ShouldBeFalse();
|
||||
result.StatusCode.ShouldBe(400);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user