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().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(); Identity.IsInRoleAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(call => Task.FromResult(Db.UserRoles.Any(userRole => userRole.UserId == call.Arg() && Db.Roles.Any(role => role.Id == userRole.RoleId && role.Name == call.ArgAt(1))))); Identity.GetSessionRecordAsync(Arg.Any(), Arg.Any()) .Returns(call => { var user = Db.Users.AsNoTracking().SingleOrDefault(candidate => candidate.Id == call.Arg()); 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().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 { 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 { new(ClaimTypes.NameIdentifier, id.ToString()), new("auth_method", "api_key") } : new List { 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(); } }