100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Fix MQTT session authorization and inactive realm access
Wouter Born51dce18d9e00
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.javaindex 79e2ef784..a39754b69 100644--- a/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java+++ b/manager/src/main/java/org/openremote/manager/mqtt/MQTTBrokerService.java@@ -610,6 +610,11 @@ public class MQTTBrokerService extends RouteBuilder.collect(Collectors.toSet());}+ public String getConnectionUserId(String connectionID) {+ RemotingConnection connection = connectionIDConnectionMap.get(connectionID);+ return connection == null ? null : IdentityProvider.getSubjectId(connection.getSubject());+ }+protected void doForceDisconnect(RemotingConnection connection) {LOG.log(DEBUG, () -> "Force disconnecting client connection: " + connectionToString(connection));diff --git a/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java b/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.javaindex 0e485e148..5ccf0c022 100644--- a/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/security/UserResourceImpl.java@@ -79,6 +79,8 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource}if (!authContext.isSuperUser()) {+ throwIfNotRealmActiveAndAccessible(authContext.getAuthenticatedRealmName());+// Force realm to match usersquery.realm(new RealmPredicate(authContext.getAuthenticatedRealmName()));@@ -157,11 +159,12 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource@Overridepublic User updateCurrent(RequestParams requestParams, User user) {- try {- Map.Entry<String, String> authInfo = getCurrentUserAuthInfo();- String userId = authInfo.getKey();- String realm = authInfo.getValue();+ Map.Entry<String, String> authInfo = getCurrentUserAuthInfo();+ String userId = authInfo.getKey();+ String realm = authInfo.getValue();+ throwIfNotRealmActiveAndAccessible(realm);+ try {// Ensure the user ID in the provided user object matches the current userif (user.getId() != null && !user.getId().equals(userId)) {throw new ForbiddenException("Cannot update a different user's information");@@ -229,11 +232,12 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource@Overridepublic void requestPasswordResetCurrent(RequestParams requestParams) {- try {- Map.Entry<String, String> authInfo = getCurrentUserAuthInfo();- String userId = authInfo.getKey();- String realm = authInfo.getValue();+ Map.Entry<String, String> authInfo = getCurrentUserAuthInfo();+ String userId = authInfo.getKey();+ String realm = authInfo.getValue();+ throwIfNotRealmActiveAndAccessible(realm);+ try {// Call the identity provider to request password reset for the current useridentityService.getIdentityProvider().requestPasswordReset(realm, userId);} catch (ClientErrorException ex) {@@ -259,11 +263,12 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource@Overridepublic void updatePasswordCurrent(@BeanParam RequestParams requestParams, Credential credential) {- try {- Map.Entry<String, String> authInfo = getCurrentUserAuthInfo();- String userId = authInfo.getKey();- String realm = authInfo.getValue();+ Map.Entry<String, String> authInfo = getCurrentUserAuthInfo();+ String userId = authInfo.getKey();+ String realm = authInfo.getValue();+ throwIfNotRealmActiveAndAccessible(realm);+ try {// Call the identity provider to reset the passwordidentityService.getIdentityProvider().resetPassword(realm, userId, credential);} catch (ClientErrorException ex) {@@ -459,6 +464,35 @@ public class UserResourceImpl extends ManagerWebResource implements UserResource@Overridepublic void disconnectUserSession(RequestParams requestParams, String realm, String sessionID) {+ String connectionUserId = mqttBrokerService.getConnectionUserId(sessionID);+ if (connectionUserId == null) {+ throw new NotFoundException("User session not found");+ }++ User connectionUser = identityService.getIdentityProvider().getUser(connectionUserId);+ if (connectionUser == null) {+ throw new NotFoundException("User not found");+ }++ String connectionRealm = connectionUser.getRealm();++ if (!connectionRealm.equals(realm)) {+ throw new NotFoundException("User session not found in realm");+ }++ throwIfCannotReadUserInRealm(connectionRealm, connectionUserId);++ boolean hasAdminWriteRole =+ hasResourceRoleOrIsSuperUser(+ ClientRole.WRITE_ADMIN.getValue(), Constants.KEYCLOAK_CLIENT_ID);++ if (!hasAdminWriteRole && !Objects.equals(getUserId(), connectionUserId)) {+ throw new ForbiddenException(+ "Can only disconnect own user sessions unless you have role '"+ + ClientRole.WRITE_ADMIN+ + "'");+ }+if (!mqttBrokerService.disconnectSession(sessionID)) {throw new NotFoundException("User session not found");}@@ -505,6 +539,8 @@ public class UserResourceImpl extends ManagerWebResource implements UserResourcethrow new NotAllowedException("Cannot mutate a user in a different realm");}+ throwIfNotRealmActiveAndAccessible(realm);+if (!currentUserId.equals(userId)&& !hasResourceRole(Constants.WRITE_ADMIN_ROLE, Constants.KEYCLOAK_CLIENT_ID)) {throw new NotAllowedException("Not allowed to mutate another user");@@ -520,6 +556,8 @@ public class UserResourceImpl extends ManagerWebResource implements UserResourceif (!authContext.isRealmAccessibleByUser(realm)) {throw new NotAllowedException("Cannot administer a different realm");}++ throwIfNotRealmActiveAndAccessible(realm);}protected void throwIfCannotReadUserInRealm(String realm, String userId)diff --git a/manager/test/src/groovy/org/openremote/manager/security/UserResourceRealmTest.groovy b/manager/test/src/groovy/org/openremote/manager/security/UserResourceRealmTest.groovynew file mode 100644index 000000000..4eb0eaf18--- /dev/null+++ b/manager/test/src/groovy/org/openremote/manager/security/UserResourceRealmTest.groovy@@ -0,0 +1,290 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * SPDX-License-Identifier: AGPL-3.0-or-later+ */+package org.openremote.manager.security++import com.nimbusds.jwt.JWTClaimsSet+import jakarta.ws.rs.WebApplicationException+import jakarta.ws.rs.core.SecurityContext+import org.openremote.container.security.TokenPrincipal+import org.openremote.container.timer.TimerService+import org.openremote.manager.mqtt.MQTTBrokerService+import org.openremote.model.query.UserQuery+import org.openremote.model.security.Credential+import org.openremote.model.security.Realm+import org.openremote.model.security.User+import spock.lang.Specification++import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID+import static org.openremote.model.Constants.MASTER_REALM+import static org.openremote.model.Constants.SUPER_USER_REALM_ROLE++class UserResourceRealmTest extends Specification {++ static final String REALM = "building"+ static final String USER_ID = "user-1"+ static final long NOW = 1_800_000_000_000L++ def realm = new Realm().setName(REALM).setEnabled(true)+ def user = new User().setId(USER_ID).setRealm(REALM)+ def timer = Stub(TimerService) {+ getCurrentTimeMillis() >> NOW+ }+ def provider = Spy(ManagerKeycloakIdentityProvider)+ def mqtt = Mock(MQTTBrokerService)+ UserResourceImpl resource++ def setup() {+ provider.timerService = timer+ provider.getRealm(REALM) >> realm+ provider.isUserInRealm(USER_ID, REALM) >> true+ provider.getUser(USER_ID) >> user+ provider.createUpdateUser(REALM, _ as User, null, _) >> user+ provider.queryUsers(_ as UserQuery) >> ([user] as User[])+ provider.requestPasswordReset(REALM, USER_ID) >> {}+ provider.resetPassword(REALM, USER_ID, _ as Credential) >> {}+ mqtt.getConnectionUserId("connection-1") >> USER_ID+ mqtt.disconnectSession("connection-1") >> true++ def identityService = Stub(ManagerIdentityService) {+ getIdentityProvider() >> provider+ }+ resource = new UserResourceImpl(timer, identityService, mqtt)+ authenticate(false)+ }++ def "#operation rejects an existing caller after their realm is disabled"() {+ when: "the realm is active"+ invoke(resource, user)++ then:+ noExceptionThrown()++ when: "the realm is disabled without changing the caller's token"+ realm.setEnabled(false)+ invoke(resource, user)++ then:+ def exception = thrown(WebApplicationException)+ exception.response.status == 403+ 0 * provider.createUpdateUser(_, _, _, _)+ 0 * provider.queryUsers(_)+ 0 * provider.requestPasswordReset(_, _)+ 0 * provider.resetPassword(_, _, _)+ 0 * mqtt.disconnectSession(_)++ where:+ operation | invoke+ "query" | { r, u -> r.query(null, new UserQuery()) }+ "getCurrent" | { r, u -> r.getCurrent(null) }+ "create" | { r, u -> r.create(null, REALM, u) }+ "update" | { r, u -> r.update(null, REALM, u) }+ "updateCurrent" | { r, u -> r.updateCurrent(null, u) }+ "password reset" | { r, u -> r.requestPasswordReset(null, REALM, USER_ID) }+ "own password reset" | { r, u -> r.requestPasswordResetCurrent(null) }+ "password update" | { r, u -> r.updatePassword(null, REALM, USER_ID, new Credential()) }+ "own password update" | { r, u -> r.updatePasswordCurrent(null, new Credential()) }+ "MQTT disconnect" | { r, u -> r.disconnectUserSession(null, REALM, "connection-1") }+ }++ def "a realm with a future activation time rejects user queries"() {+ given:+ realm.setNotBefore((NOW / 1000 + 60) as Double)++ when:+ resource.query(null, new UserQuery())++ then:+ def exception = thrown(WebApplicationException)+ exception.response.status == 403+ 0 * provider.queryUsers(_)+ }++ def "superusers can still administer inactive realms"() {+ given:+ realm.setEnabled(enabled).setNotBefore(notBefore)+ authenticate(true)++ when:+ def result = resource.create(null, REALM, user)+ resource.update(null, REALM, user)+ resource.query(null, new UserQuery())++ then:+ result == user+ noExceptionThrown()++ where:+ enabled | notBefore+ false | 0d+ true | (NOW / 1000 + 60) as Double+ }++ def "#caller can disconnect a session in an authorized realm"() {+ given:+ authenticate(superUser, clientRoles, callerId)+ realm.setEnabled(enabled).setNotBefore(notBefore)++ when:+ resource.disconnectUserSession(null, REALM, "connection-1")++ then:+ noExceptionThrown()+ 1 * mqtt.disconnectSession("connection-1") >> true++ where:+ caller | superUser | clientRoles | callerId | enabled | notBefore+ "owner without client roles" | false | [] | USER_ID | true | 0d+ "same-realm write administrator" | false | ["write:admin"] | "admin" | true | 0d+ "superuser without client roles" | true | [] | "superuser" | true | 0d+ "superuser in a disabled realm" | true | [] | "superuser" | false | 0d+ "superuser before realm activation" | true | [] | "superuser" | true | (NOW / 1000 + 60) as Double+ }++ def "ordinary users without write admin cannot disconnect another user's session"() {+ given:+ authenticate(false, clientRoles, "other-user")++ when:+ resource.disconnectUserSession(null, REALM, "connection-1")++ then:+ def exception = thrown(WebApplicationException)+ exception.response.status == 403+ 0 * mqtt.disconnectSession(_)++ where:+ clientRoles << [[], ["read:admin"], ["write:user"]]+ }++ def "write administrators from another realm cannot disconnect the session"() {+ given:+ authenticate(false, ["write:admin"], "other-admin", callerRealm)++ when:+ resource.disconnectUserSession(null, REALM, "connection-1")++ then:+ def exception = thrown(WebApplicationException)+ exception.response.status == 405+ 0 * mqtt.disconnectSession(_)++ where:+ callerRealm << [MASTER_REALM, "other-realm"]+ }++ def "an incorrect realm in the URL is rejected even for superusers"() {+ given:+ authenticate(superUser)++ when:+ resource.disconnectUserSession(null, "other-realm", "connection-1")++ then:+ def exception = thrown(WebApplicationException)+ exception.response.status == 404+ 0 * mqtt.disconnectSession(_)++ where:+ superUser << [false, true]+ }++ def "anonymous callers cannot disconnect an existing session"() {+ given:+ resource.securityContext = Stub(SecurityContext) {+ getUserPrincipal() >> null+ }++ when:+ resource.disconnectUserSession(null, REALM, "connection-1")++ then:+ def exception = thrown(WebApplicationException)+ exception.response.status == 401+ 0 * mqtt.disconnectSession(_)+ }++ def "a missing session returns 404 without attempting a disconnect"() {+ when:+ resource.disconnectUserSession(null, REALM, "connection-1")++ then:+ def exception = thrown(WebApplicationException)+ exception.response.status == 404+ 1 * mqtt.getConnectionUserId("connection-1") >> null+ 0 * provider.getUser(_)+ 0 * mqtt.disconnectSession(_)+ }++ def "a session whose owner was deleted returns 404 without attempting a disconnect"() {+ when:+ resource.disconnectUserSession(null, REALM, "connection-1")++ then:+ def exception = thrown(WebApplicationException)+ exception.response.status == 404+ 1 * provider.getUser(USER_ID) >> null+ 0 * mqtt.disconnectSession(_)+ }++ def "a session disappearing after authorization returns 404"() {+ when:+ resource.disconnectUserSession(null, REALM, "connection-1")++ then:+ def exception = thrown(WebApplicationException)+ exception.response.status == 404+ 1 * mqtt.disconnectSession("connection-1") >> false+ }++ def "a caller cannot disconnect a session before realm activation"() {+ given:+ realm.setNotBefore((NOW / 1000 + 60) as Double)++ when:+ resource.disconnectUserSession(null, REALM, "connection-1")++ then:+ def exception = thrown(WebApplicationException)+ exception.response.status == 403+ 0 * mqtt.disconnectSession(_)+ }++ def "a session owner no longer belonging to the resolved realm prevents disconnection"() {+ when:+ resource.disconnectUserSession(null, REALM, "connection-1")++ then:+ def exception = thrown(WebApplicationException)+ exception.response.status == 405+ 1 * provider.isUserInRealm(USER_ID, REALM) >> false+ 0 * mqtt.disconnectSession(_)+ }++ private void authenticate(boolean superUser, List<String> clientRoles = ["read:admin", "write:admin"], String userId = USER_ID, String authenticatedRealm = null) {+ def principal = new TokenPrincipal(new JWTClaimsSet.Builder()+ .subject(userId)+ .issuer("http://localhost/realms/" + (authenticatedRealm ?: (superUser ? MASTER_REALM : REALM)))+ .claim("realm_access", [roles: superUser ? [SUPER_USER_REALM_ROLE] : []])+ .claim("resource_access", [(KEYCLOAK_CLIENT_ID): [roles: clientRoles]])+ .build())+ resource.securityContext = Stub(SecurityContext) {+ getUserPrincipal() >> principal+ }+ }+}diff --git a/model/src/main/java/org/openremote/model/security/UserResource.java b/model/src/main/java/org/openremote/model/security/UserResource.javaindex 5a2a30d54..3be43493b 100644--- a/model/src/main/java/org/openremote/model/security/UserResource.java+++ b/model/src/main/java/org/openremote/model/security/UserResource.java@@ -44,9 +44,20 @@ import org.openremote.model.query.UserQuery;@Tag(name = "User",description =- "Query and manage identity-provider users, roles, credentials, locale, and live sessions")+ "Query and manage identity-provider users, roles, credentials, locale, and live sessions. "+ + "An active realm is enabled and its activation time has been reached. "+ + "Superusers bypass realm activity and cross-realm restrictions; endpoint-specific role requirements still apply.")@Path("user")@OpenApiResponses.Authenticated+@ApiResponse(+ responseCode = "401",+ description = "Authentication is required or the supplied credentials are invalid",+ content = @Content(mediaType = "text/plain", schema = @Schema(implementation = String.class)))+@ApiResponse(+ responseCode = "403",+ description =+ "The caller lacks the required permissions, or the target realm is inactive and the caller is not a superuser",+ content = @Content(mediaType = "text/plain", schema = @Schema(implementation = String.class)))public interface UserResource {@GET@@ -58,7 +69,8 @@ public interface UserResource {operationId = "getClientRoles",summary = "Retrieve client roles for a realm and client",description =- "Returns all role definitions exposed by the named identity-provider client. Realm-administrator access is required.")+ "Returns all role definitions exposed by the named identity-provider client. Realm-administrator access is required. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.Ok@OpenApiResponses.NotFoundRole[] getClientRoles(@@ -75,7 +87,8 @@ public interface UserResource {operationId = "updateRoles",summary = "Update OpenRemote client roles for a realm",description =- "Creates, updates, or removes role definitions for the default OpenRemote client in the requested realm.")+ "Creates, updates, or removes role definitions for the default OpenRemote client in the requested realm. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.NoContent@OpenApiResponses.BadRequest@OpenApiResponses.NotFound@@ -96,7 +109,8 @@ public interface UserResource {operationId = "updateClientRoles",summary = "Update client roles for a realm and client",description =- "Creates, updates, or removes role definitions for a named identity-provider client.")+ "Creates, updates, or removes role definitions for a named identity-provider client. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.NoContent@OpenApiResponses.BadRequest@OpenApiResponses.NotFound@@ -119,7 +133,8 @@ public interface UserResource {operationId = "queryUsers",summary = "Query users based on criteria",description =- "Executes a UserQuery. Non-super users are forced into their authenticated realm and cannot see system accounts; callers with read-users but not read-admin receive basic fields only.")+ "Executes a UserQuery. Non-super users are forced into their authenticated realm and cannot see system accounts; callers with read-users but not read-admin receive basic fields only. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.Ok@OpenApiResponses.BadRequestUser[] query(@@ -146,7 +161,8 @@ public interface UserResource {operationId = "getUser",summary = "Retrieve a user in a realm",description =- "Returns one user when it belongs to the requested accessible realm. Without read-admin permission, callers may retrieve only their own user.")+ "Returns one user when it belongs to the requested accessible realm. Without read-admin permission, callers may retrieve only their own user. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.Ok@OpenApiResponses.NotFoundUser get(@@ -162,7 +178,8 @@ public interface UserResource {operationId = "getCurrentUser",summary = "Retrieve the currently authenticated user",description =- "Returns the identity-provider record corresponding to the current access token.")+ "Returns the identity-provider record corresponding to the current access token. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.Ok@OpenApiResponses.NotFoundUser getCurrent(@BeanParam RequestParams requestParams);@@ -176,7 +193,8 @@ public interface UserResource {operationId = "updateUser",summary = "Update a user in a realm",description =- "Updates an existing identity-provider user in an administered realm. The master administrator cannot be disabled.")+ "Updates an existing identity-provider user in an administered realm. The master administrator cannot be disabled. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.Ok@OpenApiResponses.BadRequest@OpenApiResponses.NotFound@@ -202,7 +220,8 @@ public interface UserResource {operationId = "updateSelf",summary = "Update the currently authenticated user",description =- "Updates the caller's own profile. A supplied user ID must match the access token; role and realm administration are not provided by this endpoint.")+ "Updates the caller's own profile. A supplied user ID must match the access token; role and realm administration are not provided by this endpoint. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.Ok@OpenApiResponses.BadRequest@OpenApiResponses.NotFound@@ -222,7 +241,8 @@ public interface UserResource {operationId = "createUser",summary = "Create a new user in a realm",description =- "Creates an identity-provider user in a realm administered by the caller and returns the resulting user record.")+ "Creates an identity-provider user in a realm administered by the caller and returns the resulting user record. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.Ok@OpenApiResponses.BadRequest@OpenApiResponses.Conflict@@ -251,7 +271,8 @@ public interface UserResource {operationId = "deleteUser",summary = "Delete a user from a realm",description =- "Permanently deletes a user from an administered realm. The master-realm administrator cannot be deleted.")+ "Permanently deletes a user from an administered realm. The master-realm administrator cannot be deleted. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.NoContent@OpenApiResponses.NotFound@ApiResponse(@@ -272,7 +293,8 @@ public interface UserResource {operationId = "requestUserPasswordReset",summary = "Request a password reset for a user in a realm",description =- "Asks the identity provider to send or initiate its configured password-reset action for the specified user.")+ "Asks the identity provider to send or initiate its configured password-reset action for the specified user. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.NoContent@OpenApiResponses.BadRequest@OpenApiResponses.NotFound@@ -294,7 +316,8 @@ public interface UserResource {operationId = "requestPasswordReset",summary = "Request a password reset for the current user",description =- "Initiates the identity provider's configured password-reset action for the caller's own account.")+ "Initiates the identity provider's configured password-reset action for the caller's own account. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.NoContent@OpenApiResponses.BadRequestvoid requestPasswordResetCurrent(@BeanParam RequestParams requestParams);@@ -308,7 +331,8 @@ public interface UserResource {operationId = "updatePassword",summary = "Update the password for a user in a realm",description =- "Replaces a user's credential in an administered realm using the supplied credential representation.")+ "Replaces a user's credential in an administered realm using the supplied credential representation. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.NoContent@OpenApiResponses.BadRequest@OpenApiResponses.NotFound@@ -334,7 +358,8 @@ public interface UserResource {operationId = "updateOwnPassword",summary = "Update the current user's password",description =- "Replaces the caller's own identity-provider credential using the supplied credential representation.")+ "Replaces the caller's own identity-provider credential using the supplied credential representation. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.NoContent@OpenApiResponses.BadRequestvoid updatePasswordCurrent(@@ -352,7 +377,8 @@ public interface UserResource {operationId = "resetSecret",summary = "Reset the secret for a user in a realm",description =- "Generates and returns a new client secret for a service user in an administered realm.")+ "Generates and returns a new client secret for a service user in an administered realm. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.Ok@OpenApiResponses.BadRequest@OpenApiResponses.NotFound@@ -372,7 +398,8 @@ public interface UserResource {operationId = "getUserClientRoles",summary = "Retrieve a user's client roles",description =- "Returns role names assigned to one user for the named client. Without read-admin permission, callers may retrieve only their own roles.")+ "Returns role names assigned to one user for the named client. Without read-admin permission, callers may retrieve only their own roles. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.Ok@OpenApiResponses.NotFoundString[] getUserClientRoles(@@ -390,7 +417,8 @@ public interface UserResource {operationId = "getUserRealmRoles",summary = "Retrieve a user's realm roles",description =- "Returns realm-level role names assigned to one user. Without read-admin permission, callers may retrieve only their own roles.")+ "Returns realm-level role names assigned to one user. Without read-admin permission, callers may retrieve only their own roles. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.Ok@OpenApiResponses.NotFoundString[] getUserRealmRoles(@@ -406,7 +434,8 @@ public interface UserResource {operationId = "getCurrentUserClientRoles",summary = "Retrieve the current user's client roles",description =- "Returns role names assigned to the caller for the named identity-provider client.")+ "Returns role names assigned to the caller for the named identity-provider client. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.Ok@OpenApiResponses.NotFoundString[] getCurrentUserClientRoles(@@ -420,7 +449,9 @@ public interface UserResource {@Operation(operationId = "getCurrentUserRealmRoles",summary = "Retrieve the current user's realm roles",- description = "Returns realm-level role names assigned to the caller.")+ description =+ "Returns realm-level role names assigned to the caller. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.Ok@OpenApiResponses.NotFoundString[] getCurrentUserRealmRoles(@BeanParam RequestParams requestParams);@@ -433,7 +464,8 @@ public interface UserResource {operationId = "updateUserClientRoles",summary = "Update a user's client roles",description =- "Replaces the user's assigned role names for the named client in an administered realm.")+ "Replaces the user's assigned role names for the named client in an administered realm. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.NoContent@OpenApiResponses.BadRequest@OpenApiResponses.NotFound@@ -456,7 +488,9 @@ public interface UserResource {@Operation(operationId = "updateUserRealmRoles",summary = "Update a user's realm roles",- description = "Replaces the user's assigned realm-level role names in an administered realm.")+ description =+ "Replaces the user's assigned realm-level role names in an administered realm. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.NoContent@OpenApiResponses.BadRequest@OpenApiResponses.NotFound@@ -477,7 +511,8 @@ public interface UserResource {operationId = "updateCurrentUserLocale",summary = "Update the current user's locale",description =- "Stores the supplied non-empty locale string as the caller's identity-provider locale attribute.")+ "Stores the supplied non-empty locale string as the caller's identity-provider locale attribute. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.NoContent@OpenApiResponses.BadRequest@OpenApiResponses.NotFound@@ -496,7 +531,8 @@ public interface UserResource {operationId = "getUserSessions",summary = "Retrieve live sessions for a user",description =- "Returns active MQTT sessions for one user, including connection ID, creation time, and remote address. Without read-admin permission, callers may inspect only themselves.")+ "Returns active MQTT sessions for one user, including connection ID, creation time, and remote address. Without read-admin permission, callers may inspect only themselves. "+ + "The target realm must be active unless the caller is a superuser.")@OpenApiResponses.Ok@OpenApiResponses.NotFoundUserSession[] getUserSessions(@@ -510,12 +546,34 @@ public interface UserResource {@Operation(operationId = "disconnectUserSession",summary = "Disconnect a user session",- description = "Terminates the active MQTT connection identified by sessionID.")+ description =+ "Terminates the active MQTT connection identified by sessionID. The realm must match the session owner's realm. "+ + "Authenticated users may disconnect their own sessions without an additional client role. "+ + "Disconnecting another user's session requires the openremote client role write:admin or superuser status. "+ + "Non-superusers are limited to their own active realm; superusers may disconnect sessions across realms, including inactive realms.")@OpenApiResponses.NoContent- @OpenApiResponses.NotFound+ @ApiResponse(+ responseCode = "403",+ description =+ "The realm is inactive for a non-superuser, or the caller is neither the session owner, a user with write:admin, nor a superuser",+ content = @Content(mediaType = "text/plain", schema = @Schema(implementation = String.class)))+ @ApiResponse(+ responseCode = "404",+ description =+ "The session or its owning user does not exist, or the session does not belong to the specified realm",+ content = @Content(mediaType = "text/plain", schema = @Schema(implementation = String.class)))+ @ApiResponse(+ responseCode = "405",+ description = "A non-superuser cannot access the session owner's realm",+ content = @Content(mediaType = "text/plain", schema = @Schema(implementation = String.class)))void disconnectUserSession(@BeanParam RequestParams requestParams,- @Parameter(description = REALM, example = EXAMPLE_REALM) @PathParam("realm") String realm,+ @Parameter(+ description =+ "Realm of the session owner; must match even when the caller is a superuser.",+ example = EXAMPLE_REALM)+ @PathParam("realm")+ String realm,@Parameter(description = "Active MQTT connection identifier returned by getUserSessions.",example = "mqtt-connection-7")diff --git a/test/src/test/groovy/org/openremote/test/users/UserSessionResourceTest.groovy b/test/src/test/groovy/org/openremote/test/users/UserSessionResourceTest.groovynew file mode 100644index 000000000..2e5adbb4a--- /dev/null+++ b/test/src/test/groovy/org/openremote/test/users/UserSessionResourceTest.groovy@@ -0,0 +1,142 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * SPDX-License-Identifier: AGPL-3.0-or-later+ */+package org.openremote.test.users++import com.hivemq.client.mqtt.MqttClient+import com.hivemq.client.mqtt.MqttClientState+import jakarta.ws.rs.WebApplicationException+import org.openremote.manager.mqtt.MQTTBrokerService+import org.openremote.manager.setup.SetupService+import org.openremote.model.security.UserResource+import org.openremote.model.util.UniqueIdentifierGenerator+import org.openremote.setup.integration.KeycloakTestSetup+import org.openremote.test.ManagerContainerTrait+import spock.lang.Specification+import spock.util.concurrent.PollingConditions++import static java.nio.charset.StandardCharsets.UTF_8+import static java.util.concurrent.TimeUnit.SECONDS+import static org.openremote.manager.mqtt.MQTTBrokerService.MQTT_SERVER_LISTEN_HOST+import static org.openremote.manager.mqtt.MQTTBrokerService.MQTT_SERVER_LISTEN_PORT+import static org.openremote.model.Constants.MASTER_REALM+import static org.openremote.model.util.MapAccess.getInteger+import static org.openremote.model.util.MapAccess.getString++class UserSessionResourceTest extends Specification implements ManagerContainerTrait {++ def "HTTP session disconnection by #caller enforces permissions and closes the MQTT connection"() {+ given:+ def container = startContainer(defaultConfig(), defaultServices())+ def setup = container.getService(SetupService).getTaskOfType(KeycloakTestSetup)+ def broker = container.getService(MQTTBrokerService)+ def realm = setup.realmBuilding.name+ def owner = setup.serviceUser+ def other = setup.serviceUser2+ def superuser = setup.superServiceUser+ def uri = serverUri(serverPort)+ def ownerToken = authenticate(container, realm, owner.username, owner.secret)+ def otherToken = authenticate(container, realm, other.username, other.secret)+ def superuserToken = authenticate(container, MASTER_REALM, superuser.username, superuser.secret)+ def ownerTarget = getClientApiTarget(uri, realm, ownerToken)+ def superuserTarget = getClientApiTarget(uri, MASTER_REALM, superuserToken)+ def ownerResource = ownerTarget.proxy(UserResource)+ def otherResource = getClientApiTarget(uri, realm, otherToken).proxy(UserResource)+ def anonymousResource = getClientApiTarget(uri, realm).proxy(UserResource)+ def superuserResource = superuserTarget.proxy(UserResource)+ def conditions = new PollingConditions(timeout: 15, initialDelay: 0.1, delay: 0.2)+ String sessionId = null+ def response = null++ // Use the raw client without automatic reconnect so a forced disconnect remains observable.+ def client = MqttClient.builder()+ .useMqttVersion3()+ .identifier(UniqueIdentifierGenerator.generateId())+ .serverHost(getString(container.config, MQTT_SERVER_LISTEN_HOST, "127.0.0.1"))+ .serverPort(getInteger(container.config, MQTT_SERVER_LISTEN_PORT, 1883))+ .buildAsync()++ when: "the service user opens an MQTT connection"+ client.connectWith().cleanSession(true)+ .simpleAuth().username(realm + ":" + owner.username).password(owner.secret.getBytes(UTF_8)).applySimpleAuth()+ .send().get(10, SECONDS)++ then: "the owner can discover the live session through HTTP"+ conditions.eventually {+ def sessions = ownerResource.getUserSessions(null, realm, owner.id)+ assert sessions.length == 1+ sessionId = sessions[0].getID()+ assert broker.getConnectionUserId(sessionId) == owner.id+ }++ when: "an anonymous caller attempts to disconnect it"+ anonymousResource.disconnectUserSession(null, realm, sessionId)++ then:+ def anonymousException = thrown(WebApplicationException)+ anonymousException.response.status == 401+ client.state == MqttClientState.CONNECTED+ broker.getConnectionUserId(sessionId) == owner.id++ when: "another user without write:admin attempts to disconnect it"+ otherResource.disconnectUserSession(null, realm, sessionId)++ then:+ def forbiddenException = thrown(WebApplicationException)+ forbiddenException.response.status == 403+ client.state == MqttClientState.CONNECTED+ broker.getConnectionUserId(sessionId) == owner.id++ when: "a superuser supplies the wrong realm"+ superuserResource.disconnectUserSession(null, MASTER_REALM, sessionId)++ then:+ def wrongRealmException = thrown(WebApplicationException)+ wrongRealmException.response.status == 404+ client.state == MqttClientState.CONNECTED+ broker.getConnectionUserId(sessionId) == owner.id++ when: "an authorized caller disconnects the session"+ def authorizedTarget = caller == "owner" ? ownerTarget : superuserTarget+ response = authorizedTarget.path("user/${realm}/disconnect/${sessionId}".toString()).request().get()++ then:+ response.status == 204+ conditions.eventually {+ assert client.state == MqttClientState.DISCONNECTED+ assert broker.getConnectionUserId(sessionId) == null+ assert ownerResource.getUserSessions(null, realm, owner.id).length == 0+ }++ when: "the owner repeats the request for the disconnected session"+ ownerResource.disconnectUserSession(null, realm, sessionId)++ then:+ def missingException = thrown(WebApplicationException)+ missingException.response.status == 404++ cleanup:+ response?.close()+ if (client?.state == MqttClientState.CONNECTED) {+ client.disconnect().get(10, SECONDS)+ }++ where:+ caller << ["owner", "superuser"]+ }+}