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
@@ -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()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user