Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,8 @@ jobs:
- name: Require a green Build run on the tagged commit
run: |
n="$(gh api "repos/${GH_REPO}/actions/workflows/build.yml/runs?head_sha=${GITHUB_SHA}&branch=main&event=push&status=success&per_page=1" -q .total_count)"
if [ "$n" -lt 1 ]; then
echo "::error::No successful Build run for ${GITHUB_SHA}. Merge it to main, wait for Build, then tag."
if ! [ "$n" -ge 1 ] 2>/dev/null; then
echo "::error::No successful Build run on main for ${GITHUB_SHA} (count: ${n}). If the commit is on main, wait for its Build run to pass, then re-run this job."
exit 1
fi
echo "Build passed on ${GITHUB_SHA}"
Expand Down
8 changes: 4 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Output: `package/target/rbac-1.4.0.zip`
- Cache: `ConcurrentHashMap<userId, UserAuthCache>` 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`; an unknown user id throws `IllegalArgumentException`; other 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.
- `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`; an unknown user id throws `IllegalArgumentException` (a Java caller using reflection gets the exception as the cause of an `InvocationTargetException`; a Rhino script gets it unwrapped); other 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 the test lists it. 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`.

Expand All @@ -61,7 +61,7 @@ Output: `package/target/rbac-1.4.0.zip`
- The export and import flows live in `RoleTransferActions`, `RoleExportDialog`, `RoleImportDialog` and `RoleImportText` (wording, default ticks; web twin in `rbac-core.js`). The file is written as plain UTF-8, never through `Frame.exportFile`, which encrypts when export encryption is on; `RoleImportFile` reads an import file, refusing one over 5 MB or not in UTF-8 before anything is sent

