2026-07-16 20:53:56 +00:00
|
|
|
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>
|
|
|
|
|
{
|
2026-08-19 22:47:22 +02:00
|
|
|
private const string BearerPrefix = "Bearer ";
|
|
|
|
|
|
2026-07-16 20:53:56 +00:00
|
|
|
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()
|
|
|
|
|
{
|
2026-08-19 22:47:22 +02:00
|
|
|
var apiKey = ResolveApiKeyFromRequest();
|
2026-08-10 10:26:31 +02:00
|
|
|
|
2026-07-16 20:53:56 +00:00
|
|
|
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");
|
|
|
|
|
|
2026-08-19 22:47:22 +02:00
|
|
|
// Reject expired keys
|
|
|
|
|
if (apiKeyEntity.ExpiresAt.HasValue && apiKeyEntity.ExpiresAt.Value <= DateTime.UtcNow)
|
|
|
|
|
return AuthenticateResult.Fail("API key has expired");
|
|
|
|
|
|
2026-07-16 20:53:56 +00:00
|
|
|
// Hash the incoming key and constant-time compare
|
|
|
|
|
var incomingHash = SHA256.HashData(Encoding.UTF8.GetBytes(apiKey));
|
|
|
|
|
var storedHash = Convert.FromHexString(apiKeyEntity.KeyHash);
|
|
|
|
|
|
2026-08-19 22:47:22 +02:00
|
|
|
if (!CryptographicOperations.FixedTimeEquals(incomingHash, storedHash))
|
2026-07-16 20:53:56 +00:00
|
|
|
return AuthenticateResult.Fail("Invalid API key");
|
|
|
|
|
|
|
|
|
|
apiKeyEntity.MarkUsed();
|
2026-07-28 14:37:52 +00:00
|
|
|
// Persist LastUsedAt update
|
|
|
|
|
await db.SaveChangesAsync();
|
2026-07-16 20:53:56 +00:00
|
|
|
|
|
|
|
|
var claims = new List<Claim>
|
|
|
|
|
{
|
2026-08-19 22:47:22 +02:00
|
|
|
new Claim(ClaimTypes.NameIdentifier, apiKeyEntity.Id.ToString()),
|
|
|
|
|
new Claim("auth_method", "api_key"),
|
|
|
|
|
new Claim("api_key_prefix", prefix),
|
2026-07-16 20:53:56 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (apiKeyEntity.SiteId.HasValue)
|
|
|
|
|
claims.Add(new Claim("site_id", apiKeyEntity.SiteId.Value.ToString()));
|
|
|
|
|
|
2026-07-19 16:46:32 +00:00
|
|
|
// 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));
|
|
|
|
|
|
2026-07-16 20:53:56 +00:00
|
|
|
var identity = new ClaimsIdentity(claims, Scheme.Name);
|
|
|
|
|
var principal = new ClaimsPrincipal(identity);
|
|
|
|
|
|
|
|
|
|
return AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name));
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-19 22:47:22 +02:00
|
|
|
/// <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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-16 20:53:56 +00:00
|
|
|
/// <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);
|
|
|
|
|
}
|
|
|
|
|
}
|