diff --git a/src/Heimdall.Application/ApiKeys/Commands/CreateApiKey/CreateApiKeyCommand.cs b/src/Heimdall.Application/ApiKeys/Commands/CreateApiKey/CreateApiKeyCommand.cs new file mode 100644 index 0000000..fabccda --- /dev/null +++ b/src/Heimdall.Application/ApiKeys/Commands/CreateApiKey/CreateApiKeyCommand.cs @@ -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>; + +public class CreateApiKeyCommandHandler : IRequestHandler> +{ + private readonly IApplicationDbContext _db; + + public CreateApiKeyCommandHandler(IApplicationDbContext db) => _db = db; + + public async Task> 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.NotFound($"Site '{request.SiteId}' not found"); + } + + // Validate expiry is in the future + if (request.ExpiresAt.HasValue && request.ExpiresAt.Value <= DateTime.UtcNow) + return ServiceResult.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.Success( + new CreateApiKeyResult(apiKey.Id, plainKey, prefix, request.SiteId, request.ExpiresAt)); + } + + /// Generate a new API key and return (plainKey, prefix, hash). + 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); + } +} diff --git a/src/Heimdall.Application/ApiKeys/Commands/RevokeApiKey/RevokeApiKeyCommand.cs b/src/Heimdall.Application/ApiKeys/Commands/RevokeApiKey/RevokeApiKeyCommand.cs new file mode 100644 index 0000000..35a8778 --- /dev/null +++ b/src/Heimdall.Application/ApiKeys/Commands/RevokeApiKey/RevokeApiKeyCommand.cs @@ -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; + +public class RevokeApiKeyCommandHandler : IRequestHandler +{ + private readonly IApplicationDbContext _db; + + public RevokeApiKeyCommandHandler(IApplicationDbContext db) => _db = db; + + public async Task 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(); + } +} diff --git a/src/Heimdall.Application/ApiKeys/Queries/ListApiKeys/ListApiKeysQuery.cs b/src/Heimdall.Application/ApiKeys/Queries/ListApiKeys/ListApiKeysQuery.cs new file mode 100644 index 0000000..5b8658c --- /dev/null +++ b/src/Heimdall.Application/ApiKeys/Queries/ListApiKeys/ListApiKeysQuery.cs @@ -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>>; + +public class ListApiKeysQueryHandler : IRequestHandler>> +{ + private readonly IApplicationDbContext _db; + + public ListApiKeysQueryHandler(IApplicationDbContext db) => _db = db; + + public async Task>> 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>.Success(keys); + } +} diff --git a/src/Heimdall.Application/DTOs/ApiKeyDto.cs b/src/Heimdall.Application/DTOs/ApiKeyDto.cs new file mode 100644 index 0000000..62d19f7 --- /dev/null +++ b/src/Heimdall.Application/DTOs/ApiKeyDto.cs @@ -0,0 +1,33 @@ +namespace Heimdall.Application.DTOs; + +/// +/// API key representation returned to the client (never includes the full key). +/// +public record ApiKeyDto( + Guid Id, + string KeyPrefix, + Guid? SiteId, + string? SiteName, + Guid? CreatedByUserId, + string? CreatedByUserName, + DateTime CreatedAt, + DateTime? ExpiresAt, + bool Enabled, + DateTime? LastUsedAt); + +/// +/// Response from POST /api/api-keys — the plain key is shown only once. +/// +public record CreateApiKeyResult( + Guid Id, + string PlainKey, + string KeyPrefix, + Guid? SiteId, + DateTime? ExpiresAt); + +/// +/// Request body for creating a new API key. +/// +public record CreateApiKeyRequest( + Guid? SiteId, + DateTime? ExpiresAt); diff --git a/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs b/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs index bf88111..b0587c3 100644 --- a/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs +++ b/src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs @@ -20,6 +20,8 @@ public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions { } /// public class ApiKeyAuthenticationHandler : AuthenticationHandler { + private const string BearerPrefix = "Bearer "; + private readonly IServiceProvider _serviceProvider; public ApiKeyAuthenticationHandler( @@ -34,28 +36,7 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler 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 { - 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 : AuthenticationHandlerResolve the API key from X-API-Key header, query string, or Bearer token on hub paths. + 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; + } + /// Generate a new API key and return (plainKey, prefix, hash). public static (string plainKey, string prefix, string hash) GenerateApiKey() { diff --git a/src/Heimdall.Web/Components/Pages/Admin/ApiKeysPage.razor b/src/Heimdall.Web/Components/Pages/Admin/ApiKeysPage.razor new file mode 100644 index 0000000..716ef57 --- /dev/null +++ b/src/Heimdall.Web/Components/Pages/Admin/ApiKeysPage.razor @@ -0,0 +1,337 @@ +@page "/admin/api-keys" +@attribute [Authorize(Policy = "Admin.ApiKeys")] +@layout MainLayout +@inject HeimdallApiClient Api +@inject ISnackbar Snackbar + + + + Clés API + + + + Créer une clé + + +@if (_loading) +{ + +} +else if (_error) +{ + + Erreur lors du chargement des clés API. + + Réessayer + + +} +else if (_keys is null || _keys.Count == 0) +{ + + Aucune clé API configurée. Créez une clé pour permettre aux agents de se connecter. + +} +else +{ + @* KPI Cards *@ + + + + @_keys.Count(k => k.Enabled) + Clés actives + + + + + + @(_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") + : "—") + + Expiration la plus proche + + + + + @_keys.Count(k => !k.Enabled) + Clés révoquées + + + + + @* Table *@ + + + Préfixe + Site + Créée le + Expire le + Statut + Dernière utilisation + Actions + + + + + @context.KeyPrefix + + + @(context.SiteName ?? "—") + @context.CreatedAt.ToString("g") + @(context.ExpiresAt?.ToString("g") ?? "—") + + @if (context.Enabled) + { + Actif + } + else + { + Révoquée + } + + @(context.LastUsedAt?.ToString("g") ?? "Jamais") + + @if (context.Enabled) + { + + + + } + + + + Aucune clé API + + +} + +@* Dialog: Créer une clé *@ + + + Créer une clé API + + + + La clé complète ne sera affichée qu'une seule fois. Copiez-la immédiatement. + + + + + + + @if (!string.IsNullOrEmpty(_createError)) + { + @_createError + } + + + Annuler + + @if (_saving) { } + Créer + + + + +@* Dialog: Clé créée — affichage unique *@ + + + Clé créée avec succès + + + + Copiez cette clé maintenant. Elle ne sera plus jamais affichée. + + + + + Préfixe : @_createdPrefix + + + + + J'ai copié la clé + + + + +@* Dialog: Confirmer la révocation *@ + + + Révoquer la clé API + + + Êtes-vous sûr de vouloir révoquer la clé @_revokeKey?.KeyPrefix ? + + + Cette action est immédiate et irréversible. L'agent associé ne pourra plus se connecter. + + @if (!string.IsNullOrEmpty(_revokeError)) + { + @_revokeError + } + + + Annuler + + @if (_saving) { } + Révoquer + + + + +@code { + private List? _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; + } + } +} diff --git a/src/Heimdall.Web/Controllers/ApiKeysController.cs b/src/Heimdall.Web/Controllers/ApiKeysController.cs new file mode 100644 index 0000000..1e86cab --- /dev/null +++ b/src/Heimdall.Web/Controllers/ApiKeysController.cs @@ -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 _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(); + } +} diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 924f3c1..c225664 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -671,6 +671,30 @@ public class HeimdallApiClient $"api/settings/agent/{agentId}") ?? []; } + // ─── API Keys ─────────────────────────────────────────────────── + + public async Task> GetApiKeysAsync() + { + var client = CreateClient(); + return await client.GetFromJsonAsync>("api/api-keys", Json) ?? []; + } + + public async Task 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(Json); + } + + public async Task RevokeApiKeyAsync(Guid id) + { + var client = CreateClient(); + var response = await client.DeleteAsync($"api/api-keys/{id}"); + return response.IsSuccessStatusCode; + } + // ─── Events ──────────────────────────────────────────────────────── public async Task GetEventsAsync(Guid? cameraId, Guid? siteId, int page = 1, int pageSize = 50, @@ -981,3 +1005,22 @@ public record UpdateNotificationConfigRequest( bool? WeeklyDigest, List? 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); diff --git a/tests/Heimdall.Application.Tests/Handlers/ApiKeys/CreateApiKeyHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/ApiKeys/CreateApiKeyHandlerTests.cs new file mode 100644 index 0000000..97ee4f8 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/ApiKeys/CreateApiKeyHandlerTests.cs @@ -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(); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor()); + context.Sites.Returns(MockDbSetHelper.CreateFor()); + context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).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(); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor()); + context.Sites.Returns(MockDbSetHelper.CreateFor([site])); + context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).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(); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor()); + context.Sites.Returns(MockDbSetHelper.CreateFor()); + 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(); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor()); + context.Sites.Returns(MockDbSetHelper.CreateFor()); + 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(); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor()); + context.Sites.Returns(MockDbSetHelper.CreateFor()); + context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).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(); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/ApiKeys/ListApiKeysHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/ApiKeys/ListApiKeysHandlerTests.cs new file mode 100644 index 0000000..1b2e4f1 --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/ApiKeys/ListApiKeysHandlerTests.cs @@ -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(); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor()); + 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(); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor([key1, key2])); + context.Sites.Returns(MockDbSetHelper.CreateFor([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); + } +} diff --git a/tests/Heimdall.Application.Tests/Handlers/ApiKeys/RevokeApiKeyHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/ApiKeys/RevokeApiKeyHandlerTests.cs new file mode 100644 index 0000000..bc3271f --- /dev/null +++ b/tests/Heimdall.Application.Tests/Handlers/ApiKeys/RevokeApiKeyHandlerTests.cs @@ -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(); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor([key])); + context.SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()).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(); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor()); + 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(); + context.ApiKeys.Returns(MockDbSetHelper.CreateFor([key])); + var handler = new RevokeApiKeyCommandHandler(context); + + var result = await handler.Handle(new RevokeApiKeyCommand(key.Id), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(400); + } +}