fix(identity): harden user lifecycle and permissions
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Successful in 20m8s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Failing after 6m10s
Heimdall Gitea / Build and scan server image (pull_request) Failing after 8m2s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 2s
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Successful in 20m8s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Failing after 6m10s
Heimdall Gitea / Build and scan server image (pull_request) Failing after 8m2s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 2s
This commit is contained in:
1 parent
ea5f0b7589
commit
2bf3dbc95b
80 files changed
+1208
-507
No files matched your search
@@ -147,7 +147,7 @@ public class AuthFlowTests : IAsyncLifetime
|
||||
/// This validates the complete auth pipeline works end-to-end.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task RegisterAdmin_ThenLogin_ReturnsJwt_AndAccessesProtectedApi()
|
||||
public async Task FirstAdminBootstraps_AndCreatesFurtherAdminsThroughUserManagement()
|
||||
{
|
||||
var email = $"e2e-{Guid.NewGuid()}@heimdall.test";
|
||||
var password = "E2eTestPwd123!";
|
||||
@@ -166,33 +166,35 @@ public class AuthFlowTests : IAsyncLifetime
|
||||
var bootToken = bootContent.GetProperty("accessToken").GetString();
|
||||
bootToken.ShouldNotBeNullOrEmpty();
|
||||
|
||||
// Enable the admin-registration feature flag
|
||||
// Further accounts, including additional administrators, use the same
|
||||
// user-management path that the authenticated UI calls.
|
||||
client.DefaultRequestHeaders.Authorization =
|
||||
new AuthenticationHeaderValue("Bearer", bootToken);
|
||||
var flagResponse = await client.PostAsJsonAsync("/api/settings", new
|
||||
var createResponse = await client.PostAsJsonAsync("/api/users", new
|
||||
{
|
||||
key = "auth.admin-registration.enabled",
|
||||
value = "true",
|
||||
valueType = "bool",
|
||||
category = "Auth",
|
||||
description = "Enable admin registration via API"
|
||||
email,
|
||||
password,
|
||||
displayName = "E2E Test Admin",
|
||||
roles = new[] { "Admin" }
|
||||
});
|
||||
flagResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
createResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
|
||||
// Step 2: Register a new admin via RegisterAdmin
|
||||
var registerResponse = await client.PostAsJsonAsync("/api/auth/register-admin", new
|
||||
var legacyAdminRegistration = await client.PostAsJsonAsync("/api/auth/register-admin", new
|
||||
{
|
||||
email,
|
||||
password,
|
||||
displayName = "E2E Test Admin"
|
||||
});
|
||||
legacyAdminRegistration.StatusCode.ShouldBe(HttpStatusCode.NotFound);
|
||||
|
||||
registerResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
var registerContent = await registerResponse.Content.ReadFromJsonAsync<JsonElement>(Json);
|
||||
var accessToken = registerContent.GetProperty("accessToken").GetString();
|
||||
var refreshToken = registerContent.GetProperty("refreshToken").GetString();
|
||||
accessToken.ShouldNotBeNullOrEmpty("register-admin must return an access token");
|
||||
refreshToken.ShouldNotBeNullOrEmpty("register-admin must return a refresh token");
|
||||
// New accounts are not implicitly signed in by account-management actions.
|
||||
var loginResponse = await client.PostAsJsonAsync("/api/auth/login", new { email, password });
|
||||
loginResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
var loginContent = await loginResponse.Content.ReadFromJsonAsync<JsonElement>(Json);
|
||||
var accessToken = loginContent.GetProperty("accessToken").GetString();
|
||||
var refreshToken = loginContent.GetProperty("refreshToken").GetString();
|
||||
accessToken.ShouldNotBeNullOrEmpty();
|
||||
refreshToken.ShouldNotBeNullOrEmpty();
|
||||
|
||||
// Step 3: Use the new admin token to access a protected API endpoint
|
||||
client.DefaultRequestHeaders.Authorization =
|
||||
|
||||
@@ -82,6 +82,8 @@ public sealed class AuthSessionSecurityTests(PostgreSqlContainerFixture postgres
|
||||
[Theory]
|
||||
[InlineData("lock")]
|
||||
[InlineData("roles")]
|
||||
[InlineData("password")]
|
||||
[InlineData("email")]
|
||||
public async Task Existing_jwt_cookie_and_refresh_are_revoked_by_account_change(string change)
|
||||
{
|
||||
var auth = await LoginAsync();
|
||||
@@ -92,7 +94,25 @@ public sealed class AuthSessionSecurityTests(PostgreSqlContainerFixture postgres
|
||||
{
|
||||
var sender = scope.ServiceProvider.GetRequiredService<ISender>();
|
||||
if (change == "lock") (await sender.Send(new LockUserCommand(_userId))).IsSuccess.ShouldBeTrue();
|
||||
else (await sender.Send(new AssignRolesCommand(_userId, ["Supervisor"]))).IsSuccess.ShouldBeTrue();
|
||||
else if (change == "roles") (await sender.Send(new AssignRolesCommand(_userId, ["Supervisor"]))).IsSuccess.ShouldBeTrue();
|
||||
else
|
||||
{
|
||||
var users = scope.ServiceProvider.GetRequiredService<UserManager<AppUser>>();
|
||||
var user = (await users.FindByIdAsync(_userId.ToString()))!;
|
||||
if (change == "email")
|
||||
{
|
||||
var update = await users.SetEmailAsync(user, $"changed-{_email}");
|
||||
update.Succeeded.ShouldBeTrue();
|
||||
await users.UpdateSecurityStampAsync(user);
|
||||
}
|
||||
else
|
||||
{
|
||||
var token = await users.GeneratePasswordResetTokenAsync(user);
|
||||
var reset = await users.ResetPasswordAsync(user, token, "Changed-password-123!");
|
||||
reset.Succeeded.ShouldBeTrue();
|
||||
await users.UpdateSecurityStampAsync(user);
|
||||
}
|
||||
}
|
||||
}
|
||||
var refresh = await _client.PostAsJsonAsync("/api/auth/refresh", new { refreshToken = auth.RefreshToken });
|
||||
refresh.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Heimdall.IntegrationTests.Factories;
|
||||
using System.Net.Http.Headers;
|
||||
using Shouldly;
|
||||
|
||||
namespace Heimdall.IntegrationTests.Controllers;
|
||||
@@ -59,4 +60,65 @@ public class RolesControllerTests : PostgresTestBase
|
||||
roles.Any(r => r.GetProperty("name").GetString() == "Admin").ShouldBeTrue();
|
||||
roles.Any(r => r.GetProperty("name").GetString() == "Viewer").ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admin_can_change_viewer_permissions_and_existing_viewer_sessions_are_revoked()
|
||||
{
|
||||
var admin = await Factory.CreateAdminClientAsync();
|
||||
var email = $"dynamic-viewer-{Guid.NewGuid():N}@heimdall.test";
|
||||
const string password = "DynamicViewer123!";
|
||||
var created = await admin.PostAsJsonAsync("api/users", new
|
||||
{
|
||||
email, password, displayName = "Dynamic Viewer", roles = new[] { "Viewer" }
|
||||
});
|
||||
created.EnsureSuccessStatusCode();
|
||||
using var viewer = Factory.CreateClient();
|
||||
var login = await viewer.PostAsJsonAsync("api/auth/login", new { email, password });
|
||||
login.EnsureSuccessStatusCode();
|
||||
var loginBody = await login.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var oldToken = loginBody.GetProperty("accessToken").GetString()!;
|
||||
viewer.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", oldToken);
|
||||
var forbiddenUpdate = await viewer.PutAsJsonAsync("api/roles/Viewer/permissions", new
|
||||
{
|
||||
permissions = new[] { "Site.Read" }
|
||||
});
|
||||
forbiddenUpdate.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden);
|
||||
|
||||
var update = await admin.PutAsJsonAsync("api/roles/Viewer/permissions", new
|
||||
{
|
||||
permissions = new[] { "Site.Read", "Camera.Read", "Event.Read", "Camera.Write" }
|
||||
});
|
||||
update.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var staleSession = await viewer.GetAsync("api/users/me");
|
||||
staleSession.StatusCode.ShouldBe(System.Net.HttpStatusCode.Unauthorized);
|
||||
|
||||
var freshLogin = await viewer.PostAsJsonAsync("api/auth/login", new { email, password });
|
||||
freshLogin.EnsureSuccessStatusCode();
|
||||
var freshBody = await freshLogin.Content.ReadFromJsonAsync<JsonElement>();
|
||||
freshBody.GetProperty("user").GetProperty("permissions").EnumerateArray()
|
||||
.Select(p => p.GetString()).ShouldContain("Camera.Write");
|
||||
|
||||
var list = await admin.GetFromJsonAsync<JsonElement>("api/roles");
|
||||
var viewerRole = list.GetProperty("roles").EnumerateArray()
|
||||
.Single(r => r.GetProperty("name").GetString() == "Viewer");
|
||||
viewerRole.GetProperty("permissions").EnumerateArray().Select(p => p.GetString())
|
||||
.ShouldNotContain("Camera.Live");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admin_role_permissions_are_immutable()
|
||||
{
|
||||
var admin = await Factory.CreateAdminClientAsync();
|
||||
var update = await admin.PutAsJsonAsync("api/roles/Admin/permissions", new
|
||||
{
|
||||
permissions = new[] { "Site.Read" }
|
||||
});
|
||||
update.StatusCode.ShouldBe(System.Net.HttpStatusCode.BadRequest);
|
||||
|
||||
var role = await admin.GetFromJsonAsync<JsonElement>("api/roles/Admin");
|
||||
var permissions = role.GetProperty("permissions").EnumerateArray().Select(p => p.GetString()).ToArray();
|
||||
permissions.ShouldContain("Admin.Users");
|
||||
permissions.ShouldContain("Admin.Manage");
|
||||
}
|
||||
}
|
||||
@@ -69,4 +69,30 @@ public class UsersControllerTests : PostgresTestBase
|
||||
var resetContent = await resetResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
resetContent.GetProperty("temporaryPassword").GetString().ShouldNotBeNullOrEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Last_unlocked_admin_cannot_be_locked_when_another_admin_is_already_locked()
|
||||
{
|
||||
var admin = await Factory.CreateAdminClientAsync();
|
||||
var list = await admin.GetFromJsonAsync<JsonElement>("api/users?page=1&pageSize=20");
|
||||
var firstAdminId = list.GetProperty("items").EnumerateArray()
|
||||
.Single(user => user.GetProperty("roles").EnumerateArray().Any(role => role.GetString() == "Admin"))
|
||||
.GetProperty("id").GetGuid();
|
||||
|
||||
var created = await admin.PostAsJsonAsync("api/users", new
|
||||
{
|
||||
email = $"extra-admin-{Guid.NewGuid():N}@heimdall.test",
|
||||
password = "ExtraAdmin123!",
|
||||
displayName = "Extra Admin",
|
||||
roles = new[] { "Admin" }
|
||||
});
|
||||
created.EnsureSuccessStatusCode();
|
||||
var secondAdminId = (await created.Content.ReadFromJsonAsync<JsonElement>())
|
||||
.GetProperty("id").GetGuid();
|
||||
(await admin.PostAsync($"api/users/{secondAdminId}/lock", null)).StatusCode
|
||||
.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var lockLast = await admin.PostAsync($"api/users/{firstAdminId}/lock", null);
|
||||
lockLast.StatusCode.ShouldBe(System.Net.HttpStatusCode.BadRequest);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user