diff --git a/.github/workflows/keycloak.yml b/.github/workflows/keycloak.yml index a4dd75a..90613d7 100644 --- a/.github/workflows/keycloak.yml +++ b/.github/workflows/keycloak.yml @@ -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. diff --git a/Dockerfile b/Dockerfile index 314ca05..9ca47ec 100644 --- a/Dockerfile +++ b/Dockerfile @@ -36,6 +36,7 @@ ENV KC_HTTP_RELATIVE_PATH=$KC_HTTP_RELATIVE_PATH # 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 diff --git a/README.md b/README.md index f648421..c9ab8e8 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 387504e..3bc862e 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -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" } diff --git a/master-token-filter/build.gradle b/master-token-filter/build.gradle new file mode 100644 index 0000000..86a286e --- /dev/null +++ b/master-token-filter/build.gradle @@ -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 +} diff --git a/master-token-filter/src/main/java/org/openremote/keycloak/MasterTokenRoleFilter.java b/master-token-filter/src/main/java/org/openremote/keycloak/MasterTokenRoleFilter.java new file mode 100644 index 0000000..5a1e6df --- /dev/null +++ b/master-token-filter/src/main/java/org/openremote/keycloak/MasterTokenRoleFilter.java @@ -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 . + * + * 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 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); + } + } +} diff --git a/master-token-filter/src/main/resources/META-INF/services/org.keycloak.protocol.ProtocolMapper b/master-token-filter/src/main/resources/META-INF/services/org.keycloak.protocol.ProtocolMapper new file mode 100644 index 0000000..4501a47 --- /dev/null +++ b/master-token-filter/src/main/resources/META-INF/services/org.keycloak.protocol.ProtocolMapper @@ -0,0 +1 @@ +org.openremote.keycloak.MasterTokenRoleFilter diff --git a/master-token-filter/src/test/groovy/org/openremote/keycloak/MasterTokenRoleFilterTest.groovy b/master-token-filter/src/test/groovy/org/openremote/keycloak/MasterTokenRoleFilterTest.groovy new file mode 100644 index 0000000..3e80f90 --- /dev/null +++ b/master-token-filter/src/test/groovy/org/openremote/keycloak/MasterTokenRoleFilterTest.groovy @@ -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 . + * + * 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)) } + } +} diff --git a/self-register-user-configure/build.gradle b/self-register-user-configure/build.gradle index 343ed65..f3584e9 100644 --- a/self-register-user-configure/build.gradle +++ b/self-register-user-configure/build.gradle @@ -10,11 +10,8 @@ configurations { jarLibs } -repositories { - mavenCentral() -} - dependencies { + implementation platform(libs.keycloakBom) implementation libs.keycloakServerSpi implementation libs.keycloakServerSpiPrivate implementation libs.keycloakCore diff --git a/settings.gradle b/settings.gradle index 64671b9..08e434f 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,2 +1,20 @@ -include 'self-register-user-configure' -include 'theme' +dependencyResolutionManagement { + repositoriesMode = RepositoriesMode.FAIL_ON_PROJECT_REPOS + repositories { + mavenCentral() + } +} + +// A .buildignore next to a build.gradle excludes that project from discovery. +fileTree( + dir: rootDir, + include: '**/build.gradle', + excludes: ['**/.git/**', '**/.gradle/**', '**/build/**', '**/dist/**', '**/node_modules/**'] +).matching { + exclude 'build.gradle' +}.sort { it.path }.each { buildFile -> + def projectDir = buildFile.parentFile + if (!new File(projectDir, '.buildignore').exists()) { + include rootDir.toPath().relativize(projectDir.toPath()).join(':') + } +} diff --git a/theme/build.gradle b/theme/build.gradle index 8f84b9a..da35cdf 100644 --- a/theme/build.gradle +++ b/theme/build.gradle @@ -192,10 +192,6 @@ processResources.dependsOn 'unpackLoginTheme' // ui/.keycloak (gitignored). Nothing here reaches the jar. // --------------------------------------------------------------------------- -repositories { - mavenCentral() -} - /* * The Keycloak the image actually runs, taken from the Dockerfile's ARG VERSION, because the * pages to compare against are the ones that version serves. The version catalog's keycloak