88 lines
3.2 KiB
C#
88 lines
3.2 KiB
C#
using ManagerService.Controllers;
|
|
using ManagerService.Data;
|
|
using ManagerService.Services;
|
|
using static ManagerService.Services.ApiKeyDatabaseService;
|
|
using ManagerService.Tests.Infrastructure;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Xunit;
|
|
|
|
namespace ManagerService.Tests.Controllers
|
|
{
|
|
public class ApiKeyControllerTests
|
|
{
|
|
private static ApiKeyController BuildController(MyInfoMateDbContext db, string instanceId = "inst-test")
|
|
{
|
|
var service = new ApiKeyDatabaseService(db);
|
|
var controller = new ApiKeyController(service);
|
|
FakeUser.SetUser(controller, FakeUser.Create("Manager.instanceadmin", instanceId));
|
|
return controller;
|
|
}
|
|
|
|
[Fact]
|
|
public async Task GetApiKeys_ReturnsKeysForInstance()
|
|
{
|
|
using var db = DbContextFactory.Create();
|
|
db.ApiKeys.AddRange(
|
|
new ApiKey { Id = "k1", InstanceId = "inst-test", Name = "Key1", KeyHash = "h1", IsActive = true, AppType = ApiKeyAppType.VisitApp },
|
|
new ApiKey { Id = "k2", InstanceId = "other-inst", Name = "Key2", KeyHash = "h2", IsActive = true, AppType = ApiKeyAppType.VisitApp }
|
|
);
|
|
db.SaveChanges();
|
|
|
|
var result = await BuildController(db).GetApiKeys();
|
|
|
|
var ok = Assert.IsType<OkObjectResult>(result);
|
|
var keys = Assert.IsAssignableFrom<System.Collections.Generic.IEnumerable<ApiKeyDTO>>(ok.Value);
|
|
Assert.Single(keys);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task CreateApiKey_ValidRequest_ReturnsPlainKey()
|
|
{
|
|
using var db = DbContextFactory.Create();
|
|
|
|
var result = await BuildController(db).CreateApiKey(new CreateApiKeyRequest
|
|
{
|
|
Name = "My Key",
|
|
AppType = ApiKeyAppType.VisitApp
|
|
});
|
|
|
|
var ok = Assert.IsType<OkObjectResult>(result);
|
|
Assert.NotNull(ok.Value);
|
|
// La clé plain text doit commencer par "ak_"
|
|
var keyProp = ok.Value!.GetType().GetProperty("key");
|
|
Assert.NotNull(keyProp);
|
|
var plainKey = keyProp!.GetValue(ok.Value) as string;
|
|
Assert.StartsWith("ak_", plainKey);
|
|
|
|
// La clé est stockée hachée, pas en clair
|
|
Assert.Equal(1, db.ApiKeys.Count());
|
|
Assert.Null(db.ApiKeys.First().Key);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RevokeApiKey_ExistingKey_Returns204()
|
|
{
|
|
using var db = DbContextFactory.Create();
|
|
db.ApiKeys.Add(new ApiKey { Id = "k1", InstanceId = "inst-test", Name = "Key1", KeyHash = "h1", IsActive = true, AppType = ApiKeyAppType.VisitApp });
|
|
db.SaveChanges();
|
|
|
|
var result = await BuildController(db).RevokeApiKey("k1");
|
|
|
|
Assert.IsType<NoContentResult>(result);
|
|
Assert.Equal(0, db.ApiKeys.Count(k => k.IsActive));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RevokeApiKey_UnknownKey_Returns404()
|
|
{
|
|
using var db = DbContextFactory.Create();
|
|
|
|
var result = await BuildController(db).RevokeApiKey("unknown");
|
|
|
|
Assert.IsType<NotFoundResult>(result);
|
|
}
|
|
}
|
|
}
|