feat(mvp): implement MVP multi-site platform
Complete MVP implementation (Étape 1) covering: - Domain: primitives (Entity<TId>, ValueObject), 10 entities, 6 enums - EF Core: AppDbContext + Identity, 8 EntityTypeConfigurations, audit/soft-delete interceptors, initial migration - Application: service interfaces, DTOs, FluentValidation, ServiceResult pattern - Security: Identity + JWT + API Key multi-auth, role-based permissions, constant-time key validation - API: Auth/Sites/Agents controllers with explicit auth scheme policies - Workers: Hangfire PostgreSQL setup with schema isolation, HeartbeatMonitorJob - Agent: registration service + 30s heartbeat loop - Docker: multi-stage Dockerfiles for central + agent, docker-compose.yml - CI/CD: GitHub Actions pipeline with build+test and Docker build - Tests: 13 domain tests (Site, Agent, Camera entities) Architecture decisions per deliberation council: - API Key via AuthenticationHandler<T> (not middleware) - Explicit [Authorize(AuthenticationSchemes)] on all endpoints - Event/Recording/Person/Vehicle deferred from initial migration - Hangfire compatible with .NET 10 (v1.8.17)
This commit is contained in:
1 parent
ad78346ac4
commit
b217c932e8
78 files changed
+5359
-11
No files matched your search
@@ -0,0 +1,91 @@
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Heimdall.Infrastructure.Security;
|
||||
|
||||
public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions { }
|
||||
|
||||
/// <summary>
|
||||
/// AuthenticationHandler for API Key authentication.
|
||||
/// Validates SHA256-hashed API keys using constant-time comparison.
|
||||
/// Integrates with ASP.NET Core's standard auth pipeline.
|
||||
/// </summary>
|
||||
public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
|
||||
public ApiKeyAuthenticationHandler(
|
||||
IOptionsMonitor<ApiKeyAuthenticationOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
IServiceProvider serviceProvider)
|
||||
: base(options, logger, encoder)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
}
|
||||
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var apiKey = Request.Headers.Authorization.FirstOrDefault()
|
||||
?.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase)
|
||||
?? Request.Headers["X-API-Key"].FirstOrDefault()
|
||||
?? Request.Query["apiKey"].FirstOrDefault();
|
||||
|
||||
if (string.IsNullOrEmpty(apiKey) || apiKey.Length < 8)
|
||||
return AuthenticateResult.NoResult();
|
||||
|
||||
var prefix = apiKey[..8];
|
||||
|
||||
using var scope = _serviceProvider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
|
||||
var apiKeyEntity = await db.ApiKeys
|
||||
.FirstOrDefaultAsync(k => k.KeyPrefix == prefix && k.Enabled);
|
||||
|
||||
if (apiKeyEntity is null)
|
||||
return AuthenticateResult.Fail("Invalid API key");
|
||||
|
||||
// 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))
|
||||
return AuthenticateResult.Fail("Invalid API key");
|
||||
|
||||
apiKeyEntity.MarkUsed();
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, apiKeyEntity.Id.ToString()),
|
||||
new("auth_method", "api_key"),
|
||||
new("api_key_prefix", prefix),
|
||||
};
|
||||
|
||||
if (apiKeyEntity.SiteId.HasValue)
|
||||
claims.Add(new Claim("site_id", apiKeyEntity.SiteId.Value.ToString()));
|
||||
|
||||
var identity = new ClaimsIdentity(claims, Scheme.Name);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
|
||||
return AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name));
|
||||
}
|
||||
|
||||
/// <summary>Generate a new API key and return (plainKey, prefix, hash).</summary>
|
||||
public 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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user