using NTP.Application.Abstractions; using NTP.Application.Access; namespace NTP.Tests; public class PermissionTests { // the permission cache is static (shared by all requests): every test starts from an empty one public PermissionTests() => PermissionService.ResetCache(); private sealed class FakeUser(string role, bool authenticated = true) : ICurrentUser { public bool IsAuthenticated => authenticated; public long Id => 1; public string UserId => "T"; public string Name => "t"; public string RoleCode => role; public string RoleName => role; public string Domain => "GN"; public long? LocationId => null; public string LocationName => ""; public long? StkId => null; public long? CompId => null; public long? CompanyId => null; public string CompanyName => ""; public string CompanyCode => ""; public string EmpNo => ""; public string Lang => "AR"; public bool IsStaff => false; public bool IsInRole(string roleCode) => string.Equals(role, roleCode, StringComparison.OrdinalIgnoreCase); public bool IsInAnyRole(params string[] roleCodes) => roleCodes.Any(IsInRole); } /// Rows of a role. The DISABLED pseudo role is answered by instead. private sealed class FakeRepo(Func?> answer, IReadOnlyList? disabled = null) : IPermissionRepository { public int Calls; // lookups of real roles only public readonly List Asked = []; public Task?> GetAllowedAsync(string roleCode, CancellationToken ct = default) { Asked.Add(roleCode); if (roleCode == PermissionService.DisabledRole) return Task.FromResult(disabled); Calls++; return Task.FromResult(answer(roleCode)); } } // The service caches per role in a static dictionary; each test uses its own role code so tests do not interfere. private static PermissionService Svc(string role, FakeRepo repo, bool authenticated = true) => new(repo, new FakeUser(role, authenticated)); [Fact] public async Task Super_user_gets_everything_without_a_role_lookup() { var repo = new FakeRepo(_ => throw new InvalidOperationException("must not be called")); var svc = Svc("SU", repo); var dto = await svc.GetForCurrentUserAsync(); Assert.True(dto.All); Assert.Empty(dto.Allowed); Assert.True(await svc.IsAllowedAsync("grains.anything.at.all")); Assert.Equal(0, repo.Calls); // no role rows read for SU Assert.Equal([PermissionService.DisabledRole], repo.Asked.Distinct()); // only the disabled list is consulted } [Fact] public async Task Missing_table_falls_back_to_the_sheet_defaults() { var svc = Svc("GOO", new FakeRepo(_ => null)); var dto = await svc.GetForCurrentUserAsync(); Assert.False(dto.All); Assert.Contains(PermissionKeys.OrdersList, dto.Allowed); // الطلبيات: GTO,GOO Assert.Contains(PermissionKeys.OrdersCompanyDest, dto.Allowed); // وجهات الشركات: GOO Assert.Contains(PermissionKeys.PermitsDestinations, dto.Allowed); // تحديد وجهة ارسالية تموين: GOO Assert.DoesNotContain(PermissionKeys.PermitsWeighbridge, dto.Allowed);// شاشة القبان: GTO,GGO only Assert.DoesNotContain(PermissionKeys.OrdersWeights, dto.Allowed); // تثبيت أوزان التحميل: GTO only } [Fact] public async Task New_order_action_is_allowed_for_gto_only_by_default() { Assert.False(await Svc("GOO", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.OrdersCreate)); Assert.True(await Svc("GTO", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.OrdersCreate)); Assert.False(await Svc("GGO", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.OrdersCreate)); Assert.False(await Svc("GPO", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.OrdersCreate)); } [Fact] public async Task Registering_trucks_trailers_and_drivers_is_granted_by_database_rows_only() { foreach (var role in new[] { "GTO", "GOO", "GPO", "GGO" }) { var none = Svc(role, new FakeRepo(_ => null)); // table missing: built-in defaults grant none of the create keys Assert.False(await none.IsAllowedAsync(PermissionKeys.RegistryTrucksCreate)); Assert.False(await none.IsAllowedAsync(PermissionKeys.RegistryTrailersCreate)); Assert.False(await none.IsAllowedAsync(PermissionKeys.RegistryDriversCreate)); Assert.False(await none.IsAllowedAsync(PermissionKeys.RegistryTrucksEdit)); // edit rights too: database rows only Assert.False(await none.IsAllowedAsync(PermissionKeys.RegistryTrailersEdit)); } var granted = Svc("CREATE-ROLE", new FakeRepo(_ => new[] { PermissionKeys.RegistryTrucksCreate })); Assert.True(await granted.IsAllowedAsync(PermissionKeys.RegistryTrucksCreate)); Assert.False(await granted.IsAllowedAsync(PermissionKeys.RegistryDriversCreate)); Assert.True(await Svc("SU", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.RegistryDriversCreate)); } [Fact] public async Task Registering_a_turn_is_granted_by_database_rows_only() { foreach (var role in new[] { "GTO", "GOO", "GPO", "GGO" }) Assert.False(await Svc(role, new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.PermitsCreate)); Assert.True(await Svc("GOO-TURN", new FakeRepo(_ => new[] { PermissionKeys.PermitsCreate })).IsAllowedAsync(PermissionKeys.PermitsCreate)); Assert.True(await Svc("SU", new FakeRepo(_ => null)).IsAllowedAsync(PermissionKeys.PermitsCreate)); } [Fact] public async Task A_resource_with_a_DISABLED_row_is_off_for_everybody_including_su() { IReadOnlyList? Rows(string role) => new[] { PermissionKeys.PermitsAbsence, PermissionKeys.PermitsList }; var off = new[] { PermissionKeys.PermitsAbsence, PermissionKeys.PermitsActivation }; var su = Svc("SU", new FakeRepo(Rows, off)); Assert.False(await su.IsAllowedAsync(PermissionKeys.PermitsAbsence)); // even SU Assert.False(await su.IsAllowedAsync(PermissionKeys.PermitsActivation)); Assert.True(await su.IsAllowedAsync(PermissionKeys.OrdersList)); // everything else stays open for SU var dto = await su.GetForCurrentUserAsync(); Assert.True(dto.All); Assert.Contains(PermissionKeys.PermitsAbsence, dto.Denied); Assert.Contains(PermissionKeys.PermitsActivation, dto.Denied); var gto = Svc("GTO-DISABLED-TEST", new FakeRepo(Rows, off)); Assert.False(await gto.IsAllowedAsync(PermissionKeys.PermitsAbsence)); // granted by its own row, still disabled Assert.True(await gto.IsAllowedAsync(PermissionKeys.PermitsList)); var gtoDto = await gto.GetForCurrentUserAsync(); Assert.DoesNotContain(PermissionKeys.PermitsAbsence, gtoDto.Allowed); Assert.Contains(PermissionKeys.PermitsList, gtoDto.Allowed); } [Fact] public async Task Nothing_is_disabled_while_the_permission_table_is_missing() { var su = Svc("SU", new FakeRepo(_ => null)); Assert.True(await su.IsAllowedAsync(PermissionKeys.PermitsAbsence)); Assert.Empty((await su.GetForCurrentUserAsync()).Denied); } [Fact] public async Task Screens_not_in_the_sheet_are_hidden_from_non_super_roles() { var svc = Svc("GGO", new FakeRepo(_ => null)); Assert.True(await svc.IsAllowedAsync(PermissionKeys.PermitsWeighbridge)); Assert.False(await svc.IsAllowedAsync(PermissionKeys.OrdersQuotas)); // not in the sheet for anyone Assert.False(await svc.IsAllowedAsync(PermissionKeys.OrdersBilling)); } [Fact] public async Task Database_rows_replace_the_defaults_once_the_table_exists() { var svc = Svc("GPO", new FakeRepo(_ => new[] { "grains.orders.quotas" })); Assert.True(await svc.IsAllowedAsync("grains.orders.quotas")); Assert.False(await svc.IsAllowedAsync(PermissionKeys.PermitsList)); // in the defaults for GPO, but not in the table } [Fact] public async Task Role_code_matching_ignores_case() { var svc = Svc("gto", new FakeRepo(_ => null)); Assert.True(await svc.IsAllowedAsync(PermissionKeys.PermitsActivation)); // GTO only } [Fact] public async Task Anonymous_callers_are_never_allowed() { var svc = Svc("GTO-ANON", new FakeRepo(_ => new[] { PermissionKeys.PermitsList }), authenticated: false); Assert.False(await svc.IsAllowedAsync(PermissionKeys.PermitsList)); } [Fact] public async Task Result_is_cached_per_role() { var repo = new FakeRepo(_ => new[] { "k" }); var svc = Svc("CACHEROLE", repo); await svc.IsAllowedAsync("k"); await svc.IsAllowedAsync("k"); Assert.Equal(1, repo.Calls); } [Fact] public void Every_default_resource_has_at_least_one_role_and_no_super_user_row() { foreach (var (key, roles) in PermissionDefaults.RolesByResource) { Assert.NotEmpty(roles); Assert.DoesNotContain("SU", roles); // SU is implicit, never stored Assert.StartsWith("grains.", key); } } }