|
| 1 | +using System.Security.Claims; |
| 2 | +using FluentAssertions; |
| 3 | +using Microsoft.AspNetCore.Authorization; |
| 4 | +using Microsoft.Extensions.Options; |
| 5 | +using SharedKernel.Authentication.BackOfficeIdentity; |
| 6 | +using Xunit; |
| 7 | + |
| 8 | +namespace Account.Tests.BackOffice; |
| 9 | + |
| 10 | +// Verifies the optional BackOffice:AdminsGroupId capability gate. When unset, no one is admin. |
| 11 | +// When set, the principal must carry a 'groups' claim matching the configured value. |
| 12 | +public sealed class BackOfficeAdminRequirementTests |
| 13 | +{ |
| 14 | + [Fact] |
| 15 | + public async Task HandleRequirement_WhenAdminsGroupIdUnset_ShouldFail() |
| 16 | + { |
| 17 | + var handler = CreateHandler(null); |
| 18 | + var requirement = new BackOfficeAdminRequirement(); |
| 19 | + var context = CreateAuthorizationContext(requirement, ["BackOfficeAdmins"]); |
| 20 | + |
| 21 | + await handler.HandleAsync(context); |
| 22 | + |
| 23 | + context.HasSucceeded.Should().BeFalse(); |
| 24 | + } |
| 25 | + |
| 26 | + [Fact] |
| 27 | + public async Task HandleRequirement_WhenPrincipalCarriesMatchingGroup_ShouldSucceed() |
| 28 | + { |
| 29 | + var handler = CreateHandler("BackOfficeAdmins"); |
| 30 | + var requirement = new BackOfficeAdminRequirement(); |
| 31 | + var context = CreateAuthorizationContext(requirement, ["BackOfficeAdmins"]); |
| 32 | + |
| 33 | + await handler.HandleAsync(context); |
| 34 | + |
| 35 | + context.HasSucceeded.Should().BeTrue(); |
| 36 | + } |
| 37 | + |
| 38 | + [Fact] |
| 39 | + public async Task HandleRequirement_WhenPrincipalLacksMatchingGroup_ShouldFail() |
| 40 | + { |
| 41 | + var handler = CreateHandler("BackOfficeAdmins"); |
| 42 | + var requirement = new BackOfficeAdminRequirement(); |
| 43 | + var context = CreateAuthorizationContext(requirement, []); |
| 44 | + |
| 45 | + await handler.HandleAsync(context); |
| 46 | + |
| 47 | + context.HasSucceeded.Should().BeFalse(); |
| 48 | + } |
| 49 | + |
| 50 | + private static BackOfficeAdminAuthorizationHandler CreateHandler(string? adminsGroupId) |
| 51 | + { |
| 52 | + var options = Options.Create(new BackOfficeHostOptions { Host = "back-office.test.localhost", AdminsGroupId = adminsGroupId }); |
| 53 | + return new BackOfficeAdminAuthorizationHandler(options); |
| 54 | + } |
| 55 | + |
| 56 | + private static AuthorizationHandlerContext CreateAuthorizationContext(IAuthorizationRequirement requirement, string[] groups) |
| 57 | + { |
| 58 | + var claims = groups.Select(group => new Claim(BackOfficeIdentityDefaults.GroupsClaimType, group)); |
| 59 | + var identity = new ClaimsIdentity(claims, BackOfficeIdentityDefaults.AuthenticationScheme); |
| 60 | + var principal = new ClaimsPrincipal(identity); |
| 61 | + return new AuthorizationHandlerContext([requirement], principal, null); |
| 62 | + } |
| 63 | +} |
0 commit comments