Files
Heimdall/tests/Heimdall.Web.Tests/Security/ApiKeyIdentityTests.cs
T

43 lines
2.1 KiB
C#

using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
namespace Heimdall.Web.Tests.Security;
public sealed class ApiKeyIdentityTests
{
[Fact]
public async Task Real_handler_emits_server_resolved_agent_and_rejects_unbound_expired_deleted_keys()
{
using var f = new AccessFixture();
var (plain, prefix, hash) = ApiKeyAuthenticationHandler.GenerateApiKey();
var key = new ApiKey(hash, prefix, f.A.Id);
f.Db.ApiKeys.Add(key); await f.Db.SaveChangesAsync();
var services = new ServiceCollection();
services.AddLogging(); services.AddSingleton(f.Db);
services.AddAuthentication("ApiKey").AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>("ApiKey", _ => { });
using var provider = services.BuildServiceProvider();
async Task<AuthenticateResult> Authenticate(string input)
{
using var scope = provider.CreateScope();
var context = new DefaultHttpContext { RequestServices = scope.ServiceProvider };
context.Request.Headers["X-API-Key"] = input;
return await context.AuthenticateAsync("ApiKey");
}
(await Authenticate(plain)).Succeeded.ShouldBeFalse();
f.PeerA.Register(hash, prefix); await f.Db.SaveChangesAsync();
var success = await Authenticate(plain);
success.Succeeded.ShouldBeTrue();
success.Principal!.FindFirst("agent_id")!.Value.ShouldBe(f.PeerA.Id.ToString());
success.Principal.FindFirst("site_id")!.Value.ShouldBe(f.A.Id.ToString());
(await Authenticate(plain[..^1] + (plain[^1] == '0' ? '1' : '0'))).Succeeded.ShouldBeFalse();
key.SetExpiry(DateTime.UtcNow.AddMinutes(-1)); await f.Db.SaveChangesAsync();
(await Authenticate(plain)).Succeeded.ShouldBeFalse();
key.SetExpiry(DateTime.UtcNow.AddMinutes(1)); f.PeerA.SoftDelete(); await f.Db.SaveChangesAsync();
(await Authenticate(plain)).Succeeded.ShouldBeFalse();
}
}