Files
arnaud.dartois 89c4c43922
Heimdall Gitea / Detect CI scope (push) Successful in 7s
Heimdall Gitea / Build and tests (push) Successful in 14m48s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 4m27s
Heimdall Gitea / Build and scan agent image (push) Successful in 15m42s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m27s
Heimdall Gitea / CI policy (push) Successful in 2s
fix(identity): harden user lifecycle and permissions (#136)
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-04 13:33:30 +01:00

107 lines
4.9 KiB
C#

using System.Security.Claims;
using Heimdall.Api.Security;
using Heimdall.Application.Auth.Services;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Security;
using Heimdall.Infrastructure.Services;
using Microsoft.Data.Sqlite;
using Microsoft.AspNetCore.Identity;
using NSubstitute;
using Microsoft.EntityFrameworkCore;
using Heimdall.Infrastructure.Identity;
namespace Heimdall.Web.Tests.Security;
public sealed class AccessFixture : IDisposable
{
private readonly SqliteConnection _connection = new("DataSource=:memory:");
public AppDbContext Db { get; }
public CameraAccessService Cameras { get; }
public ResourceAccess Access { get; }
public IIdentityAccountService Identity { get; }
public Site A { get; } = new("A");
public Site B { get; } = new("B");
public Camera A1 { get; }
public Camera A2 { get; }
public Camera B1 { get; }
public Agent AgentA { get; }
public Agent PeerA { get; }
public Agent AgentB { get; }
public ApiKey KeyA { get; }
public Group Group { get; } = new("Operators", null);
public AccessFixture()
{
_connection.Open();
_connection.CreateFunction("NOW", () => DateTime.UtcNow.ToString("O", System.Globalization.CultureInfo.InvariantCulture));
Db = new(new DbContextOptionsBuilder<AppDbContext>().UseSqlite(_connection).Options, new AuditInterceptor());
Db.Database.EnsureCreated();
AgentA = new(A.Id, "a", "a", "1");
PeerA = new(A.Id, "peer", "peer", "1");
AgentB = new(B.Id, "b", "b", "1");
var (_, prefix, hash) = ApiKeyAuthenticationHandler.GenerateApiKey();
AgentA.Register(hash, prefix);
KeyA = new(hash, prefix, A.Id);
A1 = new(A.Id, "a1"); A1.AssignAgent(AgentA.Id);
A2 = new(A.Id, "a2"); A2.AssignAgent(PeerA.Id);
B1 = new(B.Id, "b1"); B1.AssignAgent(AgentB.Id);
Db.AddRange(A, B, AgentA, PeerA, AgentB, KeyA, A1, A2, B1, Group);
Db.SaveChanges();
Cameras = new CameraAccessService(Db, Db);
Identity = Substitute.For<IIdentityAccountService>();
Identity.IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(call => Task.FromResult(Db.UserRoles.Any(userRole => userRole.UserId == call.Arg<Guid>()
&& Db.Roles.Any(role => role.Id == userRole.RoleId && role.Name == call.ArgAt<string>(1)))));
Identity.GetSessionRecordAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
.Returns(call =>
{
var user = Db.Users.AsNoTracking().SingleOrDefault(candidate => candidate.Id == call.Arg<Guid>());
return Task.FromResult(user is null ? null : new UserSessionRecord(user.SecurityStamp, user.LockoutEnabled, user.LockoutEnd, user.EmailConfirmed));
});
Access = new(Db, Cameras, Identity);
}
public AppDbContext CreateDbContext() => new(
new DbContextOptionsBuilder<AppDbContext>().UseSqlite(_connection).Options, new AuditInterceptor());
public IdentityAppUser User(string role, string grant)
{
var user = new IdentityAppUser { Id = Guid.NewGuid(), UserName = Guid.NewGuid().ToString(), SecurityStamp = "fixture-stamp" };
var entity = Db.Roles.FirstOrDefault(r => r.Name == role) ?? new IdentityAppRole { Id = Guid.NewGuid(), Name = role, NormalizedName = role.ToUpperInvariant() };
if (Db.Entry(entity).State == EntityState.Detached) Db.Roles.Add(entity);
Db.Users.Add(user);
Db.UserRoles.Add(new IdentityUserRole<Guid> { UserId = user.Id, RoleId = entity.Id });
switch (grant)
{
case "direct": Db.UserCameraAccesses.Add(new(user.Id, A.Id, A1.Id)); break;
case "legacy": Db.UserCameras.Add(new(user.Id, A1.Id)); break;
case "site": Db.UserSites.Add(new(user.Id, A.Id)); break;
case "group":
Db.UserGroups.Add(new(user.Id, Group.Id));
if (!Db.GroupCameraAccesses.Any(g => g.GroupId == Group.Id && g.CameraId == A1.Id))
Db.GroupCameraAccesses.Add(new(Group.Id, A1.Id));
break;
}
Db.SaveChanges();
return user;
}
public static ClaimsPrincipal Principal(Guid id, bool agent = false)
{
var claims = agent
? new List<Claim> { new(ClaimTypes.NameIdentifier, id.ToString()), new("auth_method", "api_key") }
: new List<Claim>
{
new(ClaimTypes.NameIdentifier, id.ToString()),
new(AccountSessionPolicy.StampClaim, "fixture-stamp"),
new(AccountSessionPolicy.StartedClaim, DateTime.UtcNow.ToString("O", System.Globalization.CultureInfo.InvariantCulture))
};
return new ClaimsPrincipal(new ClaimsIdentity(claims, "test"));
}
public void Dispose() { Db.Dispose(); _connection.Dispose(); }
}