Gebruikersbeheer herkent de aanroeper aan het gebruikers-id van het token

Een echt access token heeft geen naam-claim, dus User.Identity.Name was null en elke aanroeper gold als
Beheerder: een Eigenaar kreeg 403 bij het toekennen van de Eigenaar-rol, en de controles voor 'jezelf'
(niet zelf verwijderen of deactiveren) sloegen nooit aan. Nu via het id van het token. Regressietest met
echte tokens en de echte pipeline.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 21:29:24 +01:00
co-authored by Claude Sonnet 5.5
parent f242da8429
commit ef7df53988
5 changed files with 293 additions and 6 deletions
@@ -0,0 +1,219 @@
using System.Net;
using System.Net.Http.Json;
using FluentAssertions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NSubstitute;
using SlpModularCms.Core.Data;
using SlpModularCms.Core.Email;
using SlpModularCms.Core.Hosting;
using SlpModularCms.Core.Identity.Authorization;
using SlpModularCms.Core.Identity.Entities;
using SlpModularCms.Core.Identity.Models;
using SlpModularCms.Core.Identity.Services;
using SlpModularCms.Modules.Identity.Controllers;
namespace SlpModularCms.Modules.Identity.Tests.Controllers;
/// <summary>
/// The user-management API as the browser really calls it: real login tokens from <see cref="AuthService"/>, the
/// real bearer pipeline and policies, the real controller. The unit tests of the controller hand it claims they
/// choose; a real access token carries the user id and the e-mail address but NO name claim
/// (<c>User.Identity.Name</c> is null), which once made every caller look like an Administrator, so an Owner
/// could not promote anybody to Owner. This class exists so that cannot happen unnoticed again.
/// </summary>
public class UsersApiWithRealTokensTests : IAsyncLifetime
{
private static readonly JwtSettings Jwt = new()
{
Secret = "a-test-secret-that-is-long-enough-for-hmac-sha256-0123456789",
Issuer = "test-issuer", Audience = "test-audience", ExpiryMinutes = 30
};
private readonly string _dbName = Guid.NewGuid().ToString();
private readonly IIdentityMailService _mail = Substitute.For<IIdentityMailService>();
private readonly IInvitationService _invitations = Substitute.For<IInvitationService>();
private IHost _host = null!;
private HttpClient _client = null!;
public async Task InitializeAsync()
{
_mail.SendRoleChangedAsync(default!, default!, default).ReturnsForAnyArgs(MailSendResult.Ok);
_mail.SendAccountDeactivatedAsync(default!, default).ReturnsForAnyArgs(MailSendResult.Ok);
_mail.SendAccountReactivatedAsync(default!, default).ReturnsForAnyArgs(MailSendResult.Ok);
_invitations.GetAllPendingInvitationsAsync().Returns(new List<PendingInvitationInfo>());
_host = await new HostBuilder().ConfigureWebHost(web =>
{
web.UseTestServer();
web.ConfigureServices(services =>
{
services.AddLogging();
services.AddDbContext<ApplicationDbContext>(o => o.UseInMemoryDatabase(_dbName));
services.AddIdentityCore<ApplicationUser>().AddRoles<ApplicationRole>().AddEntityFrameworkStores<ApplicationDbContext>();
services.Configure<JwtSettings>(o =>
{
o.Secret = Jwt.Secret; o.Issuer = Jwt.Issuer; o.Audience = Jwt.Audience; o.ExpiryMinutes = Jwt.ExpiryMinutes;
});
services.AddScoped<IAuthService, AuthService>();
services.AddSingleton(_mail);
services.AddSingleton(_invitations);
services.AddAuthentication("Bearer").AddJwtBearer(o => o.UseCmsTokenValidation(JwtTokenValidation.Create(Jwt)));
services.AddAuthorization(o =>
{
o.AddPolicy("OwnerOnly", p => p.Requirements.Add(new HierarchicalRoleRequirement("Owner")));
o.AddPolicy("AdminOnly", p => p.Requirements.Add(new HierarchicalRoleRequirement("Administrator")));
});
services.AddSingleton<IAuthorizationHandler, HierarchicalRoleHandler>();
services.AddControllers().AddApplicationPart(typeof(UsersController).Assembly);
});
web.Configure(app =>
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(e => e.MapControllers());
});
}).StartAsync();
_client = _host.GetTestClient();
using var scope = _host.Services.CreateScope();
var roles = scope.ServiceProvider.GetRequiredService<RoleManager<ApplicationRole>>();
foreach (var role in new[] { "Owner", "Administrator", "User" })
await roles.CreateAsync(new ApplicationRole { Name = role });
}
public async Task DisposeAsync()
{
_client.Dispose();
await _host.StopAsync();
_host.Dispose();
}
private async Task<ApplicationUser> AddUserAsync(string email, string role)
{
using var scope = _host.Services.CreateScope();
var users = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var user = new ApplicationUser { UserName = email, Email = email, IsActive = true, DisplayName = email };
(await users.CreateAsync(user, "Password1!")).Succeeded.Should().BeTrue();
await users.AddToRoleAsync(user, role);
return user;
}
private async Task<string> TokenAsync(string email)
{
using var scope = _host.Services.CreateScope();
return (await scope.ServiceProvider.GetRequiredService<IAuthService>().AuthenticateAsync(email, "Password1!")).AccessToken;
}
private async Task<string> RoleOfAsync(Guid id)
{
using var scope = _host.Services.CreateScope();
var users = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
return (await users.GetRolesAsync((await users.FindByIdAsync(id.ToString()))!)).Single();
}
private async Task<HttpStatusCode> SendAsync(string token, HttpMethod method, string path, object? body = null)
{
using var request = new HttpRequestMessage(method, path);
request.Headers.Authorization = new("Bearer", token);
if (body is not null) request.Content = JsonContent.Create(body);
return (await _client.SendAsync(request)).StatusCode;
}
private Task<HttpStatusCode> ChangeRoleAsync(string token, Guid target, string newRole) =>
SendAsync(token, HttpMethod.Put, $"/Users/{target}/role", new { newRole });
// ---- the reported bug: an Owner promotes an Administrator to Owner
[Fact]
public async Task AnOwner_CanPromoteAnAdministratorToOwner()
{
await AddUserAsync("andrea@test.nl", "Owner");
var bryan = await AddUserAsync("bryan@test.nl", "Administrator");
var status = await ChangeRoleAsync(await TokenAsync("andrea@test.nl"), bryan.Id, "Owner");
status.Should().Be(HttpStatusCode.OK);
(await RoleOfAsync(bryan.Id)).Should().Be("Owner");
}
[Fact]
public async Task AnOwner_CanKeepTheirOwnRole_DemoteAnAdministrator_AndDeactivateAndDeleteOthers()
{
var andrea = await AddUserAsync("andrea@test.nl", "Owner");
var admin = await AddUserAsync("admin@test.nl", "Administrator");
var user = await AddUserAsync("user@test.nl", "User");
var token = await TokenAsync("andrea@test.nl");
(await ChangeRoleAsync(token, andrea.Id, "Owner")).Should().Be(HttpStatusCode.OK);
(await ChangeRoleAsync(token, admin.Id, "User")).Should().Be(HttpStatusCode.OK);
(await SendAsync(token, HttpMethod.Put, $"/Users/{user.Id}/active", new { isActive = false })).Should().Be(HttpStatusCode.OK);
(await SendAsync(token, HttpMethod.Delete, $"/Users/{admin.Id}")).Should().Be(HttpStatusCode.NoContent);
}
// ---- the Administrator is held to the hierarchy
[Fact]
public async Task AnAdministrator_CannotMakeAnyoneOwner_NotEvenThemselves_NorTouchAnOwner()
{
var owner = await AddUserAsync("andrea@test.nl", "Owner");
var admin = await AddUserAsync("bryan@test.nl", "Administrator");
var user = await AddUserAsync("user@test.nl", "User");
var token = await TokenAsync("bryan@test.nl");
(await ChangeRoleAsync(token, admin.Id, "Owner")).Should().Be(HttpStatusCode.Forbidden);
(await ChangeRoleAsync(token, user.Id, "Owner")).Should().Be(HttpStatusCode.Forbidden);
(await SendAsync(token, HttpMethod.Put, $"/Users/{owner.Id}/active", new { isActive = false })).Should().Be(HttpStatusCode.Forbidden);
(await SendAsync(token, HttpMethod.Delete, $"/Users/{owner.Id}")).Should().Be(HttpStatusCode.Forbidden);
(await RoleOfAsync(admin.Id)).Should().Be("Administrator");
(await RoleOfAsync(owner.Id)).Should().Be("Owner");
}
[Fact]
public async Task AnAdministrator_CanStillPromoteAUserToAdministrator()
{
await AddUserAsync("bryan@test.nl", "Administrator");
var user = await AddUserAsync("user@test.nl", "User");
(await ChangeRoleAsync(await TokenAsync("bryan@test.nl"), user.Id, "Administrator")).Should().Be(HttpStatusCode.OK);
(await RoleOfAsync(user.Id)).Should().Be("Administrator");
}
// ---- "yourself" is recognised from the token
[Fact]
public async Task NobodyCanDeleteOrDeactivateThemselves()
{
var andrea = await AddUserAsync("andrea@test.nl", "Owner");
await AddUserAsync("second@test.nl", "Owner");
var token = await TokenAsync("andrea@test.nl");
(await SendAsync(token, HttpMethod.Delete, $"/Users/{andrea.Id}")).Should().Be(HttpStatusCode.BadRequest);
(await SendAsync(token, HttpMethod.Put, $"/Users/{andrea.Id}/active", new { isActive = false })).Should().Be(HttpStatusCode.BadRequest);
}
[Fact]
public async Task TheLastOwner_CannotBeDemoted_ByThemselves()
{
var andrea = await AddUserAsync("andrea@test.nl", "Owner");
(await ChangeRoleAsync(await TokenAsync("andrea@test.nl"), andrea.Id, "User")).Should().Be(HttpStatusCode.BadRequest);
(await RoleOfAsync(andrea.Id)).Should().Be("Owner");
}
[Fact]
public async Task AnAdministrator_CanStepDownToUser_Themselves()
{
var admin = await AddUserAsync("bryan@test.nl", "Administrator");
(await ChangeRoleAsync(await TokenAsync("bryan@test.nl"), admin.Id, "User")).Should().Be(HttpStatusCode.OK);
(await RoleOfAsync(admin.Id)).Should().Be("User");
}
}