From d0ab0a207caed74896c73a043a95a44770f69c19 Mon Sep 17 00:00:00 2001 From: Finnegan's Owner <44065187+pacmano1@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:51:40 -0700 Subject: [PATCH] Add UserRoles, a supported way for plugins to set a user's role OIDC Authentication sets a user's role from identity provider groups, and the LDAP plugin, not released yet, does the same from directory groups. Both call rbac's repository by reflection. Those calls bypass rbac's last-admin check, cache refresh and audit event, so each plugin repeats the check and the refresh itself. com.diridium.rbac.UserRoles is the supported way. Plugins still call it by reflection: - isReady, roleNames, adminRoleName, currentRoleName and assign, all static. - Roles by name, compared exactly on every database. - assign returns ASSIGNED, ALREADY_ASSIGNED, NO_SUCH_ROLE, LAST_ADMIN or NOT_READY, and throws on unexpected failures. - It keeps the last admin on the admin role, refreshes that user's cached permissions, and records an audit event naming the plugin. Role changes on one engine now run one at a time: UserRoles.assign and the Administrators' Assign Role and Remove Role hold one lock from the last-admin check through the write. A lock was rejected on 2026-06-12, when only people changed roles. Plugins change roles at every sign-in, and a restart doesn't repair a race there: rbac restores the admin role at startup only to a user 1 left with no role. The direct repository calls OIDC Authentication 1.0.3 makes keep working and are deprecated. The release notes will name the release that ends support for them. Tests: unit tests for each code assign returns, a race test that fails without the lock, a contract test pinning the class name, its public methods and the codes, and an e2e check that calls UserRoles from a channel deploy script by reflection on all six databases. Co-Authored-By: Claude --- CLAUDE.md | 9 +- README.md | 34 +++++ docs/design-notes.md | 23 +++ e2e/checks.py | 108 ++++++++++++++ e2e/rbac.py | 14 +- e2e/scenarios.py | 1 + .../com/diridium/rbac/AdminRoleGuard.java | 51 ++++--- .../java/com/diridium/rbac/RbacAuditLog.java | 18 +++ .../rbac/RbacAuthorizationController.java | 9 +- .../com/diridium/rbac/RbacRepository.java | 14 +- .../java/com/diridium/rbac/RoleService.java | 12 +- .../java/com/diridium/rbac/UserRoles.java | 111 ++++++++++++++ .../com/diridium/rbac/UserRolesService.java | 102 +++++++++++++ .../com/diridium/rbac/AdminRoleGuardTest.java | 19 +++ .../com/diridium/rbac/RbacAuditLogTest.java | 21 +++ .../rbac/ReflectionCallerContractTest.java | 7 +- .../com/diridium/rbac/RoleChangeRaceTest.java | 126 ++++++++++++++++ .../diridium/rbac/UserRolesContractTest.java | 110 ++++++++++++++ .../diridium/rbac/UserRolesServiceTest.java | 140 ++++++++++++++++++ 19 files changed, 895 insertions(+), 34 deletions(-) create mode 100644 server/src/main/java/com/diridium/rbac/UserRoles.java create mode 100644 server/src/main/java/com/diridium/rbac/UserRolesService.java create mode 100644 server/src/test/java/com/diridium/rbac/RoleChangeRaceTest.java create mode 100644 server/src/test/java/com/diridium/rbac/UserRolesContractTest.java create mode 100644 server/src/test/java/com/diridium/rbac/UserRolesServiceTest.java diff --git a/CLAUDE.md b/CLAUDE.md index 70b1ec4..da6529a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ Role-Based Access Control plugin for OIE/Mirth Connect 4.7.0 (1.1.4 is the last ## Project Structure ``` rbac/ -├── server/ # RbacAuthorizationController, RbacServicePlugin, RbacServlet, RbacRepository, RbacMigrator, RoleTransfer*/RoleImport* (export and import), PluginSettingsGuard +├── server/ # RbacAuthorizationController, RbacServicePlugin, RbacServlet, RbacRepository, RbacMigrator, RoleTransfer*/RoleImport* (export and import), PluginSettingsGuard, UserRoles (for other plugins) ├── shared/ # RbacServletInterface (JAX-RS), Role model, RoleImportResult/RoleImportRow, NameCharacters (the name rules the server and the Swing role editor share) ├── client/ # RbacClientPlugin, RbacSettingsPanel (+ UserAssignmentsPanel), RoleEditorDialog, RoleTransferActions/RoleImport*/RoleExport* (export and import), SecureAuthorizationController ├── package/ # plugin.xml, sqlmap.xml, assembly.xml @@ -43,6 +43,11 @@ Output: `package/target/rbac-1.3.0.zip` - Names with control characters: `RoleService` refuses a new or renamed role name, and newly added permissions, holding one of those characters or a character XML can't carry (`UNSAFE_CHARACTERS`), and a new or changed description holding a control character other than a tab or a line break, or a character XML can't carry (`UNSAFE_DESCRIPTION`); the import planner refuses a file that would create a role with such a name. Existing names, permissions and descriptions are left alone. A stored name, permission or description holding a character XML can't carry (a bell, U+0007) makes the role list answer HTTP 500 to both Administrators and stops role export (measured on OIE 4.7.0), so `UnlistableRoles` logs such roles at startup with their id, and the README gives the REST call that deletes one. Deleting a role removes its users' assignments (`ON DELETE CASCADE`), and the README says so. Owner's decisions 2026-11-23 and 2026-11-24: refuse only these characters. The engine's channel-name allow-list isn't used; the engine checks it only in the Swing client. - Cache: `ConcurrentHashMap` invalidated on all write REST endpoints. `DeletedUserCleanup` removes a deleted user's `rbac_user_role` row on the request after the engine's delete (the engine has no user-delete hook, but it asks rbac to authorize `removeUser` first, so the approved target is held as pending and checked against the engine on the next authorization); the startup sweep (`deleteOrphanUserRoles`) covers users deleted while rbac wasn't loaded. +### Setting a role from another plugin (`UserRoles`) +- `com.diridium.rbac.UserRoles` (public, static methods, issue #56) is the supported way for another plugin to set a user's role, called by reflection: `isReady`, `roleNames`, `adminRoleName`, `currentRoleName(int)`, `assign(int, String, String)` returning `ASSIGNED`, `ALREADY_ASSIGNED`, `NO_SUCH_ROLE`, `LAST_ADMIN` or `NOT_READY`; unexpected failures throw; the reads throw `IllegalStateException` before rbac starts. `UserRolesService` does the work and is unit-tested; `UserRolesContractTest` pins the class name, its exact set of public methods and the codes, so a new public method fails the build until it is meant. Owner's decisions 2026-11-26 to 2026-11-29: by role name, never id (ids differ after an export and import); names compared exactly on every database (`findRoleIdByName` ignores case on MySQL and SQL Server, so its answer is checked); no remove method until a plugin asks; the audit event (`RbacAuditLog.pluginAssignment`) names the plugin as the caller gives it. +- The outside calls OIDC 1.0.3 makes (`RbacRepository` methods and `invalidateCache(Integer)`, pinned by `ReflectionCallerContractTest`) are deprecated, not removed: they keep working until a release named in the release notes. rbac keeps using those methods itself. The LDAP plugin uses `UserRoles` from its first release. +- The e2e suite calls `UserRoles` from a channel deploy script, by reflection like a plugin, with no signed-in user (`checks.user_roles`). Measured 2026-11-29: a deploy script reaches rbac's classes through `Class.forName`. + ### Client-Side Authorization - `SecureAuthorizationController` implements `com.mirth.connect.client.ui.AuthorizationController` - Must be in package `com.mirth.connect.plugins.auth.client` (factory expects this exact FQCN) @@ -94,7 +99,7 @@ Output: `package/target/rbac-1.3.0.zip` ## Key Design Decisions - Admin access is by role flag (`is_admin`), not by user ID — supports multiple admin users; identified the same way on server and client (`Role.isAdmin()`) -- The admin role cannot be deleted, and an "admin floor" prevents removing/reassigning the last *live* admin user (enforced server-side by `AdminRoleGuard`; the floor count excludes orphaned rows for engine-deleted users). The admin role's name *can* be changed; the role editor disables the admin role's name, permission, and channel controls (only the description is editable) and re-sends its stored perms on save. +- The admin role cannot be deleted, and an "admin floor" prevents removing/reassigning the last *live* admin user (enforced server-side by `AdminRoleGuard`; the floor count excludes orphaned rows for engine-deleted users). Role changes run one at a time: `RoleService.assignUserRole`/`removeUserRole` and `UserRoles.assign` hold `AdminRoleGuard.ROLE_CHANGES` from the floor check through the write, so two simultaneous demotions can't leave no admin (`RoleChangeRaceTest`). This reverses a 2026-06-12 decision against a lock: sign-in plugins now change roles programmatically, and a restart doesn't recover their case (`AdminRoleSeeder` restores only a roleless user 1). Owner's decision 2026-11-29. One engine only; OIDC's direct repository calls don't take the lock. The admin role's name *can* be changed; the role editor disables the admin role's name, permission, and channel controls (only the description is editable) and re-sends its stored perms on save. - The admin role's retention floor is the **core** permission set, not core+extension. The seeder grants only core perms, and admin access is by the flag regardless of stored perms, so requiring extension perms just made the admin role uneditable. - `manageExtensions` is effectively an admin-equivalent grant: a holder can disable the RBAC extension, and on the next restart the engine reverts to the always-allow `DefaultAuthorizationController` (every user becomes admin). The role editor tags it with a warning tooltip; treat it as a privileged grant. This mirrors stock OIE (manageExtensions = install/enable/disable plugins = arbitrary code). - `Manage Roles` is for delegating user management, not a security boundary: a holder can give their own account any role, the admin role included (measured on OIE 4.7.0 with rbac 1.2.0). Both role editors tag it with a warning tooltip, like `manageExtensions`. diff --git a/README.md b/README.md index 9a0fe69..15b0cbc 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,40 @@ A role stores a plugin's permission by its display name, the name the role edito The engine's plugin-settings calls (`/api/extensions/{name}/properties`) are allowed only under the exact name of an installed extension, and rbac's own settings only to the admin role. +## Setting a user's role from another plugin + +A plugin that signs users in, from a directory or an identity provider for example, can give each user an RBAC role through `com.diridium.rbac.UserRoles`. Call it by reflection, so your plugin has no build or install dependency on RBAC: + +```java +Class userRoles; +try { + userRoles = Class.forName("com.diridium.rbac.UserRoles"); +} catch (ClassNotFoundException e) { + return; // RBAC isn't installed, or is older than the first version with UserRoles +} +if (!(Boolean) userRoles.getMethod("isReady").invoke(null)) { + return; // RBAC hasn't started +} +String result = (String) userRoles.getMethod("assign", int.class, String.class, String.class) + .invoke(null, userId, "Billing", "My Sign-in Plugin"); +``` + +Its static methods: + +- `isReady()`: whether RBAC has started. +- `roleNames()`: every role's name, for a settings screen. +- `adminRoleName()`: the admin role's name. +- `currentRoleName(userId)`: the user's role, or null when the user has none. +- `assign(userId, roleName, callerPlugin)`: gives the user the role and returns a code. + +`assign` returns `ASSIGNED`, `ALREADY_ASSIGNED`, `NO_SUCH_ROLE`, `LAST_ADMIN` or `NOT_READY`. `LAST_ADMIN` means the user is the last user holding the admin role, so they keep it. On an unexpected failure, such as the database being down, `assign` throws and the role is unchanged. The read methods throw `IllegalStateException` before RBAC has started. + +Roles are given by name, because role ids differ between engines. Names are compared exactly on every database, so "billing" doesn't find "Billing". `assign` applies the same last-admin check as Assign Role in the Administrator, refreshes the user's permissions at once, and records an audit event with the user, the role and the plugin name you pass. RBAC records that name as given and doesn't check it. + +Role changes on one engine run one at a time, whether they come from `assign` or from the Administrator. Two changes made at the same moment can't both move one of the last two admins off the admin role. Engines that share one database don't wait for each other, and the other engines keep the permissions they cached before the change ([#62](https://github.com/diridium-com/role-based-access-control/issues/62)). + +Plugins that call `RbacRepository` and `RbacAuthorizationController.invalidateCache` directly should move to `UserRoles`. Those calls bypass RBAC's last-admin check, cache refresh and audit event, and don't wait for other role changes. They keep working for now, and the release notes will name the release that stops supporting them ([#72](https://github.com/diridium-com/role-based-access-control/issues/72)). + ## If the RBAC tab can't list roles A role whose name, permission or description contains a control character stops the OIE Administrator and the web Administrator from listing roles. RBAC names it in mirth.log at startup, with its number. Delete it with `curl -k -u admin -H 'X-Requested-With: OpenAPI' -X DELETE https://:8443/api/extensions/rbac/roles/`, then recreate it in the role editor. Deleting a role also removes it from its users, so assign them the new role. diff --git a/docs/design-notes.md b/docs/design-notes.md index 51407de..6dce12a 100644 --- a/docs/design-notes.md +++ b/docs/design-notes.md @@ -274,3 +274,26 @@ The list and removal are admin-only, like role export and import. - Browser tests: who sees the task, the list with the disabled plugins, Remove Selected and Remove All with their confirmations, and an empty list. - The e2e suite: a made-up grant is listed and no registered permission is, a View Roles and Manage Roles holder who is not the admin is refused both calls, and a removal takes the made-up grant and leaves the engine permission. - Both dialogs, driven on OIE 4.7.0 with a role still holding "Use Perm Test", the permission of a throwaway test plugin that doesn't ship, after the plugin's version 2 renamed it: both listed it, and the web dialog removed a made-up grant while that role kept its engine permissions. + +## 2026-11-29: UserRoles, for plugins that set a user's role + +Two sign-in plugins give users a role from their directory or identity provider groups: OIDC Authentication (gibson9583/oie-oidc-auth), and the LDAP plugin, which isn't released yet. Both call rbac's repository by reflection. Those calls bypass rbac's last-admin check, cache refresh and audit event, so each plugin repeats the check and the refresh itself. `com.diridium.rbac.UserRoles` is the supported way. Plugins still call it by reflection, so they need no build or install dependency on rbac. + +Roles are given by name. Role ids differ between engines, for example after a role export and import, and both plugins are configured with names. The database's name lookup ignores case on MySQL and SQL Server, so `UserRoles` checks the role it finds against the name and answers the same on every database. + +`assign` returns a code for each expected outcome. An unexpected failure, such as the database being down, throws. Both plugins catch every exception around their reflection calls (read in the code of OIDC 1.0.3 and of the LDAP plugin), so the caller can log the cause. + +There is no method to take a role away. Neither plugin's code does that today. A method is easy to add later, but once a plugin relies on one, removing it means a deprecation. The contract test pins the exact set of public methods so that each new one is a deliberate choice. + +Role changes on one engine now run one at a time. A lock around the last-admin check and the write was considered and rejected on 2026-06-12, when only people changed roles in the Administrator, with a note to revisit if roles were ever changed programmatically. Sign-in plugins change roles programmatically, at every sign-in. A restart doesn't repair a race there either. rbac restores the admin role at startup only to a user 1 left with no role, and a plugin moves users to another role. The lock covers `UserRoles.assign` and the Administrators' Assign Role and Remove Role. Engines sharing one database aren't covered. + +The audit event names the plugin as the caller gives it. rbac doesn't check that name: any plugin in the engine can write rbac's tables directly. + +OIDC's direct calls keep working. Going by its code, if they stopped working, OIDC 1.0.3 would log a warning in mirth.log at each sign-in and leave the user's role as it was, until a new OIDC release. They are deprecated, and a later release, named in the release notes, ends support for them. + +### Tests + +- Unit tests: each code `assign` returns, a name differing only in case where the database ignores case, the last admin kept, a database failure thrown with nothing recorded, the audit event and the one user's cache refresh. +- A race test starts two demotions of the last two admins at the same moment: once with both through `UserRoles`, once with one through `UserRoles` and one through the Administrator's Assign Role. It checks that one admin is left. With the lock removed, both demotions went through in both cases and no admin was left. With only the Administrator path's lock removed, the second case failed. +- A contract test pins the class name, its exact public methods, their signatures and the codes, looked up the way plugins look them up. +- The e2e suite calls `UserRoles` from a channel deploy script on OIE 4.7.0, by reflection and with no signed-in user, as a sign-in plugin does. Before writing it, a probe showed a deploy script can reach rbac's classes through `Class.forName`. Not measured: whether that is the class loader a plugin's own classes see. The LDAP plugin's switch to `UserRoles` will test that. diff --git a/e2e/checks.py b/e2e/checks.py index a2b8e65..491ac08 100644 --- a/e2e/checks.py +++ b/e2e/checks.py @@ -4,7 +4,10 @@ """The fresh scenario's checks, one function per feature. Each takes the Report and a World: the engine, the admin's session, the test users' sessions and ids, the roles and the channels the scenario made.""" +import json +import time import types +import uuid import xml.etree.ElementTree as ET import urllib.parse @@ -464,6 +467,111 @@ def orphaned_permissions(r, w): and all(d in (200, 204) for d in deleted), f"unassign HTTP {unassigned}, delete HTTP {deleted}") +# The deploy script user_roles runs: it calls UserRoles the way another plugin does, by reflection, and logs what +# each call returned on one line. @ROLE@, @ROLE_UPPER@, @UID@ and @MARK@ are filled in by user_roles. +USER_ROLES_SCRIPT = r"""var out = []; +function put(key, value) { + out.push(key + '=' + value); +} +function n(x) { + return java.lang.Integer.valueOf(String(x)); +} +try { + var type = java.lang.Class.forName('com.diridium.rbac.UserRoles'); + var INT = java.lang.Integer.TYPE; + var STR = java.lang.String; + var assign = type.getMethod('assign', INT, STR, STR); + var current = type.getMethod('currentRoleName', INT); + var plugin = 'rbac e2e caller'; + put('ready', type.getMethod('isReady').invoke(null)); + put('names_has_role', type.getMethod('roleNames').invoke(null).contains(@ROLE@)); + put('admin', type.getMethod('adminRoleName').invoke(null)); + put('current_before', current.invoke(null, n(@UID@))); + put('assign', assign.invoke(null, n(@UID@), @ROLE@, plugin)); + put('assign_again', assign.invoke(null, n(@UID@), @ROLE@, plugin)); + put('assign_missing', assign.invoke(null, n(@UID@), 'rbac e2e no such role', plugin)); + put('assign_case', assign.invoke(null, n(@UID@), @ROLE_UPPER@, plugin)); + put('current_after', current.invoke(null, n(@UID@))); + put('last_admin', assign.invoke(null, n(1), @ROLE@, plugin)); + put('admin_after', current.invoke(null, n(1))); +} catch (e) { + put('error', e); +} +logger.info(@MARK@ + ' ' + out.join(' || ')); +return;""" + + +def user_roles(r, w): + """UserRoles, the supported way for another plugin to set a user's role, called from a channel deploy script the + way a plugin calls it: by reflection, on the engine, with no signed-in user. Each code assign returns, the role's + name compared exactly, the last admin kept on the admin role, one audit event naming the calling plugin, and the + user's cached permissions refreshed at once.""" + a = w.api + role_name = "rbac e2e plugin role" + rid = b.create_role(a, role_name, ["viewDashboard", "viewChannels", "viewServerSettings"]) + session = add_user(w, "pluginuser") + uid = w.ids["pluginuser"] + expect(r, "UserRoles: before, the user with no role is refused server settings", session, "GET", + "/server/settings", (403,)) + admin_role = b.user_role(a, "1") + # admin_floor left two admins, admin and early-1. Moving early-1 off leaves admin as the last one. + b.assign_role(a, w.ids["early-1"], w.roles["viewer"]) + + cid, mark = str(uuid.uuid4()), "RBAC56E2E-" + uuid.uuid4().hex[:8] + channel = ET.fromstring(b.channel_xml(cid, "rbac e2e UserRoles " + cid[:8])) + script = USER_ROLES_SCRIPT + for key, value in (("@ROLE@", json.dumps(role_name)), ("@ROLE_UPPER@", json.dumps(role_name.upper())), + ("@UID@", str(uid)), ("@MARK@", json.dumps(mark))): + script = script.replace(key, value) + channel.find("deployScript").text = script + status, text = a.request("POST", "/channels", ET.tostring(channel, encoding="unicode"), accept="application/json") + saved = status in (200, 201) and "true" in text + results = {} + if saved: + status, text = b.deploy_channel(a, cid) + r.check("UserRoles: the channel that calls it deploys", status in (200, 204), f"HTTP {status}: {text[:200]}") + for _ in range(30): + lines = [line for line in w.engine.log().splitlines() if mark + " " in line] + if lines: + results = dict(part.split("=", 1) for part in lines[-1].split(mark + " ", 1)[1].split(" || ")) + break + time.sleep(1) + r.check("UserRoles: the deploy script ran and reported", saved and results and "error" not in results, + f"saved={saved} results={results}") + wanted = {"ready": "true", "names_has_role": "true", "admin": admin_role["name"], "current_before": "null", + "assign": "ASSIGNED", "assign_again": "ALREADY_ASSIGNED", "assign_missing": "NO_SUCH_ROLE", + "assign_case": "NO_SUCH_ROLE", "current_after": role_name, "last_admin": "LAST_ADMIN", + "admin_after": admin_role["name"]} + labels = {"ready": "isReady is true", "names_has_role": "roleNames lists the role", + "admin": "adminRoleName is the admin role", "current_before": "currentRoleName is null with no role", + "assign": "assign gives the role", "assign_again": "assigning it again changes nothing", + "assign_missing": "a name no role has is NO_SUCH_ROLE", + "assign_case": "the name in other letter case is NO_SUCH_ROLE", + "current_after": "currentRoleName is the new role", + "last_admin": "moving the last admin off is LAST_ADMIN", + "admin_after": "and the last admin keeps the admin role"} + for key, value in wanted.items(): + r.check("UserRoles: " + labels[key], results.get(key) == value, f"got {results.get(key)!r}") + r.check("UserRoles: the user holds the role over REST too", (b.user_role(a, uid) or {}).get("id") == rid) + expect(r, "UserRoles: right after, the same session is allowed server settings", session, "GET", + "/server/settings", (200,)) + events = [e for e in b.plugin_events(a, "rbac e2e caller") if e.get("Assigned by plugin") == "rbac e2e caller"] + r.check("UserRoles: one audit event, naming the user, the role and the plugin", + len(events) == 1 and events[0].get("User ID") == str(uid) + and events[0].get("Username") == "rbac-e2e-pluginuser" and events[0].get("Role") == role_name + and events[0].get("Action") == "Assigned", f"{events}") + + undeployed = b.undeploy_channel(a, cid)[0] if saved else None + deleted = b.delete_channel(a, cid)[0] if saved else None + restored, _ = b.assign_role(a, w.ids["early-1"], admin_role["id"]) + unassigned, _ = b.remove_role(a, uid) + gone, _ = b.delete_role(a, rid) + r.check("UserRoles: its channel, role and assignments are put back", + all(s in (200, 204) for s in (undeployed, deleted, restored, unassigned, gone)), + f"undeploy {undeployed}, delete channel {deleted}, early-1 admin again {restored}, " + f"unassign {unassigned}, delete role {gone}") + + def user_preferences(r, w): """A user's preferences: their own for any role, another user's only with manageUsers. rbac decides this itself, whatever the engine labels, and a write it refuses changes nothing. The engine asks rbac even for a user's own diff --git a/e2e/rbac.py b/e2e/rbac.py index 436b650..7df3fa5 100644 --- a/e2e/rbac.py +++ b/e2e/rbac.py @@ -280,7 +280,7 @@ def attr(value): return "".join(out) -# ---------- channels: never deployed; the checks only list, read and remove them +# ---------- channels: the checks list, read and remove them; only user_roles deploys one, for its deploy script CHANNEL_FIXTURE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "channel.xml") @@ -301,6 +301,18 @@ def create_channel(api, cid, name): return status in (200, 201) and "true" in text, f"HTTP {status} {api.reason}: {text[:200]}" +def deploy_channel(api, cid): + return api.request("POST", f"/channels/{cid}/_deploy", query={"returnErrors": "true"}, accept="application/json") + + +def undeploy_channel(api, cid): + return api.request("POST", f"/channels/{cid}/_undeploy", query={"returnErrors": "true"}, accept="application/json") + + +def delete_channel(api, cid): + return api.request("DELETE", f"/channels/{cid}", accept="application/json") + + def rename_channel(api, cid, name): """Saves the e2e channel again under a new name, keeping its id.""" status, text = api.request("PUT", f"/channels/{cid}", channel_xml(cid, name), accept="application/json", diff --git a/e2e/scenarios.py b/e2e/scenarios.py index bac45e5..e9a29e7 100644 --- a/e2e/scenarios.py +++ b/e2e/scenarios.py @@ -174,6 +174,7 @@ def fresh(r, engine, db, dbname, new_zip, **_): k.unsafe_names(r, w) k.unregistered_grant(r, w) k.orphaned_permissions(r, w) + k.user_roles(r, w) k.unknown_operations(r, engine) # Deleting an engine user: the engine tells no plugin, but it asks rbac to authorize the delete first, so diff --git a/server/src/main/java/com/diridium/rbac/AdminRoleGuard.java b/server/src/main/java/com/diridium/rbac/AdminRoleGuard.java index ba70620..5c05c31 100644 --- a/server/src/main/java/com/diridium/rbac/AdminRoleGuard.java +++ b/server/src/main/java/com/diridium/rbac/AdminRoleGuard.java @@ -38,16 +38,18 @@ *

When no admin role exists (edge case during bootstrap or after disaster), * the guard is permissive — there is no admin role to protect.

* - *

Concurrency: the floor checks are check-then-act and deliberately - * unsynchronized — they are best-effort under concurrent mutations. Defeating - * them requires two requests that each strip one of the last two admins to - * interleave within the milliseconds between the COUNT and the write, which - * no realistic admin-UI usage produces. A lock spanning validate-plus-mutate - * was considered and rejected (2026-06-12): concurrency machinery in - * security-critical code is its own mistake generator. If the race ever - * fires, recovery is a server restart — {@link AdminRoleSeeder} re-floors - * user 1 if they end up roleless. Revisit only if admins start mutating - * roles programmatically/concurrently via the REST API.

+ *

Concurrency: the floor checks for a user's role are check-then-act, + * so {@link RoleService} and {@link UserRoles} hold {@link #ROLE_CHANGES} from + * the check through the write. Two changes that each move one of the last two + * admins off the admin role then run one at a time, and the second is refused. + * A lock was considered and rejected on 2026-06-12, when only people changed + * roles, through the Administrator, with a note to revisit if roles were ever + * changed programmatically. Sign-in plugins now change roles at every sign-in, + * and a restart doesn't undo the race in their case: {@link AdminRoleSeeder} + * gives user 1 the admin role back only when user 1 has no role at all. The + * lock covers one engine, not engines sharing one database. Outside plugins + * that still call {@link RbacRepository#assignUserRole} directly don't take + * it.

* *

Validation failures throw {@link MirthApiException} with * {@link Status#BAD_REQUEST} so the admin UI can surface a clean error code @@ -55,6 +57,9 @@ */ class AdminRoleGuard { + /** Held from a floor check on a user's role through the write it allows; see the class comment. */ + static final Object ROLE_CHANGES = new Object(); + private final RbacRepository repo; private final Supplier> requiredPermissionsSupplier; @@ -157,20 +162,28 @@ void validateUserRoleRemoval(int userId) { * assignment would leave zero admins */ void validateUserRoleAssignment(int userId, int newRoleId) { - Integer adminRoleId = getAdminRoleId(); - if (adminRoleId == null) { - return; + if (leavesNoAdmin(userId, newRoleId)) { + throw badRequest("Cannot reassign the last admin user to a non-admin role; assign another admin first"); } - if (newRoleId == adminRoleId) { - return; // Becoming or staying an admin — fine + } + + /** + * Whether giving the user this role would move the last admin user off the admin role. + * + * @param userId the user whose role would change + * @param newRoleId the role the user would hold + * @return {@code true} when the user is the only user holding the admin role and the new role is another one + */ + boolean leavesNoAdmin(int userId, int newRoleId) { + Integer adminRoleId = getAdminRoleId(); + if (adminRoleId == null || newRoleId == adminRoleId) { + return false; // no admin role to protect, or becoming or staying an admin } Integer currentRoleId = repo.getUserRoleId(userId); if (currentRoleId == null || !currentRoleId.equals(adminRoleId)) { - return; // Wasn't an admin to begin with - } - if (repo.countUsersByRoleId(adminRoleId) <= 1) { - throw badRequest("Cannot reassign the last admin user to a non-admin role; assign another admin first"); + return false; // wasn't an admin to begin with } + return repo.countUsersByRoleId(adminRoleId) <= 1; } private static MirthApiException badRequest(String message) { diff --git a/server/src/main/java/com/diridium/rbac/RbacAuditLog.java b/server/src/main/java/com/diridium/rbac/RbacAuditLog.java index 6c75f6d..16e68ec 100644 --- a/server/src/main/java/com/diridium/rbac/RbacAuditLog.java +++ b/server/src/main/java/com/diridium/rbac/RbacAuditLog.java @@ -153,6 +153,24 @@ void orphanedPermissionsRemoved(String roleName, Set permissions) { dispatch(attributes); } + /** + * Dispatches an audit event for a role another plugin gave a user through {@link UserRoles}. + * + * @param userId the engine user id whose role changed + * @param username the user's name; null is recorded as {@code "(unknown)"} + * @param roleName the role the user now holds + * @param callerPlugin the name the calling plugin gave; null or blank is recorded as {@code "(not given)"} + */ + void pluginAssignment(int userId, String username, String roleName, String callerPlugin) { + Map attributes = new LinkedHashMap<>(); + attributes.put("User ID", String.valueOf(userId)); + attributes.put("Username", username != null ? username : "(unknown)"); + attributes.put("Role", roleName); + attributes.put("Assigned by plugin", callerPlugin != null && !callerPlugin.isBlank() ? callerPlugin : "(not given)"); + attributes.put("Action", "Assigned"); + dispatch(attributes); + } + private void dispatch(Map attributes) { eventController.dispatchEvent(new ServerEvent( serverId, RbacServletInterface.PLUGIN_NAME, Level.INFORMATION, Outcome.SUCCESS, attributes)); diff --git a/server/src/main/java/com/diridium/rbac/RbacAuthorizationController.java b/server/src/main/java/com/diridium/rbac/RbacAuthorizationController.java index 04c8f3b..fa86bcd 100644 --- a/server/src/main/java/com/diridium/rbac/RbacAuthorizationController.java +++ b/server/src/main/java/com/diridium/rbac/RbacAuthorizationController.java @@ -805,10 +805,11 @@ public void invalidateCache() { * unrelated users on the next request). * *

Also called by reflection from outside plugins (gibson9583/oie-oidc-auth, - * the upcoming diridium-com/oie-ldap-plugin) after they assign a role - * through {@link RbacRepository#assignUserRole(int, int)}. Keep it public, - * non-static and taking {@code Integer}; {@code ReflectionCallerContractTest} - * pins it.

+ * the upcoming diridium-com/oie-ldap-plugin) after they assign a role through + * {@link RbacRepository#assignUserRole(int, int)}. + * Keep it public, non-static and taking {@code Integer}; + * {@code ReflectionCallerContractTest} pins it. Those outside calls are + * deprecated in favour of {@link UserRoles}, which refreshes the cache itself.

* * @param userId engine user id whose cache entry should be removed; * {@code null} is silently ignored diff --git a/server/src/main/java/com/diridium/rbac/RbacRepository.java b/server/src/main/java/com/diridium/rbac/RbacRepository.java index f7dd519..9cc544c 100644 --- a/server/src/main/java/com/diridium/rbac/RbacRepository.java +++ b/server/src/main/java/com/diridium/rbac/RbacRepository.java @@ -36,8 +36,13 @@ * {@link #getUserRoleId(int)}, {@link #getAdminRoleId()}, * {@link #countUsersByRoleId(int)} and {@link #assignUserRole(int, int)}. * Renaming the class or changing those signatures breaks them without breaking - * this build; {@code ReflectionCallerContractTest} pins them. Issue #56 tracks a - * supported API to replace these calls.

+ * this build; {@code ReflectionCallerContractTest} pins them.

+ * + *

Those outside calls are deprecated: {@link UserRoles} is the supported way for + * another plugin to set a user's role, with the last-admin rule, an audit event and + * the cache refresh these calls skip. The pins stay until a later release, named in + * the release notes, ends support for the outside calls. rbac keeps using the + * methods itself.

*/ public class RbacRepository { @@ -82,6 +87,11 @@ public static RbacRepository getInstance() { return instance; } + /** The started repository, or {@code null} before {@link #init(java.util.List)} or after {@link #close()}. */ + static RbacRepository instanceIfStarted() { + return instance; + } + /** * Tears down the singleton instance. Called from {@code RbacServicePlugin.stop} * during plugin shutdown so a subsequent {@link #init(java.util.List)} starts fresh. diff --git a/server/src/main/java/com/diridium/rbac/RoleService.java b/server/src/main/java/com/diridium/rbac/RoleService.java index 28981ca..3f8f8b4 100644 --- a/server/src/main/java/com/diridium/rbac/RoleService.java +++ b/server/src/main/java/com/diridium/rbac/RoleService.java @@ -201,8 +201,10 @@ void assignUserRole(int userId, int roleId) { if (repo.getRoleById(roleId) == null) { throw new MirthApiException(Status.NOT_FOUND); } - adminGuard.validateUserRoleAssignment(userId, roleId); - repo.assignUserRole(userId, roleId); + synchronized (AdminRoleGuard.ROLE_CHANGES) { + adminGuard.validateUserRoleAssignment(userId, roleId); + repo.assignUserRole(userId, roleId); + } cacheInvalidator.run(); auditLog.assignment("Assigned", userId, roleId); } @@ -217,8 +219,10 @@ void assignUserRole(int userId, int roleId) { * if removing this user would leave zero admins */ void removeUserRole(int userId) { - adminGuard.validateUserRoleRemoval(userId); - repo.removeUserRole(userId); + synchronized (AdminRoleGuard.ROLE_CHANGES) { + adminGuard.validateUserRoleRemoval(userId); + repo.removeUserRole(userId); + } cacheInvalidator.run(); auditLog.assignment("Removed", userId, null); } diff --git a/server/src/main/java/com/diridium/rbac/UserRoles.java b/server/src/main/java/com/diridium/rbac/UserRoles.java new file mode 100644 index 0000000..e7da260 --- /dev/null +++ b/server/src/main/java/com/diridium/rbac/UserRoles.java @@ -0,0 +1,111 @@ +// SPDX-FileCopyrightText: Copyright 2026 Diridium Technologies Inc. +// SPDX-License-Identifier: MPL-2.0 + +package com.diridium.rbac; + +import java.util.List; + +import com.mirth.connect.server.controllers.AuthorizationController; +import com.mirth.connect.server.controllers.ConfigurationController; +import com.mirth.connect.server.controllers.ControllerFactory; +import com.mirth.connect.server.controllers.DefaultAuthorizationController; + +/** + * Lets another plugin set a user's role, for example from a directory's groups at sign-in. This class exists only + * for other plugins. + * + *

Call it by reflection, with no compile-time dependency on rbac: look the class up by name with + * {@code Class.forName("com.diridium.rbac.UserRoles")} and call its static methods with + * {@code getMethod(...).invoke(null, ...)}. When the class isn't found, rbac isn't installed or is older than the + * first version that has it. {@code UserRolesContractTest} pins the class name, its public methods and the codes + * {@link #assign} returns.

+ * + *

Roles are named, never numbered: role ids differ between engines, for example after a role export and + * import. Names are compared exactly, the same on every database.

+ * + *

{@link #assign} applies the rules the Administrator's Assign Role does: the last user holding the admin role is + * never moved off it, and assignments run one at a time with every other role change on this engine. It writes an audit + * event naming the calling plugin and refreshes that user's cached permissions on this engine.

+ */ +public final class UserRoles { + + /** {@link #assign}: the user now holds the role. */ + public static final String ASSIGNED = "ASSIGNED"; + /** {@link #assign}: the user already held the role; nothing changed. */ + public static final String ALREADY_ASSIGNED = "ALREADY_ASSIGNED"; + /** {@link #assign}: no role has exactly that name; nothing changed. */ + public static final String NO_SUCH_ROLE = "NO_SUCH_ROLE"; + /** {@link #assign}: the user is the last user holding the admin role and keeps it; nothing changed. */ + public static final String LAST_ADMIN = "LAST_ADMIN"; + /** {@link #assign}: rbac hasn't started, or its database tables aren't usable; nothing changed. */ + public static final String NOT_READY = "NOT_READY"; + + private UserRoles() { + } + + /** @return whether rbac has started and can read and change roles */ + public static boolean isReady() { + return MigrationStatus.isOk() && RbacRepository.instanceIfStarted() != null; + } + + /** + * @return every role's name, in the order the roles were created + * @throws IllegalStateException when rbac isn't ready + */ + public static List roleNames() { + return service().roleNames(); + } + + /** + * @return the admin role's name, or null when there is no admin role + * @throws IllegalStateException when rbac isn't ready + */ + public static String adminRoleName() { + return service().adminRoleName(); + } + + /** + * @param userId the engine user id + * @return the name of the role the user holds, or null when the user holds none + * @throws IllegalStateException when rbac isn't ready + */ + public static String currentRoleName(int userId) { + return service().currentRoleName(userId); + } + + /** + * Gives a user a role. + * + * @param userId the engine user id + * @param roleName the role's exact name + * @param callerPlugin the calling plugin's name, recorded in the audit event + * @return {@link #ASSIGNED}, {@link #ALREADY_ASSIGNED}, {@link #NO_SUCH_ROLE}, {@link #LAST_ADMIN} or + * {@link #NOT_READY} + * @throws RuntimeException on an unexpected failure, such as the database being unreachable; the role is then + * unchanged + */ + public static String assign(int userId, String roleName, String callerPlugin) { + if (!isReady()) { + return NOT_READY; + } + return service().assign(userId, roleName, callerPlugin); + } + + private static UserRolesService service() { + RbacRepository repo = RbacRepository.instanceIfStarted(); + if (repo == null || !MigrationStatus.isOk()) { + throw new IllegalStateException("Role-Based Access Control has not started"); + } + RbacAuditLog auditLog = new RbacAuditLog(ControllerFactory.getFactory().createEventController(), + ConfigurationController.getInstance().getServerId()); + return new UserRolesService(repo, new AdminRoleGuard(repo, PermissionUtil::getAllCorePermissions), auditLog, + UserRoles::refreshCachedPermissions, DeletedUserCleanup::usernameOf); + } + + private static void refreshCachedPermissions(int userId) { + AuthorizationController controller = DefaultAuthorizationController.create(); + if (controller instanceof RbacAuthorizationController) { + ((RbacAuthorizationController) controller).invalidateCache(userId); + } + } +} diff --git a/server/src/main/java/com/diridium/rbac/UserRolesService.java b/server/src/main/java/com/diridium/rbac/UserRolesService.java new file mode 100644 index 0000000..3f55502 --- /dev/null +++ b/server/src/main/java/com/diridium/rbac/UserRolesService.java @@ -0,0 +1,102 @@ +// SPDX-FileCopyrightText: Copyright 2026 Diridium Technologies Inc. +// SPDX-License-Identifier: MPL-2.0 + +package com.diridium.rbac; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.IntConsumer; +import java.util.function.IntFunction; + +/** + * What {@link UserRoles} does once rbac has started, with its collaborators passed in so it can be tested + * without an engine. Role names are compared exactly, the same on every database. + */ +class UserRolesService { + + private final RbacRepository repo; + private final AdminRoleGuard adminGuard; + private final RbacAuditLog auditLog; + private final IntConsumer userCacheInvalidator; + private final IntFunction usernameOf; + + /** + * @param repo persistence layer + * @param adminGuard the last-admin rule + * @param auditLog records the change + * @param userCacheInvalidator drops one user's cached permissions + * @param usernameOf the engine's name for a user id, for the audit event + */ + UserRolesService(RbacRepository repo, AdminRoleGuard adminGuard, RbacAuditLog auditLog, + IntConsumer userCacheInvalidator, IntFunction usernameOf) { + this.repo = repo; + this.adminGuard = adminGuard; + this.auditLog = auditLog; + this.userCacheInvalidator = userCacheInvalidator; + this.usernameOf = usernameOf; + } + + List roleNames() { + List names = new ArrayList<>(); + for (Role role : repo.getAllRoles()) { + names.add(role.getName()); + } + return names; + } + + String adminRoleName() { + return nameOf(repo.getAdminRoleId()); + } + + String currentRoleName(int userId) { + return nameOf(repo.getUserRoleId(userId)); + } + + String assign(int userId, String roleName, String callerPlugin) { + // The name lookup only reads, so it runs before the lock: a burst of sign-ins then holds the lock only for + // the user's current role, the last-admin check and the write. A role deleted in between makes the write + // fail on the foreign key to rbac_role, which throws. + Integer roleId = roleIdNamedExactly(roleName); + if (roleId == null) { + return UserRoles.NO_SUCH_ROLE; + } + // ponytail: one lock for every role change on this engine; take it only for changes to or from the admin + // role if sign-in bursts queue on it. + synchronized (AdminRoleGuard.ROLE_CHANGES) { + if (roleId.equals(repo.getUserRoleId(userId))) { + return UserRoles.ALREADY_ASSIGNED; + } + if (adminGuard.leavesNoAdmin(userId, roleId)) { + return UserRoles.LAST_ADMIN; + } + repo.assignUserRole(userId, roleId); + } + userCacheInvalidator.accept(userId); + auditLog.pluginAssignment(userId, usernameOf.apply(userId), roleName, callerPlugin); + return UserRoles.ASSIGNED; + } + + /** + * The role's id when a role has exactly this name, or null. The database lookup ignores case where the + * database's collation does (MySQL and SQL Server by default), so its answer is checked against the name. + */ + private Integer roleIdNamedExactly(String roleName) { + if (roleName == null) { + return null; + } + Integer roleId = repo.findRoleIdByName(roleName); + if (roleId == null) { + return null; + } + Role role = repo.getRoleById(roleId); + return role != null && roleName.equals(role.getName()) ? roleId : null; + } + + private String nameOf(Integer roleId) { + if (roleId == null) { + return null; + } + Role role = repo.getRoleById(roleId); + return role != null ? role.getName() : null; + } +} diff --git a/server/src/test/java/com/diridium/rbac/AdminRoleGuardTest.java b/server/src/test/java/com/diridium/rbac/AdminRoleGuardTest.java index 4f0f8d6..9a20ce6 100644 --- a/server/src/test/java/com/diridium/rbac/AdminRoleGuardTest.java +++ b/server/src/test/java/com/diridium/rbac/AdminRoleGuardTest.java @@ -4,6 +4,7 @@ package com.diridium.rbac; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -239,6 +240,24 @@ void validateUserRoleAssignment_noAdminRoleExists_passes() throws Exception { guard.validateUserRoleAssignment(1, OTHER_ROLE_ID); } + // ========== leavesNoAdmin (UserRoles asks it instead of catching the 400) ========== + + @Test + void leavesNoAdmin_onlyForTheLastAdminMovingToAnotherRole() { + when(repo.getAdminRoleId()).thenReturn(ADMIN_ROLE_ID); + when(repo.getUserRoleId(1)).thenReturn(ADMIN_ROLE_ID); + when(repo.getUserRoleId(2)).thenReturn(OTHER_ROLE_ID); + when(repo.countUsersByRoleId(ADMIN_ROLE_ID)).thenReturn(1); + assertTrue(guard.leavesNoAdmin(1, OTHER_ROLE_ID), "the last admin moving off"); + assertFalse(guard.leavesNoAdmin(1, ADMIN_ROLE_ID), "staying an admin"); + assertFalse(guard.leavesNoAdmin(2, 100), "not an admin"); + assertFalse(guard.leavesNoAdmin(99, OTHER_ROLE_ID), "no role before"); + when(repo.countUsersByRoleId(ADMIN_ROLE_ID)).thenReturn(2); + assertFalse(guard.leavesNoAdmin(1, OTHER_ROLE_ID), "another admin left"); + when(repo.getAdminRoleId()).thenReturn(null); + assertFalse(guard.leavesNoAdmin(1, OTHER_ROLE_ID), "no admin role"); + } + // ========== Helpers ========== private static Role roleWithPerms(String... perms) { diff --git a/server/src/test/java/com/diridium/rbac/RbacAuditLogTest.java b/server/src/test/java/com/diridium/rbac/RbacAuditLogTest.java index 9bb99d1..d39fa67 100644 --- a/server/src/test/java/com/diridium/rbac/RbacAuditLogTest.java +++ b/server/src/test/java/com/diridium/rbac/RbacAuditLogTest.java @@ -79,6 +79,27 @@ void assignment_nullRoleId_omittedFromAttributes() { assertEquals("Removed", attrs.get("Action")); } + @Test + void pluginAssignment_namesTheUser_theRole_andThePlugin() { + auditLog.pluginAssignment(12, "jdoe", "Billing", "OIDC Authentication"); + + Map attrs = capture().getAttributes(); + assertEquals("12", attrs.get("User ID")); + assertEquals("jdoe", attrs.get("Username")); + assertEquals("Billing", attrs.get("Role")); + assertEquals("OIDC Authentication", attrs.get("Assigned by plugin")); + assertEquals("Assigned", attrs.get("Action")); + } + + @Test + void pluginAssignment_withoutAPluginName_orUsername_saysSo() { + auditLog.pluginAssignment(12, null, "Billing", " "); + + Map attrs = capture().getAttributes(); + assertEquals("(unknown)", attrs.get("Username")); + assertEquals("(not given)", attrs.get("Assigned by plugin")); + } + @Test void role_actionUpdated() { auditLog.role("Updated", "MyRole"); diff --git a/server/src/test/java/com/diridium/rbac/ReflectionCallerContractTest.java b/server/src/test/java/com/diridium/rbac/ReflectionCallerContractTest.java index 57b5dfe..0c75143 100644 --- a/server/src/test/java/com/diridium/rbac/ReflectionCallerContractTest.java +++ b/server/src/test/java/com/diridium/rbac/ReflectionCallerContractTest.java @@ -32,8 +32,11 @@ *

The lookups mirror the callers' own: classes by name string (so a class * rename fails here), methods through {@link Class#getMethod} (so they must * stay public), with exact parameter and return types. If one of these has to - * change, coordinate with the callers first, then update this test. Issue #56 - * tracks a supported API to replace these calls. + * change, coordinate with the callers first, then update this test. + * + *

These outside calls are deprecated: {@link UserRoles} is the supported way + * (pinned by {@code UserRolesContractTest}). This test is deleted in the release + * the release notes name as the end of support for the outside calls.

*/ class ReflectionCallerContractTest { diff --git a/server/src/test/java/com/diridium/rbac/RoleChangeRaceTest.java b/server/src/test/java/com/diridium/rbac/RoleChangeRaceTest.java new file mode 100644 index 0000000..211cf56 --- /dev/null +++ b/server/src/test/java/com/diridium/rbac/RoleChangeRaceTest.java @@ -0,0 +1,126 @@ +// SPDX-FileCopyrightText: Copyright 2026 Diridium Technologies Inc. +// SPDX-License-Identifier: MPL-2.0 + +package com.diridium.rbac; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.mirth.connect.client.core.api.MirthApiException; + +/** + * Two role changes that each move one of the last two admins off the admin role, started at the same moment, run + * one at a time: one goes through and the other is refused, so one admin is left. The repository stand-in holds each admin + * count until both changes have counted or half a second has passed, so without the lock both see two admins and + * both write. + */ +class RoleChangeRaceTest { + + private static final int ADMIN_ROLE_ID = 1; + private static final int VIEWER_ROLE_ID = 7; + + private final Map assignments = new ConcurrentHashMap<>(); + private final CountDownLatch bothCounted = new CountDownLatch(2); + private RbacRepository repo; + private ExecutorService pool; + + @BeforeEach + void setUp() { + assignments.put(1, ADMIN_ROLE_ID); + assignments.put(2, ADMIN_ROLE_ID); + repo = mock(RbacRepository.class); + when(repo.getAdminRoleId()).thenReturn(ADMIN_ROLE_ID); + when(repo.getRoleById(ADMIN_ROLE_ID)).thenReturn(role(ADMIN_ROLE_ID, "Administrator")); + when(repo.getRoleById(VIEWER_ROLE_ID)).thenReturn(role(VIEWER_ROLE_ID, "Viewer")); + when(repo.findRoleIdByName("Viewer")).thenReturn(VIEWER_ROLE_ID); + when(repo.getUserRoleId(anyInt())).thenAnswer(call -> assignments.get(call.getArgument(0, Integer.class))); + when(repo.countUsersByRoleId(anyInt())).thenAnswer(call -> { + int roleId = call.getArgument(0, Integer.class); + int count = (int) assignments.values().stream().filter(r -> r == roleId).count(); + bothCounted.countDown(); + bothCounted.await(500, TimeUnit.MILLISECONDS); + return count; + }); + doAnswer(call -> assignments.put(call.getArgument(0, Integer.class), call.getArgument(1, Integer.class))) + .when(repo).assignUserRole(anyInt(), anyInt()); + pool = Executors.newFixedThreadPool(2); + } + + @AfterEach + void tearDown() { + pool.shutdownNow(); + } + + @Test + void twoSignInsDemotingTheLastTwoAdmins_leaveOneAdmin() throws Exception { + UserRolesService userRoles = userRoles(); + List outcomes = run(() -> userRoles.assign(1, "Viewer", "plugin A"), + () -> userRoles.assign(2, "Viewer", "plugin B")); + assertEquals(Set.of(UserRoles.ASSIGNED, UserRoles.LAST_ADMIN), new HashSet<>(outcomes), outcomes.toString()); + assertEquals(1, admins()); + } + + @Test + void aSignInAndTheAdministratorsAssignRole_runOneAtATimeToo() throws Exception { + UserRolesService userRoles = userRoles(); + RoleService roleService = new RoleService(repo, new AdminRoleGuard(repo, Set::of), mock(RbacAuditLog.class), + () -> { }); + List outcomes = run(() -> userRoles.assign(1, "Viewer", "plugin A"), () -> { + try { + roleService.assignUserRole(2, VIEWER_ROLE_ID); + return UserRoles.ASSIGNED; + } catch (MirthApiException refused) { + return "REFUSED"; + } + }); + assertEquals(1, admins(), outcomes.toString()); + assertEquals(1, outcomes.stream().filter(UserRoles.ASSIGNED::equals).count(), outcomes.toString()); + } + + private UserRolesService userRoles() { + return new UserRolesService(repo, new AdminRoleGuard(repo, Set::of), mock(RbacAuditLog.class), id -> { }, + id -> "user" + id); + } + + private List run(Callable first, Callable second) throws Exception { + Future a = pool.submit(first); + Future b = pool.submit(second); + List outcomes = new ArrayList<>(); + outcomes.add(a.get(10, TimeUnit.SECONDS)); + outcomes.add(b.get(10, TimeUnit.SECONDS)); + return outcomes; + } + + private long admins() { + return assignments.values().stream().filter(r -> r == ADMIN_ROLE_ID).count(); + } + + private static Role role(int id, String name) { + Role role = new Role(); + role.setId(id); + role.setName(name); + role.setPermissions(new HashSet<>()); + role.setChannelIds(new HashSet<>()); + return role; + } +} diff --git a/server/src/test/java/com/diridium/rbac/UserRolesContractTest.java b/server/src/test/java/com/diridium/rbac/UserRolesContractTest.java new file mode 100644 index 0000000..5188b04 --- /dev/null +++ b/server/src/test/java/com/diridium/rbac/UserRolesContractTest.java @@ -0,0 +1,110 @@ +// SPDX-FileCopyrightText: Copyright 2026 Diridium Technologies Inc. +// SPDX-License-Identifier: MPL-2.0 + +package com.diridium.rbac; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; + +/** + * Pins {@link UserRoles}, the supported way for another plugin to set a user's role. Plugins call it by reflection + * with no compile-time dependency on rbac, so a rename or a changed signature would not break this build; it would + * only switch off role assignment in those plugins. The lookups here are the callers' own: the class by name string, + * the methods through {@link Class#getMethod}, invoked on no instance. + * + *

The exact set of public methods is pinned too, so adding one fails this test until it is meant: every public + * method is something plugins can come to rely on. To add one, add it here and in the README's section for plugin + * authors.

+ */ +class UserRolesContractTest { + + private static final String CLASS_NAME = "com.diridium.rbac.UserRoles"; + + /** name(parameter types) to return type: every public method, all static. */ + private static final Map> METHODS = new TreeMap<>(Map.of( + "isReady()", boolean.class, + "roleNames()", List.class, + "adminRoleName()", String.class, + "currentRoleName(int)", String.class, + "assign(int,java.lang.String,java.lang.String)", String.class)); + + private static final List CODES = List.of("ASSIGNED", "ALREADY_ASSIGNED", "NO_SUCH_ROLE", "LAST_ADMIN", + "NOT_READY"); + + private static Class load() { + return assertDoesNotThrow(() -> Class.forName(CLASS_NAME, false, UserRolesContractTest.class.getClassLoader()), + CLASS_NAME + " must keep this exact name: plugins look it up by string"); + } + + @Test + void theClassKeepsItsName_isPublicFinal_andHasNoPublicConstructor() { + Class type = load(); + assertEquals(CLASS_NAME, UserRoles.class.getName()); + assertTrue(Modifier.isPublic(type.getModifiers()) && Modifier.isFinal(type.getModifiers())); + for (Constructor constructor : type.getDeclaredConstructors()) { + assertFalse(Modifier.isPublic(constructor.getModifiers()), "no public constructor: callers use the static methods"); + } + } + + @Test + void itsPublicMethods_areExactlyThese_allStatic() { + Map> found = new TreeMap<>(); + for (Method m : load().getDeclaredMethods()) { + if (!Modifier.isPublic(m.getModifiers())) { + continue; + } + assertTrue(Modifier.isStatic(m.getModifiers()), m.getName() + " must be static"); + String params = Arrays.stream(m.getParameterTypes()).map(Class::getName).collect(Collectors.joining(",")); + found.put(m.getName() + "(" + params + ")", m.getReturnType()); + } + assertEquals(METHODS, found); + } + + @Test + void theCodes_arePublicStringConstants_eachTheValueOfItsName() throws Exception { + TreeSet found = new TreeSet<>(); + for (Field f : load().getDeclaredFields()) { + int modifiers = f.getModifiers(); + if (Modifier.isPublic(modifiers)) { + assertTrue(Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers), f.getName()); + assertEquals(String.class, f.getType(), f.getName()); + assertEquals(f.getName(), f.get(null), f.getName()); + found.add(f.getName()); + } + } + assertEquals(new TreeSet<>(CODES), found); + } + + @Test + void beforeRbacStarts_isReadyIsFalse_assignIsNotReady_andTheReadsThrow() throws Exception { + RbacRepository.close(); + Class type = load(); + assertEquals(false, type.getMethod("isReady").invoke(null)); + assertEquals("NOT_READY", type.getMethod("assign", int.class, String.class, String.class) + .invoke(null, 12, "Billing", "a plugin")); + for (Method read : List.of(type.getMethod("roleNames"), type.getMethod("adminRoleName"))) { + InvocationTargetException thrown = assertThrows(InvocationTargetException.class, () -> read.invoke(null)); + assertEquals(IllegalStateException.class, thrown.getCause().getClass(), read.getName()); + } + InvocationTargetException thrown = assertThrows(InvocationTargetException.class, + () -> type.getMethod("currentRoleName", int.class).invoke(null, 12)); + assertEquals(IllegalStateException.class, thrown.getCause().getClass()); + } +} diff --git a/server/src/test/java/com/diridium/rbac/UserRolesServiceTest.java b/server/src/test/java/com/diridium/rbac/UserRolesServiceTest.java new file mode 100644 index 0000000..bc1ddb7 --- /dev/null +++ b/server/src/test/java/com/diridium/rbac/UserRolesServiceTest.java @@ -0,0 +1,140 @@ +// SPDX-FileCopyrightText: Copyright 2026 Diridium Technologies Inc. +// SPDX-License-Identifier: MPL-2.0 + +package com.diridium.rbac; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * What {@link UserRoles} does for another plugin once rbac has started: each code {@code assign} returns, the + * last-admin rule (the real {@link AdminRoleGuard}), the audit event and the one user's cache refresh. + */ +class UserRolesServiceTest { + + private static final int ADMIN_ROLE_ID = 1; + private static final int BILLING_ROLE_ID = 7; + + private RbacRepository repo; + private RbacAuditLog auditLog; + private List refreshed; + private UserRolesService service; + + @BeforeEach + void setUp() { + repo = mock(RbacRepository.class); + auditLog = mock(RbacAuditLog.class); + refreshed = new ArrayList<>(); + when(repo.getAdminRoleId()).thenReturn(ADMIN_ROLE_ID); + when(repo.getRoleById(ADMIN_ROLE_ID)).thenReturn(role(ADMIN_ROLE_ID, "Administrator")); + when(repo.getRoleById(BILLING_ROLE_ID)).thenReturn(role(BILLING_ROLE_ID, "Billing")); + when(repo.findRoleIdByName("Billing")).thenReturn(BILLING_ROLE_ID); + service = new UserRolesService(repo, new AdminRoleGuard(repo, Set::of), auditLog, refreshed::add, + id -> "user" + id); + } + + @Test + void assign_givesTheRole_refreshesThatUser_andRecordsThePlugin() { + assertEquals(UserRoles.ASSIGNED, service.assign(12, "Billing", "OIDC Authentication")); + verify(repo).assignUserRole(12, BILLING_ROLE_ID); + assertEquals(List.of(12), refreshed); + verify(auditLog).pluginAssignment(12, "user12", "Billing", "OIDC Authentication"); + } + + @Test + void assign_theRoleTheUserHolds_changesNothing() { + when(repo.getUserRoleId(12)).thenReturn(BILLING_ROLE_ID); + assertEquals(UserRoles.ALREADY_ASSIGNED, service.assign(12, "Billing", "OIDC Authentication")); + nothingChanged(); + } + + @Test + void assign_aNameNoRoleHas_changesNothing() { + assertEquals(UserRoles.NO_SUCH_ROLE, service.assign(12, "Payroll", "OIDC Authentication")); + assertEquals(UserRoles.NO_SUCH_ROLE, service.assign(12, null, "OIDC Authentication")); + nothingChanged(); + } + + @Test + void assign_aNameDifferingOnlyInCase_isNoSuchRole_whereTheDatabaseIgnoresCase() { + // MySQL and SQL Server find "Billing" for "billing"; the name must match exactly on every database. + when(repo.findRoleIdByName("billing")).thenReturn(BILLING_ROLE_ID); + assertEquals(UserRoles.NO_SUCH_ROLE, service.assign(12, "billing", "OIDC Authentication")); + nothingChanged(); + } + + @Test + void assign_movingTheLastAdminOff_leavesThemOnTheAdminRole() { + when(repo.getUserRoleId(1)).thenReturn(ADMIN_ROLE_ID); + when(repo.countUsersByRoleId(ADMIN_ROLE_ID)).thenReturn(1); + assertEquals(UserRoles.LAST_ADMIN, service.assign(1, "Billing", "OIDC Authentication")); + nothingChanged(); + } + + @Test + void assign_movingOneOfTwoAdminsOff_isAllowed() { + when(repo.getUserRoleId(1)).thenReturn(ADMIN_ROLE_ID); + when(repo.countUsersByRoleId(ADMIN_ROLE_ID)).thenReturn(2); + assertEquals(UserRoles.ASSIGNED, service.assign(1, "Billing", "OIDC Authentication")); + verify(repo).assignUserRole(1, BILLING_ROLE_ID); + } + + @Test + void assign_aDatabaseFailure_throws_andRecordsNothing() { + RbacRepositoryException failure = new RbacRepositoryException(new IllegalStateException("database down")); + when(repo.getUserRoleId(12)).thenThrow(failure); + assertEquals(failure, assertThrows(RbacRepositoryException.class, + () -> service.assign(12, "Billing", "OIDC Authentication"))); + nothingChanged(); + } + + @Test + void roleNames_listsEveryRole() { + when(repo.getAllRoles()).thenReturn(List.of(role(ADMIN_ROLE_ID, "Administrator"), role(BILLING_ROLE_ID, "Billing"))); + assertEquals(List.of("Administrator", "Billing"), service.roleNames()); + } + + @Test + void adminRoleName_isTheFlaggedRole_orNullWithoutOne() { + assertEquals("Administrator", service.adminRoleName()); + when(repo.getAdminRoleId()).thenReturn(null); + assertNull(service.adminRoleName()); + } + + @Test + void currentRoleName_isTheUsersRole_orNullWithoutOne() { + when(repo.getUserRoleId(12)).thenReturn(BILLING_ROLE_ID); + assertEquals("Billing", service.currentRoleName(12)); + assertNull(service.currentRoleName(13)); + } + + private void nothingChanged() { + verify(repo, never()).assignUserRole(anyInt(), anyInt()); + assertEquals(List.of(), refreshed); + verify(auditLog, never()).pluginAssignment(anyInt(), any(), any(), any()); + } + + private static Role role(int id, String name) { + Role role = new Role(); + role.setId(id); + role.setName(name); + role.setPermissions(new HashSet<>()); + role.setChannelIds(new HashSet<>()); + return role; + } +}