Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Successful in 26m21s
Heimdall Gitea / Build and scan agent image (push) Successful in 6m32s
Heimdall Gitea / Build and scan server image (push) Successful in 8m59s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m37s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 26m10s
Heimdall Gitea / Publish signed main release (push) Canceled after 42m57s
Heimdall Gitea / CI policy (push) Failing after 2s
## Résumé Réduit les écritures de `LastUsedAt` à une mise à jour atomique EF Core par clé et par minute, tout en transmettant l’annulation HTTP aux requêtes de validation. Ajoute une vérification PostgreSQL concurrente et le workflow projet dans `skills/api-key-last-used-throttle/SKILL.md`. ## Tickets Refs #200, #201, #202, #203, #205. Les tickets restent ouverts jusqu’à la vérification post-déploiement GlitchTip requise par leurs critères; les événements examinés étaient en environnement Development et ne démontrent pas une régression en production. ## Vérifications observées - `dotnet test tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj --no-restore --filter FullyQualifiedName~ApiKeyLastUsedPostgresTests` — 1 réussi. - `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore --filter FullyQualifiedName~ApiKeyIdentityTests` — 1 réussi. - `python3 scripts/ci/check-efcore-usage.py` — réussi. - Compose jetable construit depuis le commit, projet isolé `heimdall-api-key-20261109100145-12450`, image `heimdall:heimdall-api-key-20261109100145-12450-acceptance`; `/healthz` et `/api/auth/bootstrap-status` HTTP 200. Après teardown, aucune ressource Compose du projet ne subsiste et le tag exact est absent. L’image PostgreSQL et les images amont sont conservées. ## Limite d’acceptation Le Compose vérifie le démarrage source et les routes HTTP de santé/bootstrap; le changement de persistance et la concurrence sont exercés par le test d’intégration PostgreSQL. Reviewed-on: #313 Co-authored-by: Arnaud Dartois <admin@tordais.cc>
147 lines
6.2 KiB
C#
147 lines
6.2 KiB
C#
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 const string BearerPrefix = "Bearer ";
|
|
|
|
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 = ResolveApiKeyFromRequest();
|
|
|
|
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 cancellationToken = Context.RequestAborted;
|
|
|
|
var apiKeyEntity = await db.ApiKeys
|
|
.FirstOrDefaultAsync(k => k.KeyPrefix == prefix && k.Enabled, cancellationToken);
|
|
|
|
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 (!CryptographicOperations.FixedTimeEquals(incomingHash, storedHash))
|
|
return AuthenticateResult.Fail("Invalid API key");
|
|
|
|
// A site key alone is not an agent identity. Resolve the registered binding
|
|
// by the full verified hash, and reject ambiguous or stale bindings.
|
|
var agents = await db.Agents.AsNoTracking()
|
|
.Where(a => a.ApiKeyHash == apiKeyEntity.KeyHash && a.SiteId == apiKeyEntity.SiteId)
|
|
.Select(a => a.Id).Take(2).ToListAsync(cancellationToken);
|
|
if (agents.Count != 1 || !apiKeyEntity.SiteId.HasValue)
|
|
return AuthenticateResult.Fail("API key is not bound to one active agent");
|
|
|
|
// LastUsedAt is an administrative activity indicator, not an audit log.
|
|
// Updating it on every request creates avoidable writes and contention
|
|
// when an agent sends concurrent heartbeats and telemetry. The predicate
|
|
// and update execute atomically in PostgreSQL, so concurrent requests
|
|
// collapse to at most one write per key per minute.
|
|
var now = DateTime.UtcNow;
|
|
var updateBefore = now.AddMinutes(-1);
|
|
await db.ApiKeys
|
|
.Where(key => key.Id == apiKeyEntity.Id &&
|
|
(key.LastUsedAt == null || key.LastUsedAt <= updateBefore))
|
|
.ExecuteUpdateAsync(setters => setters.SetProperty(key => key.LastUsedAt, now), cancellationToken)
|
|
.ConfigureAwait(false);
|
|
|
|
var claims = new List<Claim>
|
|
{
|
|
new Claim(ClaimTypes.NameIdentifier, apiKeyEntity.Id.ToString()),
|
|
new Claim("auth_method", "api_key"),
|
|
new Claim("agent_id", agents[0].ToString()),
|
|
new Claim("api_key_prefix", prefix),
|
|
};
|
|
|
|
if (apiKeyEntity.SiteId.HasValue)
|
|
claims.Add(new Claim("site_id", apiKeyEntity.SiteId.Value.ToString()));
|
|
|
|
// API keys are used by camera agents — assign the permissions they need
|
|
// to operate (post events, read cameras/sites, stream live video).
|
|
// This maps to the Supervisor role minus Person permissions.
|
|
claims.Add(new Claim("permission", AppPermissions.CameraWrite));
|
|
claims.Add(new Claim("permission", AppPermissions.CameraRead));
|
|
claims.Add(new Claim("permission", AppPermissions.CameraLive));
|
|
claims.Add(new Claim("permission", AppPermissions.SiteRead));
|
|
claims.Add(new Claim("permission", AppPermissions.EventRead));
|
|
|
|
var identity = new ClaimsIdentity(claims, Scheme.Name);
|
|
var principal = new ClaimsPrincipal(identity);
|
|
|
|
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()
|
|
{
|
|
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);
|
|
}
|
|
}
|