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
+1
View File
@@ -13,3 +13,4 @@
| Bug | [cms-admin-nine-points](bugs/cms-admin-nine-points/bug-fix.md) | ✅ Complete (wacht op goedkeuring ASF test) | feature/andreaslop-site-hosting | Core (auth, invitations), Identity, Availability, Frontend | 2026-11-08 |
| Bug | [invitation-delete-and-lifetime](bugs/invitation-delete-and-lifetime/bug-fix.md) | ✅ Complete (wacht op goedkeuring ASF test) | feature/andreaslop-site-hosting | Core (invitations), Identity, Frontend | 2026-11-08 |
| Feature | Identity e-mail notifications (identity-email-notifications) | 🔵 Inception (wacht op antwoorden) | feature/identity-email-notifications | Core (IEmailSender), Identity, Frontend | 2026-11-08 |
| Bug | [owner-cannot-promote-requester-identity](bugs/owner-cannot-promote-requester-identity/bug-fix.md) | ✅ Complete (wacht op ASF test deploy) | feature/identity-email-notifications | Identity (UsersController) | 2026-11-08 |
@@ -0,0 +1,47 @@
# Bug Fix: an Owner gets 403 when promoting an Administrator to Owner (the caller was not recognised)
- **Slug**: owner-cannot-promote-requester-identity
- **Status**: Complete (pending ASF test deploy)
- **Issue**: None (reported by Bryan via "CMS & API" and the Pi-Main journal, 2026-11-08)
- **Branch**: feature/identity-email-notifications
- **Started**: 2026-11-08
- **Documentation Language**: English
- **Conversation Language**: Dutch (user language)
## Report
**Reproduction**: on ASF test, signed in as the owner, `PUT /api/v1/Users/{id}/role` with `newRole = Owner` for an Administrator. Six calls over three hours, two user ids, all 403; signing in again did not help. It worked earlier the same day.
**Expected**: an Owner may manage everyone and may hand out the Owner role. **Actual**: 403, as if the caller were an Administrator.
**Environment**: ASF test, release 142815a, which contains the role hierarchy of run 615.
## Root Cause
`UsersController` found out who is calling through `User.Identity.Name`. A real access token (issued by `AuthService`) carries `sub` (the user id), the e-mail address, the roles, `jti` and `stamp`, but **no name claim**, so `User.Identity.Name` is **null** for every real caller (confirmed with a probe that issued a real token and read the principal; only the unit tests supplied a name claim, so they never saw it). With the caller unresolved, `GetRequesterRoleAsync` returned its deliberately restrictive fallback, **Administrator**, so `CanAssign(Administrator, "Owner")` was false and every Owner who tried to hand out the Owner role got a 403 from the controller (`ForbidResult`). Before the hierarchy was added the same unresolved caller meant "no restrictions", which is why it worked earlier that day.
The same flaw made the "yourself" checks (cannot deactivate or delete yourself, an Administrator may step down themselves) compare against a null name, so they never matched.
Not related: the `admin_bypass_rejected ... (reason: Expired)` events. The availability middleware checks the bearer token of every request to decide whether an administrator may pass during maintenance; an access token older than its 60 minutes is logged as rejected there. That is normal noise from a tab that still holds an expired token before the silent refresh (the request then gets a 401 and the client refreshes), and an expired token would give a 401, not a 403.
**Confirmed with user**: relayed by "CMS & API" (Bryan asked for a cause first, then a fix if it is a bug).
## The Fix
- `UsersController`: the caller is found by the **user id of the token** (`NameIdentifier`/`sub`), through one helper (`CurrentUserId`, `GetRequesterAsync`); `IsSelf` compares ids. The name is only a fallback for callers that carry no id. The restrictive fallback for an unresolvable caller stays (secure by default).
- `SiteSettingsController`: the recorded `UpdatedBy` uses the e-mail claim (it was null for the same reason).
- Behaviour that now works as designed: an Owner can promote to Owner, keep their own role, demote and manage others; nobody can delete or deactivate themselves (it used to slip through); the last Owner cannot be demoted by themselves; an Administrator can still step down themselves and promote a User to Administrator, but never hands out Owner.
## Verification
**Path used**: Automated test framework. New `UsersApiWithRealTokensTests` (Identity.Tests): real login tokens from `AuthService`, the real bearer pipeline and policies, the real controller on a TestServer.
**Before the fix** (id lookup disabled): 5 of the 7 scenarios fail, including "an Owner can promote an Administrator to Owner" (403) and "nobody can delete or deactivate themselves".
**After the fix**: 7 of 7 pass; Identity.Tests 133, Core.Tests 547 green.
## Result
- **PR(s)**: None
- **Commit(s)**: see branch history
- **Completed**: 2026-11-08
@@ -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");
}
}
@@ -1,3 +1,4 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SlpModularCms.Core.SiteSettings;
@@ -24,7 +25,7 @@ public class SiteSettingsController : ControllerBase
[Authorize(Policy = "OwnerOnly")]
public async Task<IActionResult> SetMail([FromBody] UpdateMailSettingsRequest request, CancellationToken ct)
{
var result = await _settings.SetMailAsync(request.FromAddress, request.FromName, User.Identity?.Name, ct);
var result = await _settings.SetMailAsync(request.FromAddress, request.FromName, User.FindFirstValue(ClaimTypes.Email) ?? User.Identity?.Name, ct);
if (result.Ok) return Ok(await _settings.GetMailAsync(ct));
return result.Error == SetMailResult.MailDisabled
@@ -334,17 +334,36 @@ public class UsersController : ControllerBase
return NoContent();
}
/// <summary>
/// The caller's user id from the token. A real access token carries the id (<c>sub</c>, mapped to the name
/// identifier) and the e-mail address, but NO name claim, so <c>User.Identity.Name</c> is null: anything that
/// has to know who is calling must go by this id.
/// </summary>
private Guid? CurrentUserId =>
Guid.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub"), out var id) ? id : null;
private bool IsSelf(ApplicationUser target) =>
string.Equals(target.Email, User.Identity?.Name, StringComparison.OrdinalIgnoreCase);
CurrentUserId is { } id
? id == target.Id
: string.Equals(target.Email, User.Identity?.Name, StringComparison.OrdinalIgnoreCase);
private async Task<ApplicationUser?> GetRequesterAsync()
{
if (CurrentUserId is { } id)
return await _userManager.FindByIdAsync(id.ToString());
var name = User.Identity?.Name;
return name is not null ? await _userManager.FindByNameAsync(name) : null;
}
/// <summary>
/// The role of the caller from the database (not the token, which can be stale). A caller that cannot
/// be resolved is treated as an Administrator, the most restricted role that reaches this controller.
/// The role of the caller from the database (not the token, which can be stale), found by the user id of
/// the token. A caller that cannot be resolved is treated as an Administrator, the most restricted role
/// that reaches this controller.
/// </summary>
private async Task<string> GetRequesterRoleAsync()
{
var name = User.Identity?.Name;
var requester = name is not null ? await _userManager.FindByNameAsync(name) : null;
var requester = await GetRequesterAsync();
if (requester is null) return UserManagementRules.Administrator;
var roles = await _userManager.GetRolesAsync(requester);