### Database
- 4 tables: `rbac_role`, `rbac_role_permission`, `rbac_role_channel`, `rbac_user_role`. Schema version 4 (`RbacMigrator`, `MIGRATIONS.md`): `rbac_role.restricted` says whether the role sees only its `rbac_role_channel` rows (possibly none, which is "no channels") or every channel. Before v4 an empty list meant every channel; v4 sets the flag for every role that had rows. `RoleService` stores a role sent with channels but no flag as restricted (older REST callers). `RbacChannelPlugin` (a `ChannelPlugin` listed in plugin.xml's server classes, the pattern simple-channel-history uses) is called by the engine inside a channel delete and removes every restriction row naming that channel at that moment, logging each role; `DeletedChannelSweep` runs at startup after the migration check for channels deleted while rbac wasn't loaded (one delete per row, skipped if the channel list can't be read or comes back empty while restriction rows exist). Both leave the role restricted, so nothing widens, and rbac's tables don't keep restrictions to deleted channels (owner's rule, 2026-11-04; a REST caller can still store an id the engine lacks, which the next start's sweep removes). Since #53 an import's detail table still has a row for a channel id the role holds that the engine doesn't have ("(no longer exists)", found "deleted on this engine"), which only a REST caller can leave, until the next start's sweep
- 4 tables: `rbac_role`, `rbac_role_permission`, `rbac_role_channel`, `rbac_user_role`. Schema version 4 (`RbacMigrator`, `MIGRATIONS.md`): `rbac_role.restricted` says whether the role sees only its `rbac_role_channel` rows (possibly none, which is "no channels") or every channel. Before v4 an empty list meant every channel; v4 sets the flag for every role that had rows. `RoleService` stores a role sent with channels but no flag as restricted (older REST callers). `RbacChannelPlugin` (a `ChannelPlugin` listed in plugin.xml's server classes, the pattern simple-channel-history uses) is called by the engine inside a channel delete and removes every restriction row naming that channel at that moment, logging each role; `DeletedChannelSweep` runs at startup after the migration check for channels deleted while rbac wasn't loaded (one delete per row, skipped if the channel list can't be read or comes back empty while restriction rows exist). Both leave the role restricted, so nothing widens, and rbac's tables don't keep restrictions to deleted channels (owner's rule, 2026-11-04; a REST caller can still store an id the engine lacks, which the next start's sweep removes). Since rbac PR #53, an import's detail table can show a channel id that the role has and the import names but the engine doesn't have: the row reads "(no longer exists)", found "deleted on this engine". Only a REST caller can leave such an id, and the next start's sweep removes it
- MyBatis mapped statements in `sqlmap.xml` (namespace: `Rbac`, key: `all` = DB-agnostic)
- Pattern: `SqlConfig.getInstance().getSqlSessionManager().selectList(stmt("statementId"), params)`
- NEVER use raw JDBC (Connection, PreparedStatement, ResultSet)
Expand All @@ -71,7 +71,7 @@ Output: `package/target/rbac-1.4.0.zip`
### REST API
- Path: `/extensions/rbac`
- Roles: GET/POST `/roles`, GET/PUT/DELETE `/roles/{roleId}`
- Users: GET `/users/{userId}/role`, POST `/users/{userId}/role/{roleId}`, DELETE `/users/{userId}/role`
- Users: GET `/users/{userId}/role`, POST `/users/{userId}/role/{roleId}` (404 for a role or a user the engine doesn't have), DELETE `/users/{userId}/role`
- Permissions: GET `/permissions` (all available), GET `/my-permissions` (current user's granted permissions), GET `/permissions/extensions` (extension permission → publishing plugin, for the role editors' per-plugin headers), GET `/task-permissions` (extension task → permission, whitelisted for all users)
- Export/import: GET `/roles/_export?roleId=` (the file, `text/plain`), POST `/roles/_import?dryRun=&applyChannels=&matchChannelsByName=&pick=&planToken=` (the file as a `text/plain` body; preview, then apply the picked roles in one transaction). Format and rules: `docs/role-export-format.md`
- Orphaned permissions: GET `/roles/_unregistered` (the grants no installed plugin registers, never the engine's own, and the names of the disabled plugins), POST `/roles/_unregistered/_remove` (the picked grants, each checked again; one transaction)
Expand Down Expand Up @@ -99,7 +99,7 @@ Output: `package/target/rbac-1.4.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). 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 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, and neither does a user delete (the engine deletes the user after rbac's last-admin check allows it). 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`.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ Its static methods:
- `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. `assign` throws `IllegalArgumentException` when no engine user has that id, and changes nothing. 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.
`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. `assign` throws `IllegalArgumentException` when no engine user has that id, and changes nothing. 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. A Java caller using reflection gets these exceptions as the cause of an `InvocationTargetException`.

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.

Expand Down
2 changes: 1 addition & 1 deletion RELEASING.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ When the engine version the plugin is built for (`plugin.supported.mc.versions`

## 2. Tag

Tag a commit on `main` whose Build workflow has passed on the push to `main`. The release job refuses a tag without one.
Tag a commit on `main` whose Build workflow has passed on the push to `main`. The release job refuses a tag without one. A tag pushed while that Build run is still going is refused too: once it passes, re-run the failed Release job; the tag stays as it is.

```bash
git tag vX.Y.Z && git push origin vX.Y.Z
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,8 @@ private static RbacServletInterface rbac(Frame parent) {

/**
* Runs {@code call} off the event thread, then {@code onSuccess} on it; a failure is shown over {@code owner},
* then {@code onFailure} runs, when given.
* then {@code onFailure} runs, when given. {@code onFailure} also runs when {@code onSuccess} or the report
* throws, so a guard the caller set is always cleared.
*/
private static <T> void background(Frame parent, Component owner, Callable<T> call, Consumer<T> onSuccess,
Runnable onFailure) {
Expand All @@ -198,20 +199,20 @@ protected T doInBackground() throws Exception {

@Override
protected void done() {
boolean succeeded = false;
try {
onSuccess.accept(get());
succeeded = true;
} catch (ExecutionException e) {
if (e.getCause() instanceof ClientException) {
RoleTransferActions.report(parent, owner, (ClientException) e.getCause());
} else {
parent.alertThrowable(owner, e.getCause() != null ? e.getCause() : e);
}
if (onFailure != null) {
onFailure.run();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
if (onFailure != null) {
} finally {
if (!succeeded && onFailure != null) {
onFailure.run();
}
}
Expand Down
22 changes: 14 additions & 8 deletions client/src/main/java/com/diridium/rbac/RoleTransferActions.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,9 @@ class RoleTransferActions {
this.channelMap = channelMap;
}

// Set while the roles load for the export dialog, so a second press opens no second dialog.
private boolean exporting;
// Set while an export or import waits on the server (the roles load, the export file, the import preview), so a
// second press of Export Roles or Import Roles starts nothing. Cleared when the call returns, before any dialog.
private boolean busy;

private RbacServletInterface rbac() {
return parent.mirthClient.getServlet(RbacServletInterface.class);
Expand All @@ -64,10 +65,10 @@ private RbacServletInterface rbac() {
// ========== Export ==========

void exportRoles() {
if (exporting) {
return; // a second press while the roles load
if (busy) {
return;
}
exporting = true;
busy = true;
background(() -> rbac().getRoles(), roles -> {
List<Role> exportable = new ArrayList<>();
for (Role role : roles) {
Expand All @@ -85,10 +86,11 @@ void exportRoles() {
if (ids != null) {
fetchAndSave(ids);
}
}, () -> exporting = false);
}, () -> busy = false);
}

private void fetchAndSave(List<Integer> ids) {
busy = true;
background(() -> rbac().exportRoles(new HashSet<>(ids)), text -> {
File file = parent.createFileForExport(DEFAULT_FILE_NAME, "XML");
if (file == null) {
Expand All @@ -102,12 +104,15 @@ private void fetchAndSave(List<Integer> ids) {
return;
}
parent.alertInformation(parent, "Exported " + ids.size() + " role(s).");
});
}, () -> busy = false);
}

// ========== Import ==========

void importRoles() {
if (busy) {
return;
}
File file = parent.browseForFile("XML");
if (file == null) {
return;
Expand Down Expand Up @@ -137,6 +142,7 @@ public RoleImportResult apply(List<Integer> pick, String planToken, boolean appl
return rbac().importRoles(fileText, false, applyChannels, matchChannelsByName, pick, planToken);
}
};
busy = true;
background(() -> backend.preview(true, false), first -> {
if (!first.isImportable()) {
parent.alertError(parent, "This file can't be imported: " + first.getRefusal());
Expand All @@ -148,7 +154,7 @@ public RoleImportResult apply(List<Integer> pick, String planToken, boolean appl
parent.alertInformation(parent, "Imported " + dialog.getImportedCount() + " role(s).");
refreshPanel.run();
}
});
}, () -> busy = false);
}

// ========== Shared ==========
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ void nameMatchHint_followsTheSettingsOfThePreviewShown() {
}

@Test
void previewAgainAfter_onlyAFailureTheServerAnswered() {
void previewAgainAfter_onlyA400Or409WithTheServersMessage() {
assertTrue(RoleImportText.previewAgainAfter(new ClientException("Method failed: HTTP/1.1 409 Conflict",
new EntityException("The roles changed since the preview. Preview the import again."))));
assertFalse(RoleImportText.previewAgainAfter(
Expand Down
Loading
Loading