|
| 1 | +using Finbuckle.MultiTenant; |
| 2 | +using Finbuckle.MultiTenant.Abstractions; |
| 3 | +using FSH.Framework.Shared.Multitenancy; |
| 4 | +using FSH.Modules.Identity.Contracts.Authorization; |
| 5 | +using FSH.Modules.Identity.Domain; |
| 6 | +using Integration.Tests.Infrastructure; |
| 7 | +using Integration.Tests.Infrastructure.Extensions; |
| 8 | +using Microsoft.AspNetCore.Identity; |
| 9 | + |
| 10 | +namespace Integration.Tests.Tests.Groups; |
| 11 | + |
| 12 | +/// <summary> |
| 13 | +/// Proves group-derived roles confer PERMISSIONS, not just JWT role claims. |
| 14 | +/// <c>IdentityService.AddRoleClaimsAsync</c> unions direct roles with |
| 15 | +/// <c>IGroupRoleService.GetUserGroupRolesAsync</c> when minting tokens, and every group |
| 16 | +/// mutation handler invalidates the permission cache — so <c>UserPermissionService</c> |
| 17 | +/// must resolve the same union, or a user whose only role comes via a group fails every |
| 18 | +/// <c>.RequirePermission()</c> gate despite their JWT showing the role. |
| 19 | +/// </summary> |
| 20 | +[Collection(FshCollectionDefinition.Name)] |
| 21 | +public sealed class GroupRolePermissionTests |
| 22 | +{ |
| 23 | + private const string ProbePermission = IdentityPermissions.Groups.Create; |
| 24 | + |
| 25 | + private readonly FshWebApplicationFactory _factory; |
| 26 | + private readonly AuthHelper _auth; |
| 27 | + |
| 28 | + public GroupRolePermissionTests(FshWebApplicationFactory factory) |
| 29 | + { |
| 30 | + _factory = factory; |
| 31 | + _auth = new AuthHelper(factory); |
| 32 | + } |
| 33 | + |
| 34 | + [Fact] |
| 35 | + public async Task GetOwnPermissions_Should_IncludeGroupRolePermissions_When_UserHasNoDirectRoles() |
| 36 | + { |
| 37 | + // Arrange — custom role with the probe permission, attached to a GROUP (never to the user). |
| 38 | + using var adminClient = await _auth.CreateRootAdminClientAsync(); |
| 39 | + var uniqueId = Guid.NewGuid().ToString("N")[..8]; |
| 40 | + |
| 41 | + var role = await CreateRoleWithPermissionAsync(adminClient, $"GrpPermRole-{uniqueId}", ProbePermission); |
| 42 | + var groupId = await CreateGroupWithRoleAsync(adminClient, $"PermGroup-{uniqueId}", role.Id); |
| 43 | + |
| 44 | + var (email, password, userId) = await CreateActiveUserAsync($"grpperm-{uniqueId}"); |
| 45 | + await AddUserToGroupAsync(adminClient, groupId, userId); |
| 46 | + |
| 47 | + using var userClient = await _auth.CreateAuthenticatedClientAsync(email, password); |
| 48 | + |
| 49 | + // Act — read the user's own effective permissions (auth-only endpoint, backed by UserPermissionService). |
| 50 | + var response = await userClient.GetAsync($"{TestConstants.IdentityBasePath}/permissions"); |
| 51 | + response.StatusCode.ShouldBe(HttpStatusCode.OK, |
| 52 | + $"Get current-user permissions failed: {await response.Content.ReadAsStringAsync()}"); |
| 53 | + var permissions = await response.DeserializeAsync<List<string>>(); |
| 54 | + |
| 55 | + // Assert — the group-derived role's permission must be in the effective set. |
| 56 | + permissions.ShouldContain(ProbePermission, |
| 57 | + "UserPermissionService only resolves DIRECT role assignments: a role granted via group membership " + |
| 58 | + "confers no permissions, even though the JWT carries the role claim."); |
| 59 | + } |
| 60 | + |
| 61 | + [Fact] |
| 62 | + public async Task PermissionGate_Should_Open_When_UsersOnlyRoleComesViaGroup() |
| 63 | + { |
| 64 | + // Arrange — same setup, but probe through a real .RequirePermission() gate |
| 65 | + // (POST /groups requires Groups.Create), exercising the authorization handler path. |
| 66 | + using var adminClient = await _auth.CreateRootAdminClientAsync(); |
| 67 | + var uniqueId = Guid.NewGuid().ToString("N")[..8]; |
| 68 | + |
| 69 | + var role = await CreateRoleWithPermissionAsync(adminClient, $"GrpGateRole-{uniqueId}", ProbePermission); |
| 70 | + var groupId = await CreateGroupWithRoleAsync(adminClient, $"GateGroup-{uniqueId}", role.Id); |
| 71 | + |
| 72 | + var (email, password, userId) = await CreateActiveUserAsync($"grpgate-{uniqueId}"); |
| 73 | + await AddUserToGroupAsync(adminClient, groupId, userId); |
| 74 | + |
| 75 | + using var userClient = await _auth.CreateAuthenticatedClientAsync(email, password); |
| 76 | + |
| 77 | + // Act — hit the gated endpoint with the group-conferred permission. |
| 78 | + var response = await userClient.PostAsJsonAsync($"{TestConstants.IdentityBasePath}/groups", new |
| 79 | + { |
| 80 | + name = $"grp-by-member-{uniqueId}", |
| 81 | + description = "created via group-derived permission", |
| 82 | + isDefault = false, |
| 83 | + roleIds = new List<string>() |
| 84 | + }); |
| 85 | + |
| 86 | + // Assert — the gate must honor the group-derived role. |
| 87 | + response.StatusCode.ShouldNotBe(HttpStatusCode.Forbidden, |
| 88 | + "RequiredPermissionAuthorizationHandler denied a user whose group membership grants a role holding the required permission."); |
| 89 | + response.StatusCode.ShouldBe(HttpStatusCode.Created); |
| 90 | + } |
| 91 | + |
| 92 | + // ─── helpers ───────────────────────────────────────────────────── |
| 93 | + |
| 94 | + private static async Task<RoleDto> CreateRoleWithPermissionAsync(HttpClient adminClient, string name, string permission) |
| 95 | + { |
| 96 | + var createResponse = await adminClient.PostAsJsonAsync($"{TestConstants.IdentityBasePath}/roles", new |
| 97 | + { |
| 98 | + id = string.Empty, |
| 99 | + name, |
| 100 | + description = "group-role permission test role" |
| 101 | + }); |
| 102 | + var role = await createResponse.DeserializeAsync<RoleDto>(); |
| 103 | + |
| 104 | + var permResponse = await adminClient.PutAsJsonAsync( |
| 105 | + $"{TestConstants.IdentityBasePath}/{role.Id}/permissions", new |
| 106 | + { |
| 107 | + roleId = role.Id, |
| 108 | + permissions = new[] { permission } |
| 109 | + }); |
| 110 | + permResponse.StatusCode.ShouldBe(HttpStatusCode.OK, |
| 111 | + $"Set role permissions failed: {await permResponse.Content.ReadAsStringAsync()}"); |
| 112 | + |
| 113 | + return role; |
| 114 | + } |
| 115 | + |
| 116 | + private static async Task<Guid> CreateGroupWithRoleAsync(HttpClient adminClient, string name, string roleId) |
| 117 | + { |
| 118 | + var response = await adminClient.PostAsJsonAsync($"{TestConstants.IdentityBasePath}/groups", new |
| 119 | + { |
| 120 | + name, |
| 121 | + description = "group-role permission test group", |
| 122 | + isDefault = false, |
| 123 | + roleIds = new List<string> { roleId } |
| 124 | + }); |
| 125 | + response.StatusCode.ShouldBe(HttpStatusCode.Created, |
| 126 | + $"Create group failed: {await response.Content.ReadAsStringAsync()}"); |
| 127 | + var group = await response.DeserializeAsync<GroupDto>(); |
| 128 | + return group.Id; |
| 129 | + } |
| 130 | + |
| 131 | + private static async Task AddUserToGroupAsync(HttpClient adminClient, Guid groupId, string userId) |
| 132 | + { |
| 133 | + var response = await adminClient.PostAsJsonAsync( |
| 134 | + $"{TestConstants.IdentityBasePath}/groups/{groupId}/members", |
| 135 | + new { userIds = new[] { userId } }); |
| 136 | + response.StatusCode.ShouldBe(HttpStatusCode.OK, |
| 137 | + $"Add user to group failed: {await response.Content.ReadAsStringAsync()}"); |
| 138 | + } |
| 139 | + |
| 140 | + /// <summary> |
| 141 | + /// Seeds a confirmed + active user with NO role assignments. The Finbuckle tenant |
| 142 | + /// context is set INLINE because it is AsyncLocal — setting it in an awaited helper |
| 143 | + /// would lose it and the tenant query filter would throw. |
| 144 | + /// </summary> |
| 145 | + private async Task<(string Email, string Password, string UserId)> CreateActiveUserAsync(string handle) |
| 146 | + { |
| 147 | + const string password = TestConstants.DefaultPassword; |
| 148 | + var email = $"{handle}@example.com"; |
| 149 | + |
| 150 | + using var scope = _factory.Services.CreateScope(); |
| 151 | + |
| 152 | + var tenant = await scope.ServiceProvider |
| 153 | + .GetRequiredService<IMultiTenantStore<AppTenantInfo>>() |
| 154 | + .GetAsync(TestConstants.RootTenantId); |
| 155 | + scope.ServiceProvider.GetRequiredService<IMultiTenantContextSetter>() |
| 156 | + .MultiTenantContext = new MultiTenantContext<AppTenantInfo>(tenant); |
| 157 | + |
| 158 | + var userManager = scope.ServiceProvider.GetRequiredService<UserManager<FshUser>>(); |
| 159 | + var user = new FshUser |
| 160 | + { |
| 161 | + FirstName = "GroupRole", |
| 162 | + LastName = "Probe", |
| 163 | + Email = email, |
| 164 | + UserName = handle, |
| 165 | + EmailConfirmed = true, |
| 166 | + IsActive = true, |
| 167 | + }; |
| 168 | + |
| 169 | + var result = await userManager.CreateAsync(user, password); |
| 170 | + result.Succeeded.ShouldBeTrue( |
| 171 | + $"Seeding active user failed: {string.Join(", ", result.Errors.Select(e => e.Description))}"); |
| 172 | + |
| 173 | + return (email, password, user.Id); |
| 174 | + } |
| 175 | +} |
0 commit comments