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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/keycloak.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ jobs:
with:
node-version: '22'

- name: Run Gradle tests
run: ./gradlew test

# downloadStockKeycloak fetches Keycloak's own themes, FreeMarker and Jackson so the local dev
# server can render stock pages. None of it goes in the image, so CI skips it rather than
# downloading it on every run and failing a release if Maven Central is unreachable.
Expand Down
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
# Install custom providers
COPY --chown=keycloak:keycloak build/image/openremote-theme-provider.jar /opt/keycloak/providers
COPY --chown=keycloak:keycloak build/image/openremote-self-register-configure-event-listener.jar /opt/keycloak/providers
COPY --chown=keycloak:keycloak build/image/openremote-master-token-filter.jar /opt/keycloak/providers

WORKDIR /opt/keycloak

Expand Down Expand Up @@ -76,17 +77,17 @@
ENV KC_DB_URL_DATABASE=openremote
ENV KC_DB_SCHEMA=public
ENV KC_DB_USERNAME=postgres
ENV KC_DB_PASSWORD=postgres

Check warning on line 80 in Dockerfile

View workflow job for this annotation

GitHub Actions / CI/CD

Sensitive data should not be used in the ARG or ENV commands

SecretsUsedInArgOrEnv: Do not use ARG or ENV instructions for sensitive data (ENV "KC_DB_PASSWORD") More info: https://docs.docker.com/go/dockerfile/rule/secrets-used-in-arg-or-env/
ENV KC_HTTP_ENABLED=true
ENV KC_LOG_CONSOLE_FORMAT='%-5p [%c] (%t) %s%e%n'
ENV KC_PROXY_HEADERS=xforwarded
ENV KC_LOG_LEVEL=info
ENV KC_BOOTSTRAP_ADMIN_USERNAME=admin
ENV KC_BOOTSTRAP_ADMIN_PASSWORD=secret

Check warning on line 86 in Dockerfile

View workflow job for this annotation

GitHub Actions / CI/CD

Sensitive data should not be used in the ARG or ENV commands

SecretsUsedInArgOrEnv: Do not use ARG or ENV instructions for sensitive data (ENV "KC_BOOTSTRAP_ADMIN_PASSWORD") More info: https://docs.docker.com/go/dockerfile/rule/secrets-used-in-arg-or-env/
ENV KEYCLOAK_SELF_REGISTERED_USER_ROLES="{ }"

HEALTHCHECK --interval=3s --timeout=3s --start-period=30s --retries=120 CMD curl --head -fsS http://localhost:9000/auth/health/ready || exit 1

EXPOSE 8080

ENTRYPOINT exec /opt/keycloak/bin/kc.sh ${KEYCLOAK_START_COMMAND:-start} --spi-events-listener-self-register-user-configure-self-registered-user-roles="${KEYCLOAK_SELF_REGISTERED_USER_ROLES:-}" ${KEYCLOAK_START_OPTS:-}

Check warning on line 93 in Dockerfile

View workflow job for this annotation

GitHub Actions / CI/CD

JSON arguments recommended for ENTRYPOINT/CMD to prevent unintended behavior related to OS signals

JSONArgsRecommended: JSON arguments recommended for ENTRYPOINT to prevent unintended behavior related to OS signals More info: https://docs.docker.com/go/dockerfile/rule/json-args-recommended/
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,26 @@ Pages address Keycloak's own message keys, and Keycloak resolves them while it r
The wording is Keycloak's, including in English. This theme does not keep a house-style copy deck: an override can only be written in one language at a time, so it would show on an English page and nowhere else, and the theme would own auth copy it has no way to translate. A string that reads wrong reads wrong in every language, and the fix belongs in Keycloak.

`theme/ui/src/i18n.ts` therefore holds only two things, both explained there: the handful of keys Keycloak ships no message for in any language, and the stripping of the literal `«` that Keycloak prefixes to its back-links, which the stylesheet already draws as a chevron.

## Compact master OpenRemote tokens

Keycloak adds a management client for each realm, and the master realm's `admin` role inherits those clients' roles.
As realms are added, those roles and their audiences can make master access tokens too large for proxy requests.

The image includes the `openremote-master-token-role-filter` protocol mapper for the `openremote` client in the `master` realm.
It excludes Keycloak's realm-management clients from the client role claims and role-derived audiences in access tokens and introspection responses.
The stock `roles` scope continues to provide realm roles, application client roles, and their audiences.

A compatible OpenRemote Manager attaches the mapper at startup when Keycloak advertises it.
Upgrade the Keycloak image before starting the Manager version that enables the mapper.
If the mapper is unavailable, the Manager leaves the client configuration alone and checks again on its next startup.
Users receive compact tokens on their next login or token refresh.

From the repository root, run these Gradle tasks to test the mapper and package its JAR.

```shell
./gradlew :master-token-filter:test
./gradlew :master-token-filter:installDist
```

The build copies the JAR to `build/image/openremote-master-token-filter.jar` for the Docker image build.
31 changes: 15 additions & 16 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
[versions]
autoService = "1.1.1"
byteBuddy = "1.17.5"
groovy = "6.0.1"
jackson = "2.22.2"
jbossLogging = "3.6.1.Final"
keycloak = "26.6.4"
lombok = "1.18.38"
slf4j = "2.0.17"
junit = "6.1.3"
keycloak = "26.8.2"
spock = "2.5-groovy-6.0"

[libraries]
autoService = { module = "com.google.auto.service:auto-service", version.ref = "autoService" }
byteBuddy = { module = "net.bytebuddy:byte-buddy", version.ref = "byteBuddy" }
byteBuddyAgent = { module = "net.bytebuddy:byte-buddy-agent", version.ref = "byteBuddy" }
groovy = { module = "org.apache.groovy:groovy", version.ref = "groovy" }
jacksonDatabind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "jackson" }
jbossLogging = { module = "org.jboss.logging:jboss-logging", version.ref = "jbossLogging" }
keycloakCore = { module = "org.keycloak:keycloak-core", version.ref = "keycloak" }
keycloakServerSpi = { module = "org.keycloak:keycloak-server-spi", version.ref = "keycloak" }
keycloakServerSpiPrivate = { module = "org.keycloak:keycloak-server-spi-private", version.ref = "keycloak" }
keycloakServices = { module = "org.keycloak:keycloak-services", version.ref = "keycloak" }
lombok = { module = "org.projectlombok:lombok", version.ref = "lombok" }
slf4jApi = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" }
jbossLogging = { module = "org.jboss.logging:jboss-logging" }
junitBom = { module = "org.junit:junit-bom", version.ref = "junit" }
junitPlatformLauncher = { module = "org.junit.platform:junit-platform-launcher" }
keycloakBom = { module = "org.keycloak:keycloak-dependencies-server-min", version.ref = "keycloak" }
keycloakCore = { module = "org.keycloak:keycloak-core" }
keycloakServerSpi = { module = "org.keycloak:keycloak-server-spi" }
keycloakServerSpiPrivate = { module = "org.keycloak:keycloak-server-spi-private" }
keycloakServices = { module = "org.keycloak:keycloak-services" }
spockBom = { module = "org.spockframework:spock-bom", version.ref = "spock" }
spockCore = { module = "org.spockframework:spock-core" }
32 changes: 32 additions & 0 deletions master-token-filter/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
plugins {
id 'groovy'
}

base {
archivesName = 'openremote-master-token-filter'
}

dependencies {
compileOnly platform(libs.keycloakBom)
compileOnly libs.keycloakServices
testImplementation platform(libs.keycloakBom)
testImplementation libs.keycloakServices
testImplementation platform(libs.junitBom)
testImplementation libs.groovy
testImplementation platform(libs.spockBom)
testImplementation libs.spockCore
testRuntimeOnly libs.junitPlatformLauncher
}

tasks.named('test') {
useJUnitPlatform()
}

tasks.register('installDist', Copy) {
into "${rootDir}/build/image"
from jar.outputs
}

tasks.withType(JavaCompile).configureEach {
options.release = 21
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* Copyright 2016, 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.keycloak;

import java.util.List;
import java.util.Objects;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientSessionContext;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.protocol.ProtocolMapperUtils;
import org.keycloak.protocol.oidc.mappers.AbstractOIDCProtocolMapper;
import org.keycloak.protocol.oidc.mappers.OIDCAccessTokenMapper;
import org.keycloak.protocol.oidc.mappers.TokenIntrospectionTokenMapper;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.representations.IDToken;
import org.keycloak.utils.RoleResolveUtil;

public final class MasterTokenRoleFilter extends AbstractOIDCProtocolMapper
implements OIDCAccessTokenMapper, TokenIntrospectionTokenMapper {

public static final String PROVIDER_ID = "openremote-master-token-role-filter";

@Override
public String getId() {
return PROVIDER_ID;
}

@Override
public String getDisplayCategory() {
return TOKEN_MAPPER_CATEGORY;
}

@Override
public String getDisplayType() {
return "OpenRemote master token role filter";
}

@Override
public String getHelpText() {
return "Exclude Keycloak realm management client roles from master OpenRemote tokens.";
}

@Override
public List<ProviderConfigProperty> getConfigProperties() {
return List.of();
}

@Override
public int getPriority() {
// Run after role transformations and before Keycloak derives the audience and role claims.
return ProtocolMapperUtils.PRIORITY_AUDIENCE_RESOLVE_MAPPER - 1;
}

@Override
protected void setClaim(IDToken token, ProtocolMapperModel mapper, UserSessionModel userSession,
KeycloakSession session, ClientSessionContext clientSession) {
ClientModel client = clientSession.getClientSession().getClient();
RealmModel realm = client.getRealm();
if (!"master".equals(realm.getName()) || !"openremote".equals(client.getClientId())) {
return;
}

// Audience Resolve and the client-role mapper share these per-client resolved roles.
var resolvedRoles = RoleResolveUtil.getAllResolvedClientRoles(session, clientSession);
if (!resolvedRoles.isEmpty()) {
session.realms().getRealmsStream()
.map(RealmModel::getMasterAdminClient)
.filter(Objects::nonNull)
.map(ClientModel::getClientId)
.forEach(resolvedRoles::remove);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
org.openremote.keycloak.MasterTokenRoleFilter
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
/*
* Copyright 2016, 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.keycloak

import org.keycloak.models.AuthenticatedClientSessionModel
import org.keycloak.models.ClientModel
import org.keycloak.models.ClientSessionContext
import org.keycloak.models.KeycloakContext
import org.keycloak.models.KeycloakSession
import org.keycloak.models.ProtocolMapperModel
import org.keycloak.models.RealmModel
import org.keycloak.models.RealmProvider
import org.keycloak.models.UserSessionModel
import org.keycloak.protocol.ProtocolMapperUtils
import org.keycloak.protocol.oidc.mappers.AudienceResolveProtocolMapper
import org.keycloak.representations.AccessToken
import spock.lang.Specification

import java.util.stream.Stream

class MasterTokenRoleFilterTest extends Specification {

MasterTokenRoleFilter filter = new MasterTokenRoleFilter()
AccessToken resolvedRoles = new AccessToken()
KeycloakSession session = Mock()
ClientSessionContext clientSession = Stub()
UserSessionModel userSession = Stub()
RealmModel realm = Stub()
ClientModel client = Stub()
ProtocolMapperModel config = new ProtocolMapperModel()

def setup() {
def authenticatedClient = Stub(AuthenticatedClientSessionModel)
clientSession.getClientSession() >> authenticatedClient
authenticatedClient.getClient() >> client
authenticatedClient.getUserSession() >> userSession
userSession.getId() >> "session-id"
client.getId() >> "client-id"
client.getRealm() >> realm

def context = Stub(KeycloakContext)
session.getContext() >> context
context.getClient() >> client
session.getAttribute(_ as String, AccessToken) >> resolvedRoles
config.setConfig(["access.token.claim": "true", "introspection.token.claim": "true"])
}

def "filters only management clients before audience resolution"() {
given:
client.getClientId() >> "openremote"
realm.getName() >> "master"
managedClients("master-realm", "tenant-management")
resolvedRoles.addAccess("master-realm").addRole("manage-realm")
resolvedRoles.addAccess("tenant-management").addRole("manage-users")
resolvedRoles.addAccess("reports-realm").addRole("viewer")
resolvedRoles.addAccess("openremote").addRole("read:assets")
resolvedRoles.addAccess("account").addRole("view-profile")
def realmAccess = new AccessToken.Access()
realmAccess.addRole("admin")
resolvedRoles.setRealmAccess(realmAccess)
def token = new AccessToken()
def audienceMapper = new AudienceResolveProtocolMapper()

when:
filter.transformAccessToken(token, config, session, userSession, clientSession)
audienceMapper.transformAccessToken(token,
AudienceResolveProtocolMapper.createClaimMapper("audience", true, true),
session, userSession, clientSession)

then:
resolvedRoles.resourceAccess.keySet() == ["reports-realm", "openremote", "account"] as Set
resolvedRoles.getResourceAccess("reports-realm").roles == ["viewer"] as Set
resolvedRoles.realmAccess.roles == ["admin"] as Set
token.audience.toSet() == ["reports-realm", "account"] as Set
filter.priority > ProtocolMapperUtils.PRIORITY_HARDCODED_ROLE_MAPPER
filter.priority < audienceMapper.priority
}

def "filters management roles during introspection"() {
given:
client.getClientId() >> "openremote"
realm.getName() >> "master"
managedClients("tenant-management")
resolvedRoles.addAccess("tenant-management").addRole("manage-users")
resolvedRoles.addAccess("reports").addRole("viewer")

when:
filter.transformIntrospectionToken(new AccessToken(), config, session, userSession, clientSession)

then:
resolvedRoles.resourceAccess.keySet() == ["reports"] as Set
}

def "leaves management roles untouched for #clientId in #realmName"() {
given:
client.getClientId() >> clientId
realm.getName() >> realmName
resolvedRoles.addAccess("tenant-management").addRole("manage-users")

when:
filter.transformAccessToken(new AccessToken(), config, session, userSession, clientSession)

then:
resolvedRoles.getResourceAccess("tenant-management").roles == ["manage-users"] as Set
0 * session.realms()

where:
clientId | realmName
"admin-cli" | "master"
"openremote" | "tenant"
}

def "skips realm lookup when no client roles are resolved"() {
given:
client.getClientId() >> "openremote"
realm.getName() >> "master"

when:
filter.transformAccessToken(new AccessToken(), config, session, userSession, clientSession)

then:
resolvedRoles.resourceAccess.isEmpty()
0 * session.realms()
}

private void managedClients(String... clientIds) {
def realmProvider = Stub(RealmProvider)
session.realms() >> realmProvider
def managedRealms = clientIds.collect { clientId ->
def managedRealm = Stub(RealmModel)
def managementClient = Stub(ClientModel)
managedRealm.getMasterAdminClient() >> managementClient
managementClient.getClientId() >> clientId
managedRealm
}
def realmWithoutManagementClient = Stub(RealmModel)
realmWithoutManagementClient.getMasterAdminClient() >> null
realmProvider.getRealmsStream() >> { Stream.concat(managedRealms.stream(), Stream.of(realmWithoutManagementClient)) }
}
}
5 changes: 1 addition & 4 deletions self-register-user-configure/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,8 @@ configurations {
jarLibs
}

repositories {
mavenCentral()
}

dependencies {
implementation platform(libs.keycloakBom)
implementation libs.keycloakServerSpi
implementation libs.keycloakServerSpiPrivate
implementation libs.keycloakCore
Expand Down
Loading
Loading