From 3ac59c6b158bce603de22d656720fe9dd051e6ff Mon Sep 17 00:00:00 2001 From: Finnegan's Owner <44065187+pacmano1@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:56:56 -0700 Subject: [PATCH] Fix nits from the 1.4.0 release review rbac PR #75 fixed what the first 1.4.0 release review found. A second review, of PR #75, found no blocker and 31 small findings. This fixes 28 of them. The other three: - Import refusal messages show a backslash in a role name doubled. Left as is; docs/design-notes.md says why. - Splitting SecureAuthorizationController joins the splits of RbacAuthorizationController, RbacRepository, RoleEditorDialog and e2e/checks.py planned for the next release. - Not done: an optional probe of whether the e2e suite can read Derby's schema version over REST after an uninstall. Changes: - Assign Role over REST (POST /api/extensions/rbac/users/{id}/role/{roleId}) answers 404, with a message, for a user id the engine doesn't have, as UserRoles.assign refuses one. - Three web changes match what Swing already does: after a failed import apply, the web previews again only on a 400 or 409, so a 403 shows its error once; the Orphaned Permissions dialog can't be closed during a removal; and the role editor counts a field edited back to its first shown text as unedited. - Swing: Import Roles and the export download can't be started twice. The Orphaned Permissions dialog always clears its guards, so an exception can't leave it stuck open. - The release job's check that Build passed on main refuses an answer that isn't a number, and its message says to re-run the job once Build passes. RELEASING.md says the same. - Tests: LogNameEscapingTest matches each quoted placeholder to its argument, and SqlStatementIdCoverageTest reads the statement ids from the sources. New tests cover a failure reading the permission labels at startup, the REST 404, the import's skip of the admin role, the web's rule for previewing again, the web's edited-back field, the Swing permission-load guard, a 403 on apply and the dialog during a removal. The browser test for an unedited description with a line break now fails on the old code. - e2e: UserRoles.assign with an unknown user id, the REST 404, and a NOTE with the number of permission labels rbac read at startup. The UserRoles check stops before its channel script if another admin couldn't be moved off the admin role. - Docs: the README says a Java caller using reflection gets UserRoles' exceptions as the cause of an InvocationTargetException. Comments and test names list all three admin-only tasks: Export Roles, Import Roles and Orphaned Permissions. CLAUDE.md gains the full condition for the "(no longer exists)" row of the import preview's channel table, the REST 404, and that a user delete doesn't take the role-change lock. A new entry in docs/design-notes.md corrects what the previous one said about the web editor and line breaks, and says what has no automated test. - Small: a misplaced Javadoc, the --label-as help text and a docstring in e2e/run.py, a test name, an indent, a blank line. Tested on this branch: the unit tests (shared 11, server 398, client 110, web 151), the browser suite against web client 1.3.0 and 1.1.0 (92 tests each), and the e2e suite on OIE 4.7.0 with Derby, MySQL, PostgreSQL, Oracle and SQL Server (jTDS and Microsoft drivers), with no failures. The new UserRoles check first failed on every database: its script looked for the exception's cause, and Rhino unwraps the InvocationTargetException that Method.invoke throws. With the script fixed, I ran the fresh scenario again on all six. Controls: with eight fixes undone at once, only the new unit test of each fails. With three web fixes undone, the three new browser tests fail (the 403 on apply, the dialog during a removal, the line break). With the user-exists check wired to accept any id in both the REST call and UserRoles, the three new e2e checks of an unknown user fail. In the Swing Administrator on OIE 4.7.0, Export Roles, Import Roles and Orphaned Permissions each open again when pressed a second time, and a removal keeps Close off until the list reloads. Co-Authored-By: Claude --- .github/workflows/release.yml | 4 +- CLAUDE.md | 8 +- README.md | 2 +- RELEASING.md | 2 +- .../rbac/OrphanedPermissionsDialog.java | 11 +- .../diridium/rbac/RoleTransferActions.java | 22 ++-- .../com/diridium/rbac/RoleImportTextTest.java | 2 +- .../SecureAuthorizationControllerTest.java | 25 +++- docs/design-notes.md | 29 +++++ e2e/checks.py | 53 +++++++-- e2e/run.py | 7 +- .../rbac/RbacAuthorizationController.java | 12 +- .../java/com/diridium/rbac/RbacServlet.java | 2 +- .../java/com/diridium/rbac/RoleService.java | 17 ++- .../java/com/diridium/rbac/UserRoles.java | 3 +- .../diridium/rbac/LogNameEscapingTest.java | 108 ++++++++++++------ .../rbac/RbacAuthorizationControllerTest.java | 19 +++ .../com/diridium/rbac/RoleChangeRaceTest.java | 4 +- .../diridium/rbac/RoleImportPlannerTest.java | 6 + .../com/diridium/rbac/RoleServiceTest.java | 16 ++- .../rbac/SqlStatementIdCoverageTest.java | 40 ++++--- webadmin/e2e/orphaned-permissions.spec.js | 26 ++++- webadmin/e2e/role-editor.spec.js | 5 +- webadmin/e2e/role-transfer.spec.js | 23 ++++ webadmin/web/authorization-session.test.mjs | 9 +- webadmin/web/name-characters.test.mjs | 3 +- webadmin/web/orphaned-permissions.jsx | 4 +- webadmin/web/rbac-core.js | 8 +- webadmin/web/role-import-dialog.jsx | 8 +- webadmin/web/role-transfer-core.js | 7 ++ webadmin/web/role-transfer.test.mjs | 11 +- webadmin/web/roles-panel.jsx | 5 +- 32 files changed, 384 insertions(+), 117 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 046abae..dbb7bf8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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}" diff --git a/CLAUDE.md b/CLAUDE.md index 156de97..29bcb04 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -44,7 +44,7 @@ Output: `package/target/rbac-1.4.0.zip` - 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`; 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`. @@ -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) @@ -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) @@ -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`. diff --git a/README.md b/README.md index 10dc5c2..8f00d73 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/RELEASING.md b/RELEASING.md index d4c4045..31a4def 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -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 diff --git a/client/src/main/java/com/diridium/rbac/OrphanedPermissionsDialog.java b/client/src/main/java/com/diridium/rbac/OrphanedPermissionsDialog.java index b51e7c9..8223a43 100644 --- a/client/src/main/java/com/diridium/rbac/OrphanedPermissionsDialog.java +++ b/client/src/main/java/com/diridium/rbac/OrphanedPermissionsDialog.java @@ -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 void background(Frame parent, Component owner, Callable call, Consumer onSuccess, Runnable onFailure) { @@ -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(); } } diff --git a/client/src/main/java/com/diridium/rbac/RoleTransferActions.java b/client/src/main/java/com/diridium/rbac/RoleTransferActions.java index e3f9aac..ac94602 100644 --- a/client/src/main/java/com/diridium/rbac/RoleTransferActions.java +++ b/client/src/main/java/com/diridium/rbac/RoleTransferActions.java @@ -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); @@ -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 exportable = new ArrayList<>(); for (Role role : roles) { @@ -85,10 +86,11 @@ void exportRoles() { if (ids != null) { fetchAndSave(ids); } - }, () -> exporting = false); + }, () -> busy = false); } private void fetchAndSave(List ids) { + busy = true; background(() -> rbac().exportRoles(new HashSet<>(ids)), text -> { File file = parent.createFileForExport(DEFAULT_FILE_NAME, "XML"); if (file == null) { @@ -102,12 +104,15 @@ private void fetchAndSave(List 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; @@ -137,6 +142,7 @@ public RoleImportResult apply(List 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()); @@ -148,7 +154,7 @@ public RoleImportResult apply(List pick, String planToken, boolean appl parent.alertInformation(parent, "Imported " + dialog.getImportedCount() + " role(s)."); refreshPanel.run(); } - }); + }, () -> busy = false); } // ========== Shared ========== diff --git a/client/src/test/java/com/diridium/rbac/RoleImportTextTest.java b/client/src/test/java/com/diridium/rbac/RoleImportTextTest.java index 33ce9a5..6a49d1c 100644 --- a/client/src/test/java/com/diridium/rbac/RoleImportTextTest.java +++ b/client/src/test/java/com/diridium/rbac/RoleImportTextTest.java @@ -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( diff --git a/client/src/test/java/com/mirth/connect/plugins/auth/client/SecureAuthorizationControllerTest.java b/client/src/test/java/com/mirth/connect/plugins/auth/client/SecureAuthorizationControllerTest.java index d497dc4..400d7df 100644 --- a/client/src/test/java/com/mirth/connect/plugins/auth/client/SecureAuthorizationControllerTest.java +++ b/client/src/test/java/com/mirth/connect/plugins/auth/client/SecureAuthorizationControllerTest.java @@ -294,7 +294,7 @@ void mergeExtensionTaskPermissions_nullOrEmpty_isNoop() throws Exception { private static final String RBAC_GROUP = TaskConstants.SETTINGS_KEY_PREFIX + "Role-Based Access Control"; @Test - void checkTask_exportAndImportRoles_followTheAdminFlag() throws Exception { + void checkTask_theAdminOnlyTasks_followTheAdminFlag() throws Exception { SecureAuthorizationController admin = withPermissions(Set.of(RbacServletInterface.PERMISSION_VIEW)); setField(admin, "adminRole", true); assertTrue(admin.checkTask(RBAC_GROUP, "doExportRoles")); @@ -476,6 +476,29 @@ void loadPermissions_publishesThePermissionsAfterTheMapsAndTheAdminFlag() throws assertFalse(c.checkTask("settings_Foo Plugin", "doRefresh"), "the extension map was merged"); } + @Test + void aLoadStartedWhileOneRuns_returnsAtOnce_andTheFirstLoadFinishes() { + SecureAuthorizationController c = new SecureAuthorizationController(); + AtomicInteger loads = new AtomicInteger(); + c.servlet = () -> rbac(method -> { + switch (method) { + case "getMyPermissions": + if (loads.incrementAndGet() == 1) { + c.initialize(); // a second load, arriving while this one runs + } + return Set.of("viewChannels"); + case "getExtensionTaskPermissions": + return Map.of(); + default: + throw new UnsupportedOperationException(method); + } + }); + c.currentUserId = () -> 1; + c.initialize(); + assertEquals(1, loads.get(), "the load that arrived meanwhile sent no second request"); + assertTrue(c.checkTask("group", TaskConstants.VIEW_CHANNEL)); + } + // ========== Helpers ========== /** Answers a call by the method's name; a stand-in for the RBAC servlet. */ diff --git a/docs/design-notes.md b/docs/design-notes.md index fe16c6e..f9d7b1a 100644 --- a/docs/design-notes.md +++ b/docs/design-notes.md @@ -326,3 +326,32 @@ OIDC's direct calls keep working. Going by its code, if they stopped working, OI - A race test for Remove Role, beside the existing `twoSignInsDemotingTheLastTwoAdmins_leaveOneAdmin` and `aSignInAndTheAdministratorsAssignRole_runOneAtATimeToo`. - Browser tests: a description with a line break kept when only the name is edited, and the roles list read again after an orphaned permission is removed. - The e2e suite: the startup line above, the two preference calls it didn't check (writing all of a user's preferences at once, and acknowledging the login notification) for a user's own account and another user's, and on Derby no uninstall check of the schema version, which the suite can't read from the embedded database. + +## 2026-12-01: fixes from the second 1.4.0 review + +**Correction to the 2026-11-30 entry: the web role editor never lost a line break in the middle of a value.** The web editor saves the value in its state, which is the stored value until the field is edited; the text input only displays it. The browser test that entry lists passed with the old code (measured). What the web change did: an unedited value is no longer trimmed, so its leading and trailing spaces and line breaks are kept, and an edited one is trimmed as Java's `String.trim()` does. The browser test now uses a description ending in a line break, which the old code dropped. That entry also says typing the same text in either editor saves the same name. That isn't true for a value with a line break: after an edit, the Swing field has turned the line break into a space, and the web field has dropped it. + +**The web editor counts a field edited back to its first shown text as unedited, as Swing does.** A text input drops line breaks, so the web also compares the field with the stored value without them. A user who edits such a name and then types back exactly what the field showed saves the stored name, line break included. + +**The "(no longer exists)" row needs one more condition than the 2026-11-30 entry gives:** the import names that channel id too. A channel id the role has and the import doesn't name shows its id, found "not in the import". + +**REST Assign Role answers 404 for a user id the engine doesn't have,** with the message "No engine user has the id N.", as `UserRoles.assign` refuses one. A row for such an id would give the role to a user the engine created later with that id. + +**Import refusal messages show the role name through `forLog`, so a backslash shows doubled.** When the import refuses a name for a control character, the escaping is what makes that character visible in the message. The doubled backslash keeps a name containing the two characters `\n` distinct from one containing a line break. + +**The web import previews again only after a 400 or 409, as Swing does.** A 403 or a lost connection would fail the preview too and show the same error twice. The web Orphaned Permissions dialog can't be closed during a removal, as Swing's can't. + +**Swing: Import Roles and the export download are guarded against a second press too, and the Orphaned Permissions dialog always clears its guards.** One flag covers any export or import call in flight. If anything goes wrong after the dialog's server call returns, it now runs its failure path, which clears the guards, so an exception can't leave the dialog stuck open or the task unresponsive until the Administrator restarts. + +**The release gate fails closed if GitHub's answer isn't a number,** and its refusal says to re-run the job once the Build run on main passes, as RELEASING.md now does. + +### Tests + +- `LogNameEscapingTest` matches each quoted placeholder to its argument by position, and `SqlStatementIdCoverageTest` reads the statement ids from the sources. +- Unit tests for the label-read failure, the REST 404, the import's admin-role skip, the web retry rule, the web's edited-back field, and the Swing permission-load guard. +- Browser tests: a 403 on apply sends no second preview, Close is off while a removal runs, and the line-break test as above. +- The e2e suite: `UserRoles.assign` with a user id the engine doesn't have throws `IllegalArgumentException`, and the REST call answers 404 and stores nothing. The `UserRoles` check stops before its channel script if another admin couldn't be moved off the admin role. The suite writes the number of labels read in a note. + +### Not covered + +- rbac's CI has no Swing UI tests. The Swing changes of both 1.4.0 reviews are covered by unit tests only where they don't need a window (the saved-text rule, the refusal messages, the permission-load guard). The dialog and task guards, and the Swing role editor's comparison with the text its fields showed when it opened, were clicked through on OIE 4.7.0, not tested in CI. diff --git a/e2e/checks.py b/e2e/checks.py index 46cc60f..ae9fb40 100644 --- a/e2e/checks.py +++ b/e2e/checks.py @@ -98,7 +98,7 @@ def role_crud(r, w): r.check("a created role reads back with its permissions and channels", got.get("permissions") == perms and got.get("channelIds") == {chans["A"], chans["B"]}, str(got)) r.check("a created role reads back with its name, characters outside Latin-1 included", - got.get("name") == name, repr(got.get("name"))) + got.get("name") == name, repr(got.get("name"))) status, _ = b.post_role(a, b.role_xml(name, ["viewChannels"])) r.check("a second role with the same name is refused (409)", status == 409, f"HTTP {status} {a.reason}") new_perms = {"viewChannels", "manageChannels"} @@ -333,11 +333,14 @@ def labelled_operations(r, w): without the label's permission. Each refusal check passes in either case and fails on anything else. The connector call and getProperty must be both one or both the other: a mix means rbac read the core labels but not the connector ones (or the reverse). A note says which the engine is. Calls a role is allowed in both cases - are plain checks. A user's preferences are checked in user_preferences: rbac decides those itself.""" + are plain checks. A user's preferences are checked in user_preferences: rbac decides those itself. First, the + labels rbac read at startup: more than none, how many in a note, and no extension whose labels failed to read.""" log = w.engine.log() counts = [int(n) for n in re.findall(r"Read (\d+) permission labels from the extensions' registered servlet", log)] - r.check("the label reader read the extensions' labels at startup (OIE 4.7.0's bundled plugins have 11)", - bool(counts) and counts[-1] > 0, f"counts logged: {counts}") + r.check("rbac read the extensions' permission labels at startup", bool(counts) and counts[-1] > 0, + f"counts logged: {counts}") + if counts: + r.note("permission labels read at startup", str(counts[-1])) r.check("no extension's labels failed to read", "could not read the permission labels" not in log.lower(), "see mirth.log") viewer, editor, every, norole = (w.users[k] for k in ("viewer", "channel-a", "every-permission", "no-role")) @@ -476,7 +479,9 @@ def orphaned_permissions(r, w): # 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. +# each call returned on one line. @ROLE@, @ROLE_UPPER@, @UID@, @NO_USER@ and @MARK@ are filled in by user_roles. +# Rhino unwraps the InvocationTargetException Method.invoke throws (measured on OIE 4.7.0), so the script sees the +# exception assign threw; a Java caller gets it as that InvocationTargetException's cause. USER_ROLES_SCRIPT = r"""var out = []; function put(key, value) { out.push(key + '=' + value); @@ -500,6 +505,16 @@ def orphaned_permissions(r, w): 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@))); + try { + assign.invoke(null, n(@NO_USER@), @ROLE@, plugin); + put('assign_unknown', 'no exception'); + } catch (x) { + var thrown = x.javaException; + if (thrown instanceof java.lang.reflect.InvocationTargetException) { + thrown = thrown.getCause(); + } + put('assign_unknown', thrown ? thrown.getClass().getName() : String(x)); + } put('last_admin', assign.invoke(null, n(1), @ROLE@, plugin)); put('admin_after', current.invoke(null, n(1))); } catch (e) { @@ -519,22 +534,35 @@ def user_roles(r, w): rid = b.create_role(a, role_name, ["viewDashboard", "viewChannels", "viewServerSettings"]) session = add_user(w, "pluginuser") uid = w.ids["pluginuser"] + no_user = "987654321" expect(r, "UserRoles: before, the user with no role is refused server settings", session, "GET", "/server/settings", (403,)) + expect(r, "REST: assigning a role to a user id the engine doesn't have is refused (404)", a, "POST", + f"{b.RBAC}/users/{no_user}/role/{rid}", (404,)) + r.check("REST: and no assignment is stored for it", b.user_role(a, no_user) is None, + f"{b.user_role(a, no_user)}") admin_role = b.user_role(a, "1") # Leave admin as the last user holding the admin role, so the script's assign(1, ...) meets the last-admin rule; # the others are put back afterwards. - others = [uid for uid in sorted(set(w.ids.values()) - {"1"}) - if (b.user_role(a, uid) or {}).get("id") == admin_role["id"]] - moved = [b.assign_role(a, uid, w.roles["viewer"])[0] for uid in others] + others = [other for other in sorted(set(w.ids.values()) - {"1"}) + if (b.user_role(a, other) or {}).get("id") == admin_role["id"]] + moved = [b.assign_role(a, other, w.roles["viewer"])[0] for other in others] r.check("UserRoles: every other admin moved off for the last-admin case", all(s in (200, 204) for s in moved), f"other admins {others}, HTTP {moved}") + if not all(s in (200, 204) for s in moved): + # With another admin left, the script's assign(1, ...) would move admin itself off the admin role, and every + # later check in this scenario would fail for that reason. Put back what moved and stop here. + for other, status in zip(others, moved): + if status in (200, 204): + b.assign_role(a, other, admin_role["id"]) + b.delete_role(a, rid) + return 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))): + ("@UID@", str(uid)), ("@NO_USER@", no_user), ("@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") @@ -553,7 +581,8 @@ def user_roles(r, w): 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", + "assign_case": "NO_SUCH_ROLE", "current_after": role_name, + "assign_unknown": "java.lang.IllegalArgumentException", "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", @@ -561,6 +590,7 @@ def user_roles(r, w): "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", + "assign_unknown": "a user id the engine doesn't have throws IllegalArgumentException", "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(): @@ -576,7 +606,7 @@ def user_roles(r, w): 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, uid, admin_role["id"])[0] for uid in others] + restored = [b.assign_role(a, other, admin_role["id"])[0] for other in others] unassigned, _ = b.remove_role(a, uid) gone, _ = b.delete_role(a, rid) r.check("UserRoles: its channel, role and assignments are put back", @@ -611,6 +641,7 @@ def user_preferences(r, w): # The other two preference calls: all of a user's preferences at once (the body sent back as read), and the # login notification's acknowledgement. status, mine = viewer.request("GET", f"/users/{own}/preferences") + r.check("preferences: read-only reads all its preferences to send back", status == 200, f"HTTP {status}") expect(r, "preferences: read-only writes its own preferences at once", viewer, "PUT", f"/users/{own}/preferences", (200, 204), body=mine) expect(r, "preferences: read-only is refused writing another user's preferences at once", viewer, "PUT", diff --git a/e2e/run.py b/e2e/run.py index 04c1e3c..56d6cee 100644 --- a/e2e/run.py +++ b/e2e/run.py @@ -89,7 +89,7 @@ def main(): parser.add_argument("--work", required=True, help="a directory that does not exist yet") parser.add_argument("--java-home", default=os.environ.get("JAVA_HOME")) parser.add_argument("--scenarios", default="all", help="comma separated: fresh, upgrade-, uninstall") - parser.add_argument("--label-as", help="install the zips relabelled for this engine version") + parser.add_argument("--label-as", help="install a copy of the zip under test relabelled for this engine version") parser.add_argument("--keep-engines", action="store_true", help="keep every scenario's engine copy; without it a passed scenario keeps only its logs") args = parser.parse_args() @@ -112,9 +112,8 @@ def main(): relabelled = [] def labelled(zip_path, role): - """The zip itself, or with --label-as a copy relabelled for that engine version. Each copy is named for - its role, and relabel() refuses to overwrite, so an older release with the same file name as the zip - under test can never replace it.""" + """The zip itself, or for the zip under test with --label-as, a copy relabelled for that engine version. + relabel() refuses to overwrite, so nothing already in the work folder can stand in for the copy.""" built_for = mirth_version(zip_path) # Only the zip under test is relabelled: an older release in an upgrade scenario runs on the engine it # was built for (e2e/engines.txt), so relabelling it would skip the engine upgrade the scenario tests. diff --git a/server/src/main/java/com/diridium/rbac/RbacAuthorizationController.java b/server/src/main/java/com/diridium/rbac/RbacAuthorizationController.java index 9288c33..bb2a8a1 100644 --- a/server/src/main/java/com/diridium/rbac/RbacAuthorizationController.java +++ b/server/src/main/java/com/diridium/rbac/RbacAuthorizationController.java @@ -515,12 +515,6 @@ private boolean wouldRemoveLastAdmin(Map parameterMap) { * @param operationName the runtime operation name, {@code #} * @return the permission to require, or {@code null} for none */ - /** Whether a role can be granted this permission: a core permission, or one an installed plugin registers. */ - private boolean isGrantable(String permission) { - return corePermissions.contains(permission) || extensionPermissionToPlugin.containsKey(permission) - || extensionOperationToPermission.containsValue(permission); - } - private String enforceableLabel(String operationName) { String label = labelledOperationToPermission.get(operationName); if (label == null) { @@ -534,6 +528,12 @@ private String enforceableLabel(String operationName) { return null; } + /** Whether a role can be granted this permission: a core permission, or one an installed plugin registers. */ + private boolean isGrantable(String permission) { + return corePermissions.contains(permission) || extensionPermissionToPlugin.containsKey(permission) + || extensionOperationToPermission.containsValue(permission); + } + /** * Registers a plugin-supplied extension permission so {@link #isUserAuthorized} * can check it. The engine invokes this once per registered permission diff --git a/server/src/main/java/com/diridium/rbac/RbacServlet.java b/server/src/main/java/com/diridium/rbac/RbacServlet.java index eaab563..0f946a2 100644 --- a/server/src/main/java/com/diridium/rbac/RbacServlet.java +++ b/server/src/main/java/com/diridium/rbac/RbacServlet.java @@ -74,7 +74,7 @@ public RbacServlet(@Context HttpServletRequest request, @Context SecurityContext // by stored perms (isUserAuthorized bypasses on the flag; getMyPermissions returns // the full catalog for any admin-role holder regardless of what is stored). AdminRoleGuard adminGuard = new AdminRoleGuard(repo, PermissionUtil::getAllCorePermissions); - this.roleService = new RoleService(repo, adminGuard, auditLog, this::invalidateCache); + this.roleService = new RoleService(repo, adminGuard, auditLog, this::invalidateCache, UserRoles::userExists); this.transferService = new RoleTransferService(repo, auditLog, this::invalidateCache, this::getAllPermissions, RbacServlet::allChannelNames, RbacServlet::rbacVersion, () -> ConfigurationController.getInstance().getServerVersion()); diff --git a/server/src/main/java/com/diridium/rbac/RoleService.java b/server/src/main/java/com/diridium/rbac/RoleService.java index 3f8f8b4..bc84cbb 100644 --- a/server/src/main/java/com/diridium/rbac/RoleService.java +++ b/server/src/main/java/com/diridium/rbac/RoleService.java @@ -7,6 +7,7 @@ import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; +import java.util.function.IntPredicate; import java.util.function.Supplier; import javax.ws.rs.core.Response; @@ -33,6 +34,7 @@ class RoleService { private final AdminRoleGuard adminGuard; private final RbacAuditLog auditLog; private final Runnable cacheInvalidator; + private final IntPredicate userExists; /** * @param repo persistence layer @@ -42,11 +44,13 @@ class RoleService { * drop cached per-user auth state; pass a * no-op {@link Runnable} in tests */ - RoleService(RbacRepository repo, AdminRoleGuard adminGuard, RbacAuditLog auditLog, Runnable cacheInvalidator) { + RoleService(RbacRepository repo, AdminRoleGuard adminGuard, RbacAuditLog auditLog, Runnable cacheInvalidator, + IntPredicate userExists) { this.repo = repo; this.adminGuard = adminGuard; this.auditLog = auditLog; this.cacheInvalidator = cacheInvalidator; + this.userExists = userExists; } /** @@ -194,13 +198,18 @@ Set effectivePermissions(int userId, Supplier> allPermission * @param userId user receiving the assignment * @param roleId role to assign * @throws MirthApiException with {@link Status#NOT_FOUND} if the role - * doesn't exist, {@link Status#BAD_REQUEST} + * doesn't exist or the engine has no user with + * that id, {@link Status#BAD_REQUEST} * from {@link AdminRoleGuard#validateUserRoleAssignment} */ void assignUserRole(int userId, int roleId) { if (repo.getRoleById(roleId) == null) { throw new MirthApiException(Status.NOT_FOUND); } + // A row for a user the engine doesn't have would give the role to a user created later with that id. + if (!userExists.test(userId)) { + throw notFound("No engine user has the id " + userId + "."); + } synchronized (AdminRoleGuard.ROLE_CHANGES) { adminGuard.validateUserRoleAssignment(userId, roleId); repo.assignUserRole(userId, roleId); @@ -266,6 +275,10 @@ private static MirthApiException badRequest(String message) { return new MirthApiException(Response.status(Status.BAD_REQUEST).entity(message).build()); } + private static MirthApiException notFound(String message) { + return new MirthApiException(Response.status(Status.NOT_FOUND).entity(message).build()); + } + private static MirthApiException conflict(String message) { return new MirthApiException(Response.status(Status.CONFLICT).entity(message).build()); } diff --git a/server/src/main/java/com/diridium/rbac/UserRoles.java b/server/src/main/java/com/diridium/rbac/UserRoles.java index e9e2919..b95a2e9 100644 --- a/server/src/main/java/com/diridium/rbac/UserRoles.java +++ b/server/src/main/java/com/diridium/rbac/UserRoles.java @@ -105,7 +105,8 @@ private static UserRolesService service() { UserRoles::refreshCachedPermissions, DeletedUserCleanup::usernameOf, UserRoles::userExists); } - private static boolean userExists(int userId) { + /** Whether the engine has a user with this id. Also used by the REST assign call. */ + static boolean userExists(int userId) { try { return ControllerFactory.getFactory().createUserController().getUser(userId, null) != null; } catch (ControllerException e) { diff --git a/server/src/test/java/com/diridium/rbac/LogNameEscapingTest.java b/server/src/test/java/com/diridium/rbac/LogNameEscapingTest.java index 5767a8a..f214728 100644 --- a/server/src/test/java/com/diridium/rbac/LogNameEscapingTest.java +++ b/server/src/test/java/com/diridium/rbac/LogNameEscapingTest.java @@ -18,15 +18,16 @@ /** * rbac's log lines quote a role, permission, channel, user or plugin name as '{}'. The engine writes log messages as - * they are, so each such line has to pass the name through {@link NameCharacters#forLog}. This test reads the server - * sources and fails for a log line that quotes a placeholder and never calls it. + * they are, so each such name has to pass through {@link NameCharacters#forLog}. This test reads the server sources + * and, for every log line, matches each quoted placeholder to its argument by position: that argument has to be a + * {@code NameCharacters.forLog(...)} call, or the bootstrap admin role's name, which is a constant. */ class LogNameEscapingTest { private static final Pattern LOG_CALL = Pattern.compile("\\blog\\.(trace|debug|info|warn|error)\\("); @Test - void everyLogLineThatQuotesAName_escapesIt() throws IOException { + void everyQuotedPlaceholder_getsItsArgumentThroughForLog() throws IOException { List missing = new ArrayList<>(); int quoted = 0; try (Stream files = Files.walk(Path.of("src/main/java"))) { @@ -34,46 +35,35 @@ void everyLogLineThatQuotesAName_escapesIt() throws IOException { String source = Files.readString(file); Matcher m = LOG_CALL.matcher(source); while (m.find()) { - String call = arguments(source, m.end()); - if (!call.contains("'{}'")) { - continue; - } - quoted++; - // Every quoted placeholder needs its own forLog. The bootstrap admin role's name is a constant. - int placeholders = count(call, "'{}'"); - int escaped = count(call, "NameCharacters.forLog(") + count(call, "BOOTSTRAP_ADMIN_ROLE_NAME"); - if (escaped < placeholders) { - missing.add(file.getFileName() + ": " + call.lines().findFirst().orElse("").strip()); + List args = split(arguments(source, m.end())); + String format = literalText(args.get(0)); + int arg = 1; + for (int i = format.indexOf("{}"); i >= 0; i = format.indexOf("{}", i + 2), arg++) { + boolean isQuoted = i > 0 && format.charAt(i - 1) == '\'' + && i + 2 < format.length() && format.charAt(i + 2) == '\''; + if (!isQuoted) { + continue; + } + quoted++; + String value = arg < args.size() ? args.get(arg) : ""; + if (!value.startsWith("NameCharacters.forLog(") && !value.endsWith("BOOTSTRAP_ADMIN_ROLE_NAME")) { + missing.add(file.getFileName() + ": \"" + format + "\" argument " + arg + ": " + value); + } } } } } - assertTrue(quoted > 10, "found only " + quoted + " log lines that quote a placeholder; is the source path right?"); - assertTrue(missing.isEmpty(), "log lines that quote '{}' without NameCharacters.forLog: " + missing); + assertTrue(quoted > 10, "found only " + quoted + " quoted placeholders in log lines; is the source path right?"); + assertTrue(missing.isEmpty(), "quoted placeholders whose argument doesn't go through NameCharacters.forLog: " + missing); } - private static int count(String text, String needle) { - int n = 0; - for (int i = text.indexOf(needle); i >= 0; i = text.indexOf(needle, i + needle.length())) { - n++; - } - return n; - } - - /** The call's arguments: the text from its opening parenthesis to the matching one, skipping string literals. */ + /** The call's arguments: the text from its opening parenthesis to the matching one. */ private static String arguments(String source, int from) { int depth = 1; - boolean inString = false; for (int i = from; i < source.length(); i++) { char c = source.charAt(i); - if (inString) { - if (c == '\\') { - i++; - } else if (c == '"') { - inString = false; - } - } else if (c == '"') { - inString = true; + if (c == '"' || c == '\'') { + i = endOfLiteral(source, i); } else if (c == '(') { depth++; } else if (c == ')' && --depth == 0) { @@ -82,4 +72,56 @@ private static String arguments(String source, int from) { } return source.substring(from); } + + /** The arguments split at the commas that aren't inside a literal or brackets. */ + private static List split(String args) { + List out = new ArrayList<>(); + int depth = 0; + int start = 0; + for (int i = 0; i < args.length(); i++) { + char c = args.charAt(i); + if (c == '"' || c == '\'') { + i = endOfLiteral(args, i); + } else if (c == '(' || c == '{' || c == '[') { + depth++; + } else if (c == ')' || c == '}' || c == ']') { + depth--; + } else if (c == ',' && depth == 0) { + out.add(args.substring(start, i).strip()); + start = i + 1; + } + } + out.add(args.substring(start).strip()); + return out; + } + + /** The text of the string literals in the format argument, joined in order. */ + private static String literalText(String format) { + StringBuilder text = new StringBuilder(); + for (int i = 0; i < format.length(); i++) { + char c = format.charAt(i); + if (c == '"') { + int end = endOfLiteral(format, i); + text.append(format, i + 1, end); + i = end; + } else if (c == '\'') { + i = endOfLiteral(format, i); + } + } + return text.toString(); + } + + /** The index of the quote that closes the string or char literal opening at {@code open}. */ + private static int endOfLiteral(String text, int open) { + char quote = text.charAt(open); + for (int i = open + 1; i < text.length(); i++) { + char c = text.charAt(i); + if (c == '\\') { + i++; + } else if (c == quote) { + return i; + } + } + return text.length() - 1; + } } diff --git a/server/src/test/java/com/diridium/rbac/RbacAuthorizationControllerTest.java b/server/src/test/java/com/diridium/rbac/RbacAuthorizationControllerTest.java index b312956..fce8e04 100644 --- a/server/src/test/java/com/diridium/rbac/RbacAuthorizationControllerTest.java +++ b/server/src/test/java/com/diridium/rbac/RbacAuthorizationControllerTest.java @@ -1037,6 +1037,25 @@ private RbacAuthorizationController controllerWithRegistered(Class servletInt return new RbacAuthorizationController(); } + @Test + void aFailureReadingTheLabels_stillBuildsTheController_andLabelledOperationsStayUnknown() throws Exception { + ConnectorMetaData connector = new ConnectorMetaData(); + connector.setName("Test Writer"); + ApiProvider provider = new ApiProvider(); + provider.setType(ApiProvider.Type.SERVLET_INTERFACE); + provider.setName(RegisteredOperationLabelsTest.LabelledService.class.getName()); + connector.setApiProviders(List.of(provider)); + ExtensionController extensions = mock(ExtensionController.class); + when(extensions.getConnectorMetaData()).thenReturn(Map.of("Test Writer", connector)); + when(extensions.getPluginMetaData()).thenReturn(Map.of()); + when(extensions.isExtensionEnabled("Test Writer")).thenThrow(new IllegalStateException("not ready")); + when(factory.createExtensionController()).thenReturn(extensions); + + RbacAuthorizationController unlabelled = new RbacAuthorizationController(); + givenUserHasRole(2, 5, Set.of("viewDashboard"), null); + assertTrue(unlabelled.isUserAuthorized(2, op("Test Connector Service#testConnection"), null, "127.0.0.1", false)); + } + @Test void labelledOperation_refusedWithoutItsPermission() { RbacAuthorizationController labelled = controllerWithRegistered(RegisteredOperationLabelsTest.LabelledService.class); diff --git a/server/src/test/java/com/diridium/rbac/RoleChangeRaceTest.java b/server/src/test/java/com/diridium/rbac/RoleChangeRaceTest.java index ce12b62..61b25b8 100644 --- a/server/src/test/java/com/diridium/rbac/RoleChangeRaceTest.java +++ b/server/src/test/java/com/diridium/rbac/RoleChangeRaceTest.java @@ -84,7 +84,7 @@ void twoSignInsDemotingTheLastTwoAdmins_leaveOneAdmin() throws Exception { void aSignInAndTheAdministratorsAssignRole_runOneAtATimeToo() throws Exception { UserRolesService userRoles = userRoles(); RoleService roleService = new RoleService(repo, new AdminRoleGuard(repo, Set::of), mock(RbacAuditLog.class), - () -> { }); + () -> { }, id -> true); List outcomes = run(() -> userRoles.assign(1, "Viewer", "plugin A"), () -> { try { roleService.assignUserRole(2, VIEWER_ROLE_ID); @@ -101,7 +101,7 @@ void aSignInAndTheAdministratorsAssignRole_runOneAtATimeToo() throws Exception { void aSignInAndTheAdministratorsRemoveRole_runOneAtATimeToo() throws Exception { UserRolesService userRoles = userRoles(); RoleService roleService = new RoleService(repo, new AdminRoleGuard(repo, Set::of), mock(RbacAuditLog.class), - () -> { }); + () -> { }, id -> true); doAnswer(call -> assignments.remove(call.getArgument(0, Integer.class))).when(repo).removeUserRole(anyInt()); List outcomes = run(() -> userRoles.assign(1, "Viewer", "plugin A"), () -> { try { diff --git a/server/src/test/java/com/diridium/rbac/RoleImportPlannerTest.java b/server/src/test/java/com/diridium/rbac/RoleImportPlannerTest.java index 485c3ff..8cafac9 100644 --- a/server/src/test/java/com/diridium/rbac/RoleImportPlannerTest.java +++ b/server/src/test/java/com/diridium/rbac/RoleImportPlannerTest.java @@ -514,6 +514,12 @@ void anExistingRoleKeepingItsDescription_isNotRefused_butAChangedOneIs() throws () -> plan(true, new ExportedRole("Lab", "other\u007fdesc", List.of("viewChannels"), false, List.of()))); } + @Test + void theAdminRoleWithAChangedDescriptionHoldingADeleteCharacter_isSkipped_notRefused() throws Exception { + Plan plan = plan(true, new ExportedRole("Administrator", "bad\u007fdesc", List.of("viewChannels"), false, List.of())); + assertEquals(Action.SKIP, plan.rows().get(0).getAction()); + } + // ========== Helpers ========== private Plan plan(boolean applyChannels, ExportedRole... fileRoles) throws Refusal { diff --git a/server/src/test/java/com/diridium/rbac/RoleServiceTest.java b/server/src/test/java/com/diridium/rbac/RoleServiceTest.java index ad46f21..027f95f 100644 --- a/server/src/test/java/com/diridium/rbac/RoleServiceTest.java +++ b/server/src/test/java/com/diridium/rbac/RoleServiceTest.java @@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -46,7 +47,7 @@ void setUp() { adminGuard = mock(AdminRoleGuard.class); auditLog = mock(RbacAuditLog.class); cacheInvalidator = mock(Runnable.class); - service = new RoleService(repo, adminGuard, auditLog, cacheInvalidator); + service = new RoleService(repo, adminGuard, auditLog, cacheInvalidator, id -> id != 404); } // ========== get ========== @@ -317,6 +318,19 @@ void assignUserRole_missingRole_throws404() { verify(repo, never()).assignUserRole(anyInt(), anyInt()); } + @Test + void assignUserRole_aUserTheEngineDoesntHave_throws404WithAMessage_andChangesNothing() { + when(repo.getRoleById(7)).thenReturn(roleWithName(7, "Editor")); + + MirthApiException e = assertThrows(MirthApiException.class, () -> service.assignUserRole(404, 7)); + assertEquals(Status.NOT_FOUND.getStatusCode(), e.getResponse().getStatus()); + assertEquals("No engine user has the id 404.", e.getResponse().getEntity()); + verify(adminGuard, never()).validateUserRoleAssignment(anyInt(), anyInt()); + verify(repo, never()).assignUserRole(anyInt(), anyInt()); + verify(cacheInvalidator, never()).run(); + verify(auditLog, never()).assignment(anyString(), anyInt(), anyInt()); + } + @Test void assignUserRole_adminGuardRejection_propagates() { when(repo.getRoleById(7)).thenReturn(roleWithName(7, "Editor")); diff --git a/server/src/test/java/com/diridium/rbac/SqlStatementIdCoverageTest.java b/server/src/test/java/com/diridium/rbac/SqlStatementIdCoverageTest.java index 5484be6..e70084c 100644 --- a/server/src/test/java/com/diridium/rbac/SqlStatementIdCoverageTest.java +++ b/server/src/test/java/com/diridium/rbac/SqlStatementIdCoverageTest.java @@ -10,19 +10,20 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.LinkedHashSet; -import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; /** - * Cross-checks every MyBatis statement id the repository and seeder invoke - * against the ids actually declared in {@code sqlmap.xml}. The repository/seeder - * unit tests mock {@code SqlSession}, so a typo'd statement id passes the suite - * and only blows up at runtime with "Mapped Statement not found". This test - * closes that gap. + * Cross-checks every MyBatis statement id the server code names, through + * {@code RbacRepository.stmt("...")}, against the ids declared in + * {@code sqlmap.xml}. The repository unit tests mock {@code SqlSession}, so a + * typo'd statement id passes the suite and only blows up at runtime with + * "Mapped Statement not found". The ids are read from the sources, so a new + * one is checked without anyone listing it. * *

{@code sqlmap.xml} lives in the {@code package} module (not on the server * test classpath), so it is read from the filesystem relative to the module @@ -30,24 +31,33 @@ */ class SqlStatementIdCoverageTest { - /** Every statement id referenced via RbacRepository.stmt(...) or the seeder. */ - private static final List STATEMENT_IDS_IN_USE = List.of( - "getAllRoles", "getRoleById", "insertRole", "updateRole", "deleteRole", - "getRoleIdByName", "getAdminRoleId", "setRoleIsAdmin", "countUsersByRoleId", - "getUserRoleId", "deleteUserRole", "insertUserRole", "deleteOrphanUserRoles", - "getPermissionsForRole", "deletePermissionsForRole", "insertPermission", "deletePermission", - "getChannelIdsForRole", "deleteChannelIdsForRole", "insertChannelId", "getAllRoleChannels", - "deleteChannelIdForRole", "getRoleIdsForChannel", "deleteChannelIdFromRoles"); + private static final Pattern STMT_CALL = Pattern.compile("\\bstmt\\(\"([A-Za-z0-9_]+)\"\\)"); @Test void everyReferencedStatementIdIsDeclaredInSqlmap() throws IOException { + Set inUse = referencedStatementIds(); + assertTrue(inUse.size() > 20, "found only " + inUse.size() + " statement ids in the sources; is the source path right?"); Set declared = declaredStatementIds(); - for (String id : STATEMENT_IDS_IN_USE) { + for (String id : inUse) { assertTrue(declared.contains(id), "sqlmap.xml is missing statement id '" + id + "'; declared ids: " + declared); } } + /** Every id the server code passes to {@code stmt("...")}. */ + private static Set referencedStatementIds() throws IOException { + Set ids = new LinkedHashSet<>(); + try (Stream files = Files.walk(Path.of("src/main/java"))) { + for (Path file : files.filter(p -> p.toString().endsWith(".java")).toList()) { + Matcher m = STMT_CALL.matcher(Files.readString(file)); + while (m.find()) { + ids.add(m.group(1)); + } + } + } + return ids; + } + private static Set declaredStatementIds() throws IOException { String xml = Files.readString(locateSqlmap()); Set ids = new LinkedHashSet<>(); diff --git a/webadmin/e2e/orphaned-permissions.spec.js b/webadmin/e2e/orphaned-permissions.spec.js index aaaab36..a3acc60 100644 --- a/webadmin/e2e/orphaned-permissions.spec.js +++ b/webadmin/e2e/orphaned-permissions.spec.js @@ -29,7 +29,8 @@ const ROLES_VIEWER = { ...READ_ONLY_ROLE, id: 4, name: 'Roles Viewer', permissio const task = (page, name) => page.getByRole('button', { name, exact: true }); // lists: what each GET of the list answers, in turn (the last one repeats). -async function openPanel(page, { lists = [LIST], userRole = ADMIN_ROLE } = {}) { +// hold: a promise the removal waits on before it answers. +async function openPanel(page, { lists = [LIST], userRole = ADMIN_ROLE, hold = null } = {}) { const removals = []; let roleListLoads = 0; page.on('request', (req) => { @@ -39,7 +40,11 @@ async function openPanel(page, { lists = [LIST], userRole = ADMIN_ROLE } = {}) { await mockEngineWithRbac(page, { ...rbacFixtures({ userRole }), 'GET /extensions/rbac/roles/_unregistered': () => lists[Math.min(reads++, lists.length - 1)], - 'POST /extensions/rbac/roles/_unregistered/_remove': (req) => { removals.push(req.postData()); return { int: 1 }; } + 'POST /extensions/rbac/roles/_unregistered/_remove': async (req) => { + removals.push(req.postData()); + if (hold) await hold; + return { int: 1 }; + } }); await page.goto('/settings'); await page.getByRole('tab', { name: 'Role-Based Access Control', exact: true }).click(); @@ -91,6 +96,23 @@ test.describe('the Orphaned Permissions task', () => { expect(removals).toEqual([]); }); + test('while a removal runs, the dialog can\'t be closed', async ({ page }) => { + let release; + const hold = new Promise((resolve) => { release = resolve; }); + await openPanel(page, { lists: [LIST, NONE], hold }); + await task(page, 'Orphaned Permissions').click(); + const dialog = page.locator('.rbac-overlay'); + const close = dialog.locator('button.btn-primary', { hasText: 'Close' }); + await dialog.getByRole('button', { name: 'Remove All' }).click(); + await page.getByRole('button', { name: 'Remove', exact: true }).click(); + await expect(close).toBeDisabled(); + await page.keyboard.press('Escape'); + await expect(dialog).toBeVisible(); + release(); + await expect(dialog.getByText(EMPTY)).toBeVisible(); + await expect(close).toBeEnabled(); + }); + test('with nothing orphaned, the dialog says so and offers no removal', async ({ page }) => { await openPanel(page, { lists: [NONE] }); await task(page, 'Orphaned Permissions').click(); diff --git a/webadmin/e2e/role-editor.spec.js b/webadmin/e2e/role-editor.spec.js index 9a73090..c66f5ab 100644 --- a/webadmin/e2e/role-editor.spec.js +++ b/webadmin/e2e/role-editor.spec.js @@ -20,7 +20,8 @@ const DESCRIPTION_CHARACTERS = "A role description can't contain control charact const KEEPS_ONE = 'This role keeps 1 channel this list does not show.'; const ADMIN_EVERY = 'The admin role has every permission, including those of plugins installed later.'; const NONE_ROLE = { ...READ_ONLY_ROLE, id: 5, name: 'Sees None', restricted: true, channelIds: null }; -const TWO_LINES = { ...READ_ONLY_ROLE, id: 8, name: 'Two Lines', description: 'line one\nline two' }; +// A trailing line break too: the editor used to trim the description it saved, even unedited. +const TWO_LINES = { ...READ_ONLY_ROLE, id: 8, name: 'Two Lines', description: 'line one\nline two\n' }; const SOME_ROLE = { ...READ_ONLY_ROLE, id: 6, name: 'Sees Some', restricted: true, channelIds: { string: 'c-started' } }; const UNKNOWN_ID_ROLE = { ...READ_ONLY_ROLE, id: 7, name: 'Sees Unknown', restricted: true, channelIds: { string: ['c-started', 'c-not-here'] } @@ -122,7 +123,7 @@ test.describe('role editor: characters the server refuses', () => { await editor.getByRole('button', { name: 'Apply' }).click(); await expect.poll(() => writes.length).toBe(1); expect(writes[0][1]).toContain('Two Lines Renamed'); - expect(writes[0][1]).toContain('line one\nline two'); + expect(writes[0][1]).toContain('line one\nline two\n'); }); test('a bell in a changed description shows the message, keeps the editor open, and sends nothing', async ({ page }) => { diff --git a/webadmin/e2e/role-transfer.spec.js b/webadmin/e2e/role-transfer.spec.js index eb27647..fd1a462 100644 --- a/webadmin/e2e/role-transfer.spec.js +++ b/webadmin/e2e/role-transfer.spec.js @@ -705,6 +705,29 @@ test.describe('Import Roles', () => { await expect(toast(page, 'Imported 1 role(s).')).toHaveCount(0); }); + test('a 403 on apply shows the refusal once and sends no second preview', async ({ page }) => { + const seen = watch(page); + const REFUSED = 'Importing roles needs the admin role.'; + let refuse = false; + await openPanel(page, importFixtures(IMPORT_PREVIEW_TWO_ROWS, { + 'POST /extensions/rbac/roles/_import': (req) => { + // Preview and apply are one server call, so once it refuses, a preview is refused too. + if (refuse) return { __status: 403, body: REFUSED }; + return echoSettings(IMPORT_PREVIEW_TWO_ROWS, new URL(req.url()).searchParams); + } + })); + await chooseFile(page); + const box = dialog(page, 'Import Roles'); + await expect(box.locator('.rbac-xfer-roles tbody tr')).toHaveCount(2); + const previews = seen.previews.length; + refuse = true; + await box.getByRole('button', { name: 'Import', exact: true }).click(); + await expect(dialog(page, 'Error').getByText(REFUSED)).toBeVisible(); + await page.waitForLoadState('networkidle'); + expect(seen.applies).toHaveLength(1); + expect(seen.previews).toHaveLength(previews); + }); + test('a failed preview keeps the shown preview, its "not applied" state and hint, and disables Import until one succeeds', async ({ page }) => { const seen = watch(page); let fail = false; diff --git a/webadmin/web/authorization-session.test.mjs b/webadmin/web/authorization-session.test.mjs index d1cca78..339017e 100644 --- a/webadmin/web/authorization-session.test.mjs +++ b/webadmin/web/authorization-session.test.mjs @@ -245,26 +245,29 @@ test('automatic retries exhaust their budget; later lazy checks can still recove assert.equal(h.platform.controller.checkTask('settings_Role-Based Access Control', 'doRefresh'), true); }); -/* ---- admin flag for Export Roles and Import Roles ------------------------------ */ +/* ---- admin flag for the admin-only tasks: Export Roles, Import Roles, Orphaned Permissions ---- */ const EXPORT_TASK = ['settings_Role-Based Access Control', 'doExportRoles']; const IMPORT_TASK = ['settings_Role-Based Access Control', 'doImportRoles']; +const ORPHANED_TASK = ['settings_Role-Based Access Control', 'doShowOrphanedPermissions']; -test('a View Roles holder in the admin role sees both tasks; the role is read with the current user id', async t => { +test('a View Roles holder in the admin role sees all three tasks; the role is read with the current user id', async t => { const h = harness(t); h.userRole(async () => ({ isAdmin: true })); await h.register(); assert.deepEqual(h.roleCalls, [7]); assert.equal(h.platform.controller.checkTask(...EXPORT_TASK), true); assert.equal(h.platform.controller.checkTask(...IMPORT_TASK), true); + assert.equal(h.platform.controller.checkTask(...ORPHANED_TASK), true); }); -test('a View Roles holder in another role sees neither task', async t => { +test('a View Roles holder in another role sees none of the three', async t => { const h = harness(t); await h.register(); assert.deepEqual(h.roleCalls, [7]); assert.equal(h.platform.controller.checkTask(...EXPORT_TASK), false); assert.equal(h.platform.controller.checkTask(...IMPORT_TASK), false); + assert.equal(h.platform.controller.checkTask(...ORPHANED_TASK), false); }); test('without View Roles the role is never read and the tasks stay hidden', async t => { diff --git a/webadmin/web/name-characters.test.mjs b/webadmin/web/name-characters.test.mjs index d406272..9a571d9 100644 --- a/webadmin/web/name-characters.test.mjs +++ b/webadmin/web/name-characters.test.mjs @@ -71,5 +71,6 @@ test('savedText keeps the stored value of an unedited field and trims an edited assert.equal(savedText(' Lab ', ' Lab '), ' Lab ', 'even its spaces'); assert.equal(savedText('Lab', ' Lab2 '), 'Lab2'); assert.equal(savedText(null, ' New '), 'New', 'a new role'); + assert.equal(savedText('first\nsecond', 'firstsecond'), 'first\nsecond', + 'edited back to what the field showed, which drops line breaks: kept as stored'); }); - diff --git a/webadmin/web/orphaned-permissions.jsx b/webadmin/web/orphaned-permissions.jsx index 734260f..3910acd 100644 --- a/webadmin/web/orphaned-permissions.jsx +++ b/webadmin/web/orphaned-permissions.jsx @@ -64,13 +64,13 @@ export function makeOrphanedPermissions(platform, api) { const disabledLine = orphanedDisabledLine(list.disabledPlugins); return ( - - + )}>

{ORPHANED_INTRO}
diff --git a/webadmin/web/rbac-core.js b/webadmin/web/rbac-core.js index 71554ab..197f54d 100644 --- a/webadmin/web/rbac-core.js +++ b/webadmin/web/rbac-core.js @@ -437,8 +437,10 @@ export function javaTrim(s) { return String(s ?? '').replace(/^[\u0000- ]+|[\u0000- ]+$/g, ''); } -/** The value a role editor saves for its name or description: the stored value when the field wasn't edited, so a - * value a text field can't show (a line break) is kept as it is; otherwise the field, trimmed as Swing trims it. */ +/** The value a role editor saves for its name or description: the stored value when the field wasn't edited, or + * was edited back to what it showed (a text input drops line breaks, so it shows the stored value without them); + * otherwise the field, trimmed as Swing trims it. */ export function savedText(stored, current) { - return stored != null && current === stored ? stored : javaTrim(current); + const unedited = stored != null && (current === stored || current === stored.replace(/[\r\n]/g, '')); + return unedited ? stored : javaTrim(current); } diff --git a/webadmin/web/role-import-dialog.jsx b/webadmin/web/role-import-dialog.jsx index 9cea074..aabc840 100644 --- a/webadmin/web/role-import-dialog.jsx +++ b/webadmin/web/role-import-dialog.jsx @@ -19,7 +19,7 @@ import { PERMISSION_COLUMNS, CHANNEL_COLUMNS, CHANNEL_ID_COLUMNS, PERMISSIONS_LEGEND, CHANNELS_LEGEND, CHANNELS_NOT_APPLIED, importRefusedText, importSourceText, importedText, actionLabel, canTick, notesText, mergeTicks, pickedIndexes, nameMatchHint, sortByColumn, IMPORT_COUNT_COLUMNS, permissionsCountText, channelsCountText, - permissionsHeading, channelsHeading, permissionRows, channelRows, everyChannelText + permissionsHeading, channelsHeading, permissionRows, channelRows, everyChannelText, previewAgainAfter } from './role-transfer-core.js'; import { toggleIn } from './rbac-core.js'; import { makeTransferShell } from './role-transfer-shell.jsx'; @@ -98,7 +98,11 @@ export function makeRoleImportDialog(platform, api) { }); } catch (e) { ui.toast(errorText(e), 'error'); - await preview(result.applyChannels, result.matchChannelsByName); + if (previewAgainAfter(e)) { + await preview(result.applyChannels, result.matchChannelsByName); + } else { + setBusy(false); + } return; } ui.toast(importedText(pick.length), 'success'); diff --git a/webadmin/web/role-transfer-core.js b/webadmin/web/role-transfer-core.js index a518286..ecd9acb 100644 --- a/webadmin/web/role-transfer-core.js +++ b/webadmin/web/role-transfer-core.js @@ -11,6 +11,13 @@ /* ---- role export and import (strings and logic match the Swing client) ------ */ // Settings panel tasks. +/** Whether a failed import apply is worth previewing again: the server refused it with its own reason, a 400, or a + * 409 because the roles changed since the preview. Anything else, a 403 or a lost connection, would fail the preview + * too, and the same error would show twice. The Swing twin is RoleImportText.previewAgainAfter. */ +export function previewAgainAfter(e) { + return !!e && (e.status === 400 || e.status === 409); +} + export const TASK_EXPORT_ROLES = 'Export Roles'; export const TASK_EXPORT_ROLES_TOOLTIP = 'Export roles to a file.'; export const TASK_IMPORT_ROLES = 'Import Roles'; diff --git a/webadmin/web/role-transfer.test.mjs b/webadmin/web/role-transfer.test.mjs index 615a49d..fcaaacd 100644 --- a/webadmin/web/role-transfer.test.mjs +++ b/webadmin/web/role-transfer.test.mjs @@ -21,7 +21,7 @@ import { EXPORT_EVERY_CHANNEL, EXPORT_NO_CHANNEL, countText, permissionsCountText, channelsCountText, everyChannelText, foundText, permissionRows, channelRows, permissionsHeading, channelsHeading, sortRows, compareCounts, exportPermissionRows, exportChannelRows, exportPermissionsCount, exportChannelsCount, - compareIgnoreCase, sortByColumn, EXPORT_COUNT_COLUMNS, IMPORT_COUNT_COLUMNS + compareIgnoreCase, sortByColumn, EXPORT_COUNT_COLUMNS, IMPORT_COUNT_COLUMNS, previewAgainAfter } from './role-transfer-core.js'; import { MSG_NO_CHANNELS_TICKED } from './rbac-core.js'; @@ -396,3 +396,12 @@ test('Export rows: permissions sorted; channels by shown text, case-insensitive, assert.equal(exportChannelsCount({ restricted: true, channelIds: new Set() }), 'none'); assert.equal(exportChannelsCount({ restricted: true, channelIds: new Set(['a']) }), 1); }); + +test('previewAgainAfter: only a 400 or 409, the refusals the server words itself', () => { + const failure = (status) => Object.assign(new Error('refused'), { status }); + assert.equal(previewAgainAfter(failure(409)), true, 'the roles changed since the preview'); + assert.equal(previewAgainAfter(failure(400)), true); + assert.equal(previewAgainAfter(failure(403)), false, 'a 403 would refuse the preview too'); + assert.equal(previewAgainAfter(new Error('No response after 30 seconds')), false, 'no status: a lost connection'); + assert.equal(previewAgainAfter(undefined), false); +}); diff --git a/webadmin/web/roles-panel.jsx b/webadmin/web/roles-panel.jsx index 4018ed1..e94d93d 100644 --- a/webadmin/web/roles-panel.jsx +++ b/webadmin/web/roles-panel.jsx @@ -127,8 +127,9 @@ export function registerRolesPanel(platform, api) { React.useEffect(() => { load(); // No Save participation (the panel never calls setSave, so it can't - // trip the settings dirty tracking). Export and Import Roles are - // for the admin role only; the controller hides them from anyone else. + // trip the settings dirty tracking). Export Roles, Import Roles and + // Orphaned Permissions are for the admin role only; the controller + // hides them from anyone else. setTasks('Role-Based Access Control Tasks', [ ui.taskButton('Refresh', 'refresh', () => load(), { task: 'doRefresh', group: RBAC_GROUP }), ui.taskButton(TASK_EXPORT_ROLES, 'export', async () => setTransfer(await startExport(channelMapRef.current)),