Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@
public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider
implements ManagerIdentityProvider {

private static final String MASTER_TOKEN_ROLE_FILTER = "openremote-master-token-role-filter";
private static final String OPENID_CONNECT = "openid-connect";
private static final String INCLUDE_IN_ACCESS_TOKEN = "access.token.claim";
private static final String INCLUDE_IN_INTROSPECTION = "introspection.token.claim";
private static final Logger LOG =
Logger.getLogger(ManagerKeycloakIdentityProvider.class.getName());
public static final String REALM_KEYCLOAK_THEME_SUFFIX = "_REALM_KEYCLOAK_THEME";
Expand Down Expand Up @@ -156,6 +160,67 @@ public void init(Container container) {
WebService.getExternalHostnames().stream().map(host -> "https://" + host + "/*").toList());
}

/**
* Enables the Keycloak role filter for the {@code openremote} client in the master realm.
*
* <p>The master {@code admin} role inherits management roles from every realm. The filter
* excludes those client roles and their audiences from access tokens and introspection responses,
* so adding realms does not inflate tokens. The standard {@code roles} scope still supplies realm
* roles and application client roles and audiences.
*
* <p>Called at Manager startup after setup tasks have run, so the client is available on both
* fresh installs and upgrades. The mapper is added only when Keycloak advertises it, the client
* exists, and the mapper is not already attached.
*/
public void configureMasterAccessTokenMapper() {
var mapperTypes =
keycloakTarget.proxy(ServerInfoResource.class).getInfo().getProtocolMapperTypes();
if (mapperTypes == null
|| mapperTypes.getOrDefault(OPENID_CONNECT, List.of()).stream()
.noneMatch(mapper -> MASTER_TOKEN_ROLE_FILTER.equals(mapper.getId()))) {
LOG.info("Keycloak does not provide the OpenRemote master token role filter");
return;
}

getRealms(
realms -> {
var clients = realms.realm(MASTER_REALM).clients();
var existing = clients.findByClientId(KEYCLOAK_CLIENT_ID);
if (existing.isEmpty()) {
return null;
}

var mappers = clients.get(existing.getFirst().getId()).getProtocolMappers();
if (mappers.getMappers().stream()
.anyMatch(mapper -> MASTER_TOKEN_ROLE_FILTER.equals(mapper.getProtocolMapper()))) {
return null;
}

var mapper = new ProtocolMapperRepresentation();
mapper.setName("OpenRemote master token role filter");
mapper.setProtocol(OPENID_CONNECT);
mapper.setProtocolMapper(MASTER_TOKEN_ROLE_FILTER);
mapper.setConfig(
Map.of(
INCLUDE_IN_ACCESS_TOKEN, Boolean.TRUE.toString(),
INCLUDE_IN_INTROSPECTION, Boolean.TRUE.toString()));

try (Response response = mappers.createMapper(mapper)) {
int status = response.getStatus();
if (status != Response.Status.CREATED.getStatusCode()
&& !(status == Response.Status.CONFLICT.getStatusCode()
&& mappers.getMappers().stream()
.anyMatch(
installed ->
MASTER_TOKEN_ROLE_FILTER.equals(installed.getProtocolMapper())))) {
throw new IllegalStateException(
"Could not enable the OpenRemote master token role filter (HTTP " + status + ")");
}
}
return null;
});
}

@Override
protected OAuthGrant getStoredCredentials(Container container) {
// Try and load keycloak proxy credentials from the file system
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.security.IdentityService;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.manager.security.ManagerKeycloakIdentityProvider;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
import org.openremote.model.setup.Setup;
Expand All @@ -33,7 +34,8 @@
/**
* Executes setup tasks for a clean installation when the application starts.
*
* <p>This service is disabled when {@link PersistenceService#isCleanInstall} is <code>false</code>.
* <p>Setup tasks run only on a clean installation. Keycloak client configuration is checked on
* every startup.
*
* <p>First, this service will load an implementation of {@link SetupTasks} from the classpath using
* {@link ServiceLoader}. If multiple providers are found, an error is raised. If a provider is
Expand All @@ -57,7 +59,7 @@ public void init(Container container) throws Exception {
boolean isClean = container.getService(PersistenceService.class).isCleanInstall();

if (!isClean) {
LOG.info("Setup service disabled, clean install = false");
LOG.info("Skipping setup tasks, clean install = false");
return;
}

Expand Down Expand Up @@ -114,6 +116,10 @@ public void start(Container container) {
}
LOG.info("--- START TASKS COMPLETED SUCCESSFULLY ---");
}
if (container.getService(ManagerIdentityService.class).getIdentityProvider()
instanceof ManagerKeycloakIdentityProvider keycloakProvider) {
keycloakProvider.configureMasterAccessTokenMapper();
}
} catch (Exception ex) {
throw new RuntimeException("Error setting up application", ex);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/*
* Copyright 2017, 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 jakarta.ws.rs.core.Response
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget
import org.keycloak.admin.client.resource.ClientResource
import org.keycloak.admin.client.resource.ClientsResource
import org.keycloak.admin.client.resource.ProtocolMappersResource
import org.keycloak.admin.client.resource.RealmResource
import org.keycloak.admin.client.resource.RealmsResource
import org.keycloak.admin.client.resource.ServerInfoResource
import org.keycloak.representations.idm.ClientRepresentation
import org.keycloak.representations.idm.ProtocolMapperRepresentation
import org.keycloak.representations.idm.ProtocolMapperTypeRepresentation
import org.keycloak.representations.info.ServerInfoRepresentation
import spock.lang.Specification

import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
import static org.openremote.model.Constants.MASTER_REALM

class ManagerKeycloakIdentityProviderTest extends Specification {

private static final String ROLE_FILTER = "openremote-master-token-role-filter"

private final ResteasyWebTarget target = Mock()
private final ManagerKeycloakIdentityProvider provider = new ManagerKeycloakIdentityProvider()

def setup() {
provider.keycloakTarget = target
}

def "skips master client configuration when Keycloak does not advertise the role filter"() {
given:
def serverInfo = serverInfoWithMapper("oidc-usermodel-client-role-mapper")

when:
provider.configureMasterAccessTokenMapper()

then:
1 * target.proxy(ServerInfoResource.class) >> serverInfo
0 * target._
}

def "skips mapper setup when the master OpenRemote client is missing"() {
given:
target.proxy(ServerInfoResource.class) >> serverInfoWithMapper(ROLE_FILTER)
def clients = mockMasterClients()

when:
provider.configureMasterAccessTokenMapper()

then:
1 * clients.findByClientId(KEYCLOAK_CLIENT_ID) >> []
0 * clients._
}

def "reports a forbidden response when Keycloak rejects mapper creation"() {
given:
target.proxy(ServerInfoResource.class) >> serverInfoWithMapper(ROLE_FILTER)
def clients = mockMasterClients()
def mappers = Mock(ProtocolMappersResource)
def response = Mock(Response) {
getStatus() >> Response.Status.FORBIDDEN.statusCode
}
def clientId = "master-openremote-client-id"
clients.findByClientId(KEYCLOAK_CLIENT_ID) >> [new ClientRepresentation(id: clientId)]
def client = Stub(ClientResource)
client.getProtocolMappers() >> mappers
clients.get(clientId) >> client
mappers.getMappers() >> []

when:
provider.configureMasterAccessTokenMapper()

then:
def error = thrown(IllegalStateException)
error.message == "Could not enable the OpenRemote master token role filter (HTTP 403)"
1 * mappers.createMapper(_ as ProtocolMapperRepresentation) >> response
1 * response.close()
}

private ServerInfoResource serverInfoWithMapper(String mapperId) {
def info = new ServerInfoRepresentation(protocolMapperTypes: [
"openid-connect": [new ProtocolMapperTypeRepresentation(id: mapperId)]
])
Stub(ServerInfoResource) {
getInfo() >> info
}
}

private ClientsResource mockMasterClients() {
def clients = Mock(ClientsResource)
def realm = Stub(RealmResource)
realm.clients() >> clients
def realms = Stub(RealmsResource)
realms.realm(MASTER_REALM) >> realm
target.proxy(RealmsResource.class) >> realms
clients
}
}
Loading
Loading