From 60848207385edf452b4d3021d915fa3833452071 Mon Sep 17 00:00:00 2001 From: Pedro Igor Date: Mon, 10 Jun 2024 10:30:09 -0300 Subject: [PATCH 001/103] Fixing broken link (#30299) (#30301) Signed-off-by: Pedro Igor --- docs/documentation/release_notes/topics/25_0_0.adoc | 2 +- .../server_admin/topics/assembly-managing-organizations.adoc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/documentation/release_notes/topics/25_0_0.adoc b/docs/documentation/release_notes/topics/25_0_0.adoc index 48676f83063..ad4465fa4b0 100644 --- a/docs/documentation/release_notes/topics/25_0_0.adoc +++ b/docs/documentation/release_notes/topics/25_0_0.adoc @@ -244,4 +244,4 @@ This remaining work is mainly about preparing the feature for production deploym on the feedback we get until the next major release, we might eventually accept additional capabilities and add more value to the feature, without compromising its roadmap. -For more details, see link:{adminguide_link}#_managing_organizations_[{adminguide_name}]. +For more details, see link:{adminguide_link}#_managing_organizations[{adminguide_name}]. diff --git a/docs/documentation/server_admin/topics/assembly-managing-organizations.adoc b/docs/documentation/server_admin/topics/assembly-managing-organizations.adoc index d6f077742b5..c8f32e7a8da 100644 --- a/docs/documentation/server_admin/topics/assembly-managing-organizations.adoc +++ b/docs/documentation/server_admin/topics/assembly-managing-organizations.adoc @@ -1,5 +1,5 @@ [id="assembly-managing-organizations_{context}"] -[[_managing_organizations_]] +[[_managing_organizations]] == Managing organizations :tech_feature_name: Organizations From ee60406a58c60471bb0a341d425bdd5acd97dbcc Mon Sep 17 00:00:00 2001 From: rmartinc Date: Mon, 10 Jun 2024 11:20:40 +0200 Subject: [PATCH 002/103] Logout from all clients after IdP logout is performed Closes #25234 Signed-off-by: rmartinc (cherry picked from commit 7d05a7a013495a8c59c3bdc71a04f743d3391b34) --- .../managers/AuthenticationManager.java | 14 ++--- .../broker/AbstractBaseBrokerTest.java | 2 +- .../broker/KcOidcBrokerLogoutTest.java | 53 ++++++++++++++++++- 3 files changed, 59 insertions(+), 10 deletions(-) diff --git a/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java b/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java index 99de7e8d86b..10fd0e7523b 100755 --- a/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java +++ b/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java @@ -645,16 +645,11 @@ public static Response browserLogout(KeycloakSession session, final AuthenticationSessionManager asm = new AuthenticationSessionManager(session); AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, true); - Response response = browserLogoutAllClients(userSession, session, realm, headers, uriInfo, logoutAuthSession); - if (response != null) { - return response; - } - String brokerId = userSession.getNote(Details.IDENTITY_PROVIDER); String initiatingIdp = logoutAuthSession.getAuthNote(AuthenticationManager.LOGOUT_INITIATING_IDP); if (brokerId != null && !brokerId.equals(initiatingIdp)) { IdentityProvider identityProvider = IdentityBrokerService.getIdentityProvider(session, realm, brokerId); - response = identityProvider.keycloakInitiatedBrowserLogout(session, userSession, uriInfo, realm); + Response response = identityProvider.keycloakInitiatedBrowserLogout(session, userSession, uriInfo, realm); if (response != null) { return response; } @@ -688,6 +683,11 @@ public static Response finishBrowserLogout(KeycloakSession session, RealmModel r final AuthenticationSessionManager asm = new AuthenticationSessionManager(session); AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, true); + Response response = browserLogoutAllClients(userSession, session, realm, headers, uriInfo, logoutAuthSession); + if (response != null) { + return response; + } + checkUserSessionOnlyHasLoggedOutClients(realm, userSession, logoutAuthSession); // For resolving artifact we don't need any cookie, all details are stored in session storage so we can remove @@ -703,7 +703,7 @@ public static Response finishBrowserLogout(KeycloakSession session, RealmModel r .setEventBuilder(event); - Response response = protocol.finishBrowserLogout(userSession, logoutAuthSession); + response = protocol.finishBrowserLogout(userSession, logoutAuthSession); // It may be possible that there are some client sessions that are still in LOGGING_OUT state long numberOfUnconfirmedSessions = userSession.getAuthenticatedClientSessions().values().stream() diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBaseBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBaseBrokerTest.java index e25f9d107b6..a071c40f543 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBaseBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractBaseBrokerTest.java @@ -342,7 +342,7 @@ protected void executeLogoutFromRealm(String contextRoot, String realm, String i .clientId(clientId) .initiatingIdp(initiatingIdp); - if (clientId != null || idTokenHint != null) { + if (redirectUri != null && (clientId != null || idTokenHint != null)) { builder.postLogoutRedirectUri(encodeUrl(redirectUri)); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutTest.java index d0bce18f0f1..733bdaab062 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/KcOidcBrokerLogoutTest.java @@ -1,5 +1,6 @@ package org.keycloak.testsuite.broker; +import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.keycloak.OAuth2Constants; @@ -8,11 +9,14 @@ import org.keycloak.admin.client.resource.RealmResource; import org.keycloak.common.VerificationException; import org.keycloak.cookie.CookieType; +import org.keycloak.protocol.oidc.OIDCConfigAttributes; import org.keycloak.representations.IDToken; import org.keycloak.representations.idm.IdentityProviderRepresentation; import org.keycloak.testsuite.AssertEvents; +import org.keycloak.testsuite.updaters.ClientAttributeUpdater; import org.keycloak.testsuite.util.AccountHelper; import org.keycloak.testsuite.util.OAuthClient; +import org.keycloak.testsuite.util.WaitUtils; import static org.junit.Assert.assertEquals; import static org.keycloak.testsuite.broker.BrokerTestConstants.REALM_CONS_NAME; @@ -22,7 +26,6 @@ import java.util.HashMap; import java.util.Map; -import java.util.concurrent.TimeUnit; public class KcOidcBrokerLogoutTest extends AbstractKcOidcBrokerLogoutTest { @@ -162,7 +165,6 @@ public void testFrontChannelLogoutRequestsSendingOnlyClientId() { identityProviderResource.update(representation); logInAsUserInIDPForFirstTime(); appPage.assertCurrent(); - driver.manage().timeouts().pageLoadTimeout(1, TimeUnit.DAYS); executeLogoutFromRealm( getConsumerRoot(), bc.consumerRealmName(), @@ -231,4 +233,51 @@ public void testFrontChannelLogoutRequestsSendingOnlyIdTokenHint() throws Verifi identityProviderResource.update(representation); } } + + @Test + public void testFrontChannelLogoutRequestsSendingOnlyClientIdWithFrontChannelLogoutApp() throws Exception { + RealmResource realm = adminClient.realm(bc.consumerRealmName()); + IdentityProviderResource identityProviderResource = realm.identityProviders().get(bc.getIDPAlias()); + IdentityProviderRepresentation representation = identityProviderResource.toRepresentation(); + Map config = representation.getConfig(); + Map originalConfig = new HashMap<>(config); + + try (ClientAttributeUpdater clientUpdater = ClientAttributeUpdater.forClient(adminClient, bc.consumerRealmName(), "broker-app") + .setFrontchannelLogout(true) + .setAttribute(OIDCConfigAttributes.FRONT_CHANNEL_LOGOUT_URI, getConsumerRoot() + "/auth/realms/" + bc.consumerRealmName() + "/app/logout") + .update()){ + config.put("backchannelSupported", Boolean.FALSE.toString()); + config.put("sendIdTokenOnLogout", Boolean.FALSE.toString()); + config.put("sendClientIdOnLogout", Boolean.TRUE.toString()); + identityProviderResource.update(representation); + logInAsUserInIDPForFirstTime(); + appPage.assertCurrent(); + executeLogoutFromRealm( + getConsumerRoot(), + bc.consumerRealmName(), + "something-else", + null, + "broker-app", + null + ); + logoutConfirmPage.isCurrent(); + // confirm logout at consumer + logoutConfirmPage.confirmLogout(); + // confirm logout at provider + logoutConfirmPage.confirmLogout(); + + WaitUtils.waitForPageToLoad(); + logoutConfirmPage.isCurrent(); + Assert.assertTrue(driver.getPageSource().contains("You are logging out from following apps")); + Assert.assertTrue(driver.getPageSource().contains("broker-app")); + + oauth.clientId("account"); + oauth.redirectUri(getConsumerRoot() + "/auth/realms/" + REALM_PROV_NAME + "/account"); + loginPage.open(REALM_PROV_NAME); + waitForPage(driver, "sign in to provider", true); + } finally { + representation.setConfig(originalConfig); + identityProviderResource.update(representation); + } + } } From 338a472ba50b8e923721ebd7985bee498ce32219 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niko=20Ko=CC=88bler?= Date: Mon, 10 Jun 2024 18:26:17 +0200 Subject: [PATCH 003/103] add missing doXXX methods with KeycloakSession usage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit closes #30302 Signed-off-by: Niko Köbler (cherry picked from commit 72f994dc1c55b76a2fe250185b5005f504ab402c) --- .../keycloak/broker/provider/util/SimpleHttp.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/server-spi-private/src/main/java/org/keycloak/broker/provider/util/SimpleHttp.java b/server-spi-private/src/main/java/org/keycloak/broker/provider/util/SimpleHttp.java index dc3c917acfa..91ce10229ee 100755 --- a/server-spi-private/src/main/java/org/keycloak/broker/provider/util/SimpleHttp.java +++ b/server-spi-private/src/main/java/org/keycloak/broker/provider/util/SimpleHttp.java @@ -125,14 +125,29 @@ protected static SimpleHttp doPost(String url, HttpClient client, long maxConsu return new SimpleHttp(url, "POST", client, maxConsumedResponseSize); } + public static SimpleHttp doPut(String url, KeycloakSession session) { + HttpClientProvider provider = session.getProvider(HttpClientProvider.class); + return doPut(url, provider.getHttpClient(), provider.getMaxConsumedResponseSize()); + } + protected static SimpleHttp doPut(String url, HttpClient client, long maxConsumedResponseSize) { return new SimpleHttp(url, "PUT", client, maxConsumedResponseSize); } + public static SimpleHttp doHead(String url, KeycloakSession session) { + HttpClientProvider provider = session.getProvider(HttpClientProvider.class); + return doHead(url, provider.getHttpClient(), provider.getMaxConsumedResponseSize()); + } + protected static SimpleHttp doHead(String url, HttpClient client, long maxConsumedResponseSize) { return new SimpleHttp(url, "HEAD", client, maxConsumedResponseSize); } + public static SimpleHttp doPatch(String url, KeycloakSession session) { + HttpClientProvider provider = session.getProvider(HttpClientProvider.class); + return doPatch(url, provider.getHttpClient(), provider.getMaxConsumedResponseSize()); + } + protected static SimpleHttp doPatch(String url, HttpClient client, long maxConsumedResponseSize) { return new SimpleHttp(url, "PATCH", client, maxConsumedResponseSize); } From ee4dc6cfff35eb723eaeda8fceb746e917d34eff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=A1clav=20Muzik=C3=A1=C5=99?= Date: Wed, 12 Jun 2024 10:42:52 +0200 Subject: [PATCH 004/103] Enhance masking around config-keystore (#30348) (#30363) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #30346 Signed-off-by: Václav Muzikář (cherry picked from commit 375ea9da0325e68b5feab35a855e40215c81c637) --- docs/guides/server/configuration.adoc | 2 +- .../keycloak/quarkus/runtime/cli/Picocli.java | 4 ++-- .../runtime/cli/command/ShowConfig.java | 6 +++-- .../KeycloakConfigSourceProvider.java | 6 ++++- .../ConfigKeystorePropertyMappers.java | 1 + .../mappers/PropertyMappers.java | 9 ++++++-- .../it/cli/ShowConfigCommandTest.java | 22 +++++++++++++++---- .../keycloak-keystore.conf | 2 ++ 8 files changed, 40 insertions(+), 12 deletions(-) create mode 100644 quarkus/tests/integration/src/test/resources/ShowConfigCommandTest/keycloak-keystore.conf diff --git a/docs/guides/server/configuration.adoc b/docs/guides/server/configuration.adoc index dbb09dcaacb..33b6a7629d5 100644 --- a/docs/guides/server/configuration.adoc +++ b/docs/guides/server/configuration.adoc @@ -124,7 +124,7 @@ After executing the command, you will be prompted to *Enter the password to be s When the KeyStore is created, you can start the server using the following parameters: -<@kc.start parameters="--config-keystore=/path/to/keystore.p12 --config-keystore-password=storepass --config-keystore-type=PKCS12"/> +<@kc.start parameters="--config-keystore=/path/to/keystore.p12 --config-keystore-password=keystorepass --config-keystore-type=PKCS12"/> === Format for raw Quarkus properties In most cases, the available configuration options should suffice to configure the server. diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Picocli.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Picocli.java index c8b87dafe56..4e639cf9d4e 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Picocli.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Picocli.java @@ -34,7 +34,7 @@ import static org.keycloak.quarkus.runtime.configuration.Configuration.getRawPersistedProperty; import static org.keycloak.quarkus.runtime.configuration.Configuration.getRuntimeProperty; import static org.keycloak.quarkus.runtime.configuration.MicroProfileConfigProvider.NS_KEYCLOAK_PREFIX; -import static org.keycloak.quarkus.runtime.configuration.mappers.PropertyMappers.formatValue; +import static org.keycloak.quarkus.runtime.configuration.mappers.PropertyMappers.maskValue; import static org.keycloak.quarkus.runtime.configuration.mappers.PropertyMappers.isBuildTimeProperty; import static org.keycloak.utils.StringUtil.isNotBlank; import static picocli.CommandLine.Model.UsageMessageSpec.SECTION_KEY_COMMAND_LIST; @@ -222,7 +222,7 @@ public void accept(String key, String value) { return; } - properties.add(key + "=" + formatValue(key, value)); + properties.add(key + "=" + maskValue(key, value)); } }, arg -> { properties.add(arg); diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/ShowConfig.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/ShowConfig.java index 088e35530a6..6257f5ed3d1 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/ShowConfig.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/ShowConfig.java @@ -22,7 +22,7 @@ import static org.keycloak.quarkus.runtime.configuration.Configuration.getConfigValue; import static org.keycloak.quarkus.runtime.configuration.Configuration.getPropertyNames; import static org.keycloak.quarkus.runtime.configuration.Configuration.getRuntimeProperty; -import static org.keycloak.quarkus.runtime.configuration.mappers.PropertyMappers.formatValue; +import static org.keycloak.quarkus.runtime.configuration.mappers.PropertyMappers.maskValue; import java.util.HashSet; import java.util.List; @@ -148,7 +148,9 @@ private void printProperty(String property) { value = getRuntimeProperty(property).orElse(value); } - spec.commandLine().getOut().printf("\t%s = %s (%s)%n", configValue.getName(), formatValue(configValue.getName(), value), KeycloakConfigSourceProvider.getConfigSourceDisplayName(configValue.getConfigSourceName())); + value = maskValue(configValue.getName(), value, configValue.getConfigSourceName()); + + spec.commandLine().getOut().printf("\t%s = %s (%s)%n", configValue.getName(), value, KeycloakConfigSourceProvider.getConfigSourceDisplayName(configValue.getConfigSourceName())); } private static String groupProperties(String property) { diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/KeycloakConfigSourceProvider.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/KeycloakConfigSourceProvider.java index 3a5a1c1e08d..ba702dad3ef 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/KeycloakConfigSourceProvider.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/KeycloakConfigSourceProvider.java @@ -100,9 +100,13 @@ public static String getConfigSourceDisplayName(String configSource) { if (configSource == null) { return "Derived"; } - if (configSource.startsWith("KeyStoreConfigSource")) { + if (isKeyStoreConfigSource(configSource)) { return "config-keystore"; } return CONFIG_SOURCE_DISPLAY_NAMES.getOrDefault(configSource, configSource); } + + public static boolean isKeyStoreConfigSource(String configSourceName) { + return configSourceName.contains("KeyStoreConfigSource"); + } } diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/ConfigKeystorePropertyMappers.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/ConfigKeystorePropertyMappers.java index c4505054579..804bf3cbaf1 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/ConfigKeystorePropertyMappers.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/ConfigKeystorePropertyMappers.java @@ -29,6 +29,7 @@ public static PropertyMapper[] getConfigKeystorePropertyMappers() { .to(SMALLRYE_KEYSTORE_PASSWORD) .transformer(ConfigKeystorePropertyMappers::validatePassword) .paramLabel("config-keystore-password") + .isMasked(true) .build(), fromOption(ConfigKeystoreOptions.CONFIG_KEYSTORE_TYPE) .to("smallrye.config.source.keystore.kc-default.type") diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/PropertyMappers.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/PropertyMappers.java index 195666da70c..38401210ce2 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/PropertyMappers.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/PropertyMappers.java @@ -34,6 +34,7 @@ import static org.keycloak.quarkus.runtime.Environment.isParsedCommand; import static org.keycloak.quarkus.runtime.Environment.isRebuild; import static org.keycloak.quarkus.runtime.Environment.isRebuildCheck; +import static org.keycloak.quarkus.runtime.configuration.KeycloakConfigSourceProvider.isKeyStoreConfigSource; public final class PropertyMappers { @@ -125,11 +126,15 @@ public static void sanitizeDisabledMappers() { MAPPERS.sanitizeDisabledMappers(); } - public static String formatValue(String property, String value) { + public static String maskValue(String property, String value) { + return maskValue(property, value, null); + } + + public static String maskValue(String property, String value, String configSourceName) { property = removeProfilePrefixIfNeeded(property); PropertyMapper mapper = getMapper(property); - if (mapper != null && mapper.isMask()) { + if ((configSourceName != null && isKeyStoreConfigSource(configSourceName) || (mapper != null && mapper.isMask()))) { return VALUE_MASK; } diff --git a/quarkus/tests/integration/src/test/java/org/keycloak/it/cli/ShowConfigCommandTest.java b/quarkus/tests/integration/src/test/java/org/keycloak/it/cli/ShowConfigCommandTest.java index 55581227698..5d126e65e31 100644 --- a/quarkus/tests/integration/src/test/java/org/keycloak/it/cli/ShowConfigCommandTest.java +++ b/quarkus/tests/integration/src/test/java/org/keycloak/it/cli/ShowConfigCommandTest.java @@ -17,17 +17,19 @@ package org.keycloak.it.cli; +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.junit.main.Launch; +import io.quarkus.test.junit.main.LaunchResult; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.keycloak.it.junit5.extension.CLITest; import org.keycloak.it.junit5.extension.ConfigurationTestResource; - -import io.quarkus.test.common.QuarkusTestResource; -import io.quarkus.test.junit.main.Launch; -import io.quarkus.test.junit.main.LaunchResult; import org.keycloak.quarkus.runtime.cli.command.ShowConfig; import org.keycloak.quarkus.runtime.configuration.mappers.PropertyMappers; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; import static org.keycloak.quarkus.runtime.cli.command.Main.CONFIG_FILE_LONG_NAME; @QuarkusTestResource(value = ConfigurationTestResource.class, restrictToAnnotatedClass = true) @@ -59,4 +61,16 @@ void testShowConfigCommandHidesCredentialsInProfiles(LaunchResult result) { Assertions.assertFalse(output.contains("testpw3")); Assertions.assertTrue(output.contains("kc.db-password = " + PropertyMappers.VALUE_MASK)); } + + @Test + @Launch({ CONFIG_FILE_LONG_NAME+"=src/test/resources/ShowConfigCommandTest/keycloak-keystore.conf", ShowConfig.NAME, "all" }) + void testSmallRyeKeyStoreConfigSource(LaunchResult result) { + // keystore is shared with QuarkusPropertiesDistTest#testSmallRyeKeyStoreConfigSource + String output = result.getOutput(); + assertThat(output, containsString("kc.config-keystore-password = " + PropertyMappers.VALUE_MASK)); + assertThat(output, containsString("kc.log-level = " + PropertyMappers.VALUE_MASK)); + + assertThat(output, not(containsString("secret"))); + assertThat(output, not(containsString("debug"))); + } } diff --git a/quarkus/tests/integration/src/test/resources/ShowConfigCommandTest/keycloak-keystore.conf b/quarkus/tests/integration/src/test/resources/ShowConfigCommandTest/keycloak-keystore.conf new file mode 100644 index 00000000000..6a9edddf94b --- /dev/null +++ b/quarkus/tests/integration/src/test/resources/ShowConfigCommandTest/keycloak-keystore.conf @@ -0,0 +1,2 @@ +config-keystore=src/test/resources/keystore +config-keystore-password=secret \ No newline at end of file From f6aaace639a86e7114f8bb534c9ddede6fe84bd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=A1clav=20Muzik=C3=A1=C5=99?= Date: Wed, 12 Jun 2024 10:43:17 +0200 Subject: [PATCH 005/103] Use only plain hostname in Ingress (#30345) (#30362) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #30332 Signed-off-by: Václav Muzikář (cherry picked from commit 08461818097bf7212fca3d5ea7c43b78b33faa77) --- .../KeycloakIngressDependentResource.java | 15 ++++++++- .../testsuite/unit/IngressLogicTest.java | 33 ++++++++++++++++--- 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/operator/src/main/java/org/keycloak/operator/controllers/KeycloakIngressDependentResource.java b/operator/src/main/java/org/keycloak/operator/controllers/KeycloakIngressDependentResource.java index 4dd52f68dd4..5d97c2c8c0e 100644 --- a/operator/src/main/java/org/keycloak/operator/controllers/KeycloakIngressDependentResource.java +++ b/operator/src/main/java/org/keycloak/operator/controllers/KeycloakIngressDependentResource.java @@ -24,11 +24,14 @@ import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition; +import io.quarkus.logging.Log; import org.keycloak.operator.Constants; import org.keycloak.operator.Utils; import org.keycloak.operator.crds.v2alpha1.deployment.Keycloak; import org.keycloak.operator.crds.v2alpha1.deployment.spec.IngressSpec; +import java.net.MalformedURLException; +import java.net.URL; import java.util.HashMap; import java.util.Optional; @@ -107,7 +110,17 @@ public Ingress desired(Keycloak keycloak, Context context) { final var hostnameSpec = keycloak.getSpec().getHostnameSpec(); if (hostnameSpec != null && hostnameSpec.getHostname() != null) { - ingress.getSpec().getRules().get(0).setHost(hostnameSpec.getHostname()); + String hostname = hostnameSpec.getHostname(); + + try { + hostname = new URL(hostname).getHost(); + Log.debug("Hostname is a URL, extracting host: " + hostname); + } + catch (MalformedURLException e) { + Log.debug("Hostname is not a URL, using as is: " + hostname); + } + + ingress.getSpec().getRules().get(0).setHost(hostname); } return ingress; diff --git a/operator/src/test/java/org/keycloak/operator/testsuite/unit/IngressLogicTest.java b/operator/src/test/java/org/keycloak/operator/testsuite/unit/IngressLogicTest.java index 87798bddf03..ce3176c2ac1 100644 --- a/operator/src/test/java/org/keycloak/operator/testsuite/unit/IngressLogicTest.java +++ b/operator/src/test/java/org/keycloak/operator/testsuite/unit/IngressLogicTest.java @@ -41,7 +41,7 @@ public class IngressLogicTest { static class MockKeycloakIngress { - private static Keycloak getKeycloak(boolean tlsConfigured, IngressSpec ingressSpec) { + private static Keycloak getKeycloak(boolean tlsConfigured, IngressSpec ingressSpec, String hostname) { var kc = K8sUtils.getDefaultKeycloakDeployment(); kc.getMetadata().setUid("this-is-a-fake-uid"); if (ingressSpec != null) { @@ -50,6 +50,9 @@ private static Keycloak getKeycloak(boolean tlsConfigured, IngressSpec ingressSp if (!tlsConfigured) { kc.getSpec().getHttpSpec().setTlsSecret(null); } + if (hostname != null) { + kc.getSpec().getHostnameSpec().setHostname(hostname); + } return kc; } @@ -58,10 +61,18 @@ public static MockKeycloakIngress build(Boolean defaultIngressEnabled, boolean i } public static MockKeycloakIngress build(Boolean defaultIngressEnabled, boolean ingressExists, boolean ingressSpecDefined, boolean tlsConfigured) { - return build(defaultIngressEnabled, ingressExists, ingressSpecDefined, tlsConfigured, null); + return build(defaultIngressEnabled, ingressExists, ingressSpecDefined, tlsConfigured, null, null); + } + + public static MockKeycloakIngress build(String hostname) { + return build(true, false, true, true, null, hostname); } public static MockKeycloakIngress build(Boolean defaultIngressEnabled, boolean ingressExists, boolean ingressSpecDefined, boolean tlsConfigured, Map annotations) { + return build(defaultIngressEnabled, ingressExists, ingressSpecDefined, tlsConfigured, annotations, null); + } + + public static MockKeycloakIngress build(Boolean defaultIngressEnabled, boolean ingressExists, boolean ingressSpecDefined, boolean tlsConfigured, Map annotations, String hostname) { IngressSpec ingressSpec = null; if (ingressSpecDefined) { ingressSpec = new IngressSpec(); @@ -72,7 +83,7 @@ public static MockKeycloakIngress build(Boolean defaultIngressEnabled, boolean i ingressSpec.setAnnotations(annotations); } } - MockKeycloakIngress mock = new MockKeycloakIngress(tlsConfigured, ingressSpec); + MockKeycloakIngress mock = new MockKeycloakIngress(tlsConfigured, ingressSpec, hostname); mock.ingressExists = ingressExists; return mock; } @@ -82,8 +93,12 @@ public static MockKeycloakIngress build(Boolean defaultIngressEnabled, boolean i private boolean deleted = false; private Keycloak keycloak; + public MockKeycloakIngress(boolean tlsConfigured, IngressSpec ingressSpec, String hostname) { + this.keycloak = getKeycloak(tlsConfigured, ingressSpec, hostname); + } + public MockKeycloakIngress(boolean tlsConfigured, IngressSpec ingressSpec) { - this.keycloak = getKeycloak(tlsConfigured, ingressSpec); + this(tlsConfigured, ingressSpec, null); } public boolean reconciled() { @@ -101,7 +116,7 @@ public Optional getReconciledResource() { } return Optional.empty(); } - + return Optional.of(keycloakIngressDependentResource.desired(keycloak, null)); } } @@ -217,4 +232,12 @@ public void testIngressSpecDefinedWithClassName() { Ingress ingress = reconciled.map(Ingress.class::cast).orElseThrow(); assertEquals("my-class", ingress.getSpec().getIngressClassName()); } + + @Test + public void testHostnameSanitizing() { + var kc = MockKeycloakIngress.build("https://my-other.example.com:443/my-path"); + Optional reconciled = kc.getReconciledResource(); + Ingress ingress = reconciled.map(Ingress.class::cast).orElseThrow(); + assertEquals("my-other.example.com", ingress.getSpec().getRules().get(0).getHost()); + } } From 97ba5dbe6c7cca8d3bddea0fb331e45b6a9d7a7d Mon Sep 17 00:00:00 2001 From: daviddelannoy <16318239+daviddelannoy@users.noreply.github.com> Date: Wed, 12 Jun 2024 11:11:00 +0200 Subject: [PATCH 006/103] fix label error for persistent-user-sessions feature flag in documentation Signed-off-by: daviddelannoy <16318239+daviddelannoy@users.noreply.github.com> --- docs/documentation/release_notes/topics/25_0_0.adoc | 4 ++-- docs/documentation/server_admin/topics/sessions.adoc | 2 +- .../server_admin/topics/sessions/offline.adoc | 8 ++++---- .../upgrading/topics/changes/changes-25_0_0.adoc | 6 +++--- docs/documentation/upgrading/topics/prep_migration.adoc | 2 +- docs/guides/server/caching.adoc | 6 +++--- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/documentation/release_notes/topics/25_0_0.adoc b/docs/documentation/release_notes/topics/25_0_0.adoc index ad4465fa4b0..0a38eae14e5 100644 --- a/docs/documentation/release_notes/topics/25_0_0.adoc +++ b/docs/documentation/release_notes/topics/25_0_0.adoc @@ -59,13 +59,13 @@ For information on how to migrate, see the link:{upgradingguide_link}[{upgrading = Persistent user sessions Previous versions of {project_name} stored only offline user and offline client sessions in the databases. -The new feature `persistent-user-session` stores online user sessions and online client sessions not only in memory, but also in the database. +The new feature `persistent-user-sessions` stores online user sessions and online client sessions not only in memory, but also in the database. This will allow a user to stay logged in even if all instances of {project_name} are restarted or upgraded. The feature is a preview feature and disabled by default. To use it, add the following to your build command: ---- -bin/kc.sh build --features=persistent-user-session ... +bin/kc.sh build --features=persistent-user-sessions ... ---- For more details see the https://www.keycloak.org/server/features[Enabling and disabling features] {section}. diff --git a/docs/documentation/server_admin/topics/sessions.adoc b/docs/documentation/server_admin/topics/sessions.adoc index ab5e509d190..768a4016ac7 100644 --- a/docs/documentation/server_admin/topics/sessions.adoc +++ b/docs/documentation/server_admin/topics/sessions.adoc @@ -13,7 +13,7 @@ When users log into realms, {project_name} maintains a user session for each use ifeval::[{project_community}==true] By default, online user and online client sessions are only kept in memory, and will be lost if all {project_name} nodes are shut down for maintenance or during upgrades. -If the feature `persistent-user-session` is enabled, {project_name} online user and online client sessions are saved to the database to persist them across restarts and upgrades. +If the feature `persistent-user-sessions` is enabled, {project_name} online user and online client sessions are saved to the database to persist them across restarts and upgrades. See https://www.keycloak.org/server/caching[Configuring distributed caches] on how to configure this. endif::[] diff --git a/docs/documentation/server_admin/topics/sessions/offline.adoc b/docs/documentation/server_admin/topics/sessions/offline.adoc index f7c5b1e9695..74fced31f74 100644 --- a/docs/documentation/server_admin/topics/sessions/offline.adoc +++ b/docs/documentation/server_admin/topics/sessions/offline.adoc @@ -10,7 +10,7 @@ The client application is responsible for persisting the offline token in storag The difference between a refresh token and an offline token is that an offline token never expires and is not subject to the `SSO Session Idle` timeout and `SSO Session Max` lifespan. The offline token is valid after a user logout or server restart. You must use the offline token for a refresh token action at least once per thirty days or for the value of the <<_offline-session-idle, Offline Session Idle>>. -If you enable <<_offline-session-max-limited, Offline Session Max Limited>>, offline tokens expire after 60 days even if you use the offline token for a refresh token action. You can change this value, <<_offline-session-max, Offline Session Max>>, in the Admin Console. +If you enable <<_offline-session-max-limited, Offline Session Max Limited>>, offline tokens expire after 60 days even if you use the offline token for a refresh token action. You can change this value, <<_offline-session-max, Offline Session Max>>, in the Admin Console. When using offline access, client idle and max timeouts can be overridden at the <<_client_advanced_settings_oidc,client level>>. The options *Client Offline Session Idle* and *Client Offline Session Max*, in the client *Advanced Settings* tab, allow you to have a shorter offline timeouts for a specific application. Note that client session values also control the refresh token expiration but they never affect the global offline user SSO session. The option *Client Offline Session Max* is only evaluated in the client if <<_offline-session-max-limited, Offline Session Max Limited>> is *Enabled* at the realm level. @@ -26,7 +26,7 @@ Offline sessions are besides the Infinispan caches stored also in the database. To reduce memory requirements, we introduced a configuration option to shorten lifespan for imported offline sessions. Such sessions will be evicted from the Infinispan caches after the specified lifespan, but still available in the database. This will lower memory consumption, especially for deployments with a large number of offline sessions. Currently, the offline session lifespan override is disabled by default. ifeval::[{project_community}==true] -This override is only available if the feature `persistent-user-session` is disabled. +This override is only available if the feature `persistent-user-sessions` is disabled. endif::[] To specify the lifespan override for offline user sessions, start {project_name} server with the following parameter: @@ -34,7 +34,7 @@ To specify the lifespan override for offline user sessions, start {project_name} [source,bash] ---- --spi-user-sessions-infinispan-offline-session-cache-entry-lifespan-override= ----- +---- Similarly for offline client sessions: @@ -44,7 +44,7 @@ Similarly for offline client sessions: ---- ifeval::[{project_community}==true] -If the feature `persistent-user-session` is enabled, {project_name} will limit its internal cache for offline user and offline client sessions to 10000 entries by default, which will reduce the overall memory usage for offline sessions. +If the feature `persistent-user-sessions` is enabled, {project_name} will limit its internal cache for offline user and offline client sessions to 10000 entries by default, which will reduce the overall memory usage for offline sessions. Items which are evicted from memory will be loaded on-demand from the database when needed. To set different sizes for the caches, edit {project_name}'s cache config file to set a `++` for those caches. endif::[] diff --git a/docs/documentation/upgrading/topics/changes/changes-25_0_0.adoc b/docs/documentation/upgrading/topics/changes/changes-25_0_0.adoc index b6858689460..0dfa4ed8388 100644 --- a/docs/documentation/upgrading/topics/changes/changes-25_0_0.adoc +++ b/docs/documentation/upgrading/topics/changes/changes-25_0_0.adoc @@ -83,7 +83,7 @@ For more details and more comprehensive scenarios, see https://www.keycloak.org/ = Persistent user sessions Previous versions of {project_name} stored only offline user and offline client sessions in the databases. -The new feature `persistent-user-session` stores online user sessions and online client sessions not only in memory, but also in the database. +The new feature `persistent-user-sessions` stores online user sessions and online client sessions not only in memory, but also in the database. This will allow a user to stay logged in even if all instances of {project_name} are restarted or upgraded. == Enabling persistent user sessions @@ -91,7 +91,7 @@ This will allow a user to stay logged in even if all instances of {project_name} The feature is a preview feature and disabled by default. To use it, add the following to your build command: ---- -bin/kc.sh build --features=persistent-user-session ... +bin/kc.sh build --features=persistent-user-sessions ... ---- For more details see the https://www.keycloak.org/server/features[Enabling and disabling features] {section}. @@ -162,7 +162,7 @@ TIP: If the remote {jdgserver_name} is used in a multi-site setup, you can reduc == Signing out existing users In previous versions and when the feature is disabled, a restart of all {project_name} nodes logged out all users. -To sign out all online users sessions of a realm with the `persistent-user-session` feature enabled, use the following steps as before: +To sign out all online users sessions of a realm with the `persistent-user-sessions` feature enabled, use the following steps as before: . Log in to the Admin Console. . Select the menu entry *Sessions*. diff --git a/docs/documentation/upgrading/topics/prep_migration.adoc b/docs/documentation/upgrading/topics/prep_migration.adoc index aec905dd661..c64efd5c924 100644 --- a/docs/documentation/upgrading/topics/prep_migration.adoc +++ b/docs/documentation/upgrading/topics/prep_migration.adoc @@ -20,7 +20,7 @@ After the upgrade of {project_name}, except for offline user sessions, user sess endif::[] ifeval::[{project_community}==true] -After the upgrade of {project_name}, only if the feature `persistent-user-session` is enabled, users will still be logged in with their online sessions. +After the upgrade of {project_name}, only if the feature `persistent-user-sessions` is enabled, users will still be logged in with their online sessions. If it is not enabled, users will have to log in again, except where offline user sessions are used. endif::[] diff --git a/docs/guides/server/caching.adoc b/docs/guides/server/caching.adoc index 439eab3939f..442f6f1235e 100644 --- a/docs/guides/server/caching.adoc +++ b/docs/guides/server/caching.adoc @@ -109,13 +109,13 @@ CPU, memory, and network utilization. ifeval::[{project_community}==true] .Persistent user sessions -The feature `persistent-user-session` stores online user and client sessions also in the database. +The feature `persistent-user-sessions` stores online user and client sessions also in the database. This will allow a user to stay logged in even if all instances of {project_name} are restarted or upgraded. The feature is disabled by default. To use it, enable the feature: ---- -bin/kc.sh start --features=persistent-user-session ... +bin/kc.sh start --features=persistent-user-sessions ... ---- With this feature enabled, the in-memory caches for online user sessions and online client sessions are limited to, by default, 10000 entries per node which will reduce the overall memory usage of {project_name} for larger installations. @@ -146,7 +146,7 @@ Upon a cluster restart, offline sessions are lazily loaded from the database and ifeval::[{project_community}==true] -With feature `persistent-user-session` enabled, the in-memory caches for offline user sessions and offline client sessions are limited to 10000 entries which will reduce the overall memory usage of Keycloak for larger installations. +With feature `persistent-user-sessions` enabled, the in-memory caches for offline user sessions and offline client sessions are limited to 10000 entries which will reduce the overall memory usage of Keycloak for larger installations. Items which are evicted from memory will be loaded on-demand from the database when needed. To set different sizes for the caches, edit {project_name}'s cache config file to set a `++` for those caches. From 0958928d980d5afb8f912a71239b657d7e9feafb Mon Sep 17 00:00:00 2001 From: Jon Koops Date: Wed, 12 Jun 2024 17:27:59 +0200 Subject: [PATCH 007/103] Run the Vite dev server through the Keycloak server (#27311) (#30373) Closes #19750 Closes #28643 Closes #30115 Signed-off-by: Jon Koops (cherry picked from commit c7361ccf6e3079dffd72e191e839822b3309c446) --- .github/workflows/js-ci.yml | 3 - .../org/keycloak/common/util/Environment.java | 17 + core/pom.xml | 4 + .../org/keycloak/util/JsonSerialization.java | 2 + js/apps/account-ui/index.html | 63 -- .../theme/keycloak.v3/account/index.ftl | 139 ++++ js/apps/account-ui/playwright.config.ts | 5 +- js/apps/account-ui/pom.xml | 104 --- js/apps/account-ui/src/utils/getRootPath.ts | 5 - .../account-security/linked-accounts.spec.ts | 15 +- js/apps/account-ui/test/admin-client.ts | 5 +- js/apps/account-ui/test/applications.spec.ts | 24 +- js/apps/account-ui/{src => test}/constants.ts | 3 +- js/apps/account-ui/test/login.ts | 9 +- js/apps/account-ui/test/referrer.spec.ts | 6 +- js/apps/account-ui/test/utils.ts | 18 +- js/apps/account-ui/vite.config.ts | 8 +- .../e2e/identity_providers_oidc_test.spec.ts | 18 +- .../e2e/identity_providers_saml_test.spec.ts | 14 +- .../realm_settings_general_tab_test.spec.ts | 15 +- js/apps/admin-ui/cypress/support/constants.ts | 1 + js/apps/admin-ui/cypress/support/e2e.ts | 5 - .../cypress/support/util/AdminClient.ts | 3 +- js/apps/admin-ui/index.html | 63 -- .../theme/keycloak.v2/admin/index.ftl | 126 ++++ js/apps/admin-ui/pom.xml | 86 --- .../__tests__/FlowDiagram.test.tsx | 637 ------------------ js/apps/admin-ui/vite.config.ts | 5 +- js/apps/keycloak-server/README.md | 27 +- js/apps/keycloak-server/package.json | 11 +- .../scripts/security-admin-console-v2.json | 49 -- .../keycloak-server/scripts/start-server.js | 97 +-- js/libs/ui-shared/src/context/environment.ts | 22 +- pnpm-lock.yaml | 3 - .../quarkus/deployment/KeycloakProcessor.java | 4 +- .../keycloak/quarkus/runtime/Environment.java | 31 +- .../keycloak/quarkus/runtime/Messages.java | 4 +- .../keycloak/quarkus/runtime/cli/Picocli.java | 4 +- .../quarkus/runtime/cli/command/Start.java | 2 +- .../runtime/configuration/Configuration.java | 4 +- .../KeycloakConfigSourceProvider.java | 2 +- .../mappers/PropertyMappers.java | 2 +- .../configuration/test/ConfigurationTest.java | 6 +- .../resources/account/AccountConsole.java | 51 +- .../resources/admin/AdminConsole.java | 38 +- .../org/keycloak/services/util/Chunk.java | 36 + .../keycloak/services/util/ViteManifest.java | 42 ++ 47 files changed, 577 insertions(+), 1261 deletions(-) delete mode 100644 js/apps/account-ui/index.html create mode 100644 js/apps/account-ui/maven-resources/theme/keycloak.v3/account/index.ftl delete mode 100644 js/apps/account-ui/src/utils/getRootPath.ts rename js/apps/account-ui/{src => test}/constants.ts (76%) create mode 100644 js/apps/admin-ui/cypress/support/constants.ts delete mode 100644 js/apps/admin-ui/index.html create mode 100644 js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/index.ftl delete mode 100644 js/apps/admin-ui/src/authentication/__tests__/FlowDiagram.test.tsx delete mode 100644 js/apps/keycloak-server/scripts/security-admin-console-v2.json create mode 100644 services/src/main/java/org/keycloak/services/util/Chunk.java create mode 100644 services/src/main/java/org/keycloak/services/util/ViteManifest.java diff --git a/.github/workflows/js-ci.yml b/.github/workflows/js-ci.yml index 48c9f0b56fc..629a601f8e2 100644 --- a/.github/workflows/js-ci.yml +++ b/.github/workflows/js-ci.yml @@ -182,8 +182,6 @@ jobs: - name: Run Playwright tests run: pnpm --fail-if-no-match --filter ${{ env.WORKSPACE }} test - env: - KEYCLOAK_SERVER: http://localhost:8080 - name: Upload Playwright report uses: actions/upload-artifact@v4 @@ -285,7 +283,6 @@ jobs: working-directory: js/apps/admin-ui env: CYPRESS_BASE_URL: http://localhost:8080/admin/ - CYPRESS_KEYCLOAK_SERVER: http://localhost:8080 SPLIT: ${{ strategy.job-total }} SPLIT_INDEX: ${{ strategy.job-index }} SPLIT_RANDOM_SEED: ${{ needs.generate-test-seed.outputs.seed }} diff --git a/common/src/main/java/org/keycloak/common/util/Environment.java b/common/src/main/java/org/keycloak/common/util/Environment.java index 02aa6da79d0..f491eed5d30 100644 --- a/common/src/main/java/org/keycloak/common/util/Environment.java +++ b/common/src/main/java/org/keycloak/common/util/Environment.java @@ -29,6 +29,10 @@ public class Environment { public static final int DEFAULT_JBOSS_AS_STARTUP_TIMEOUT = 300; + public static final String PROFILE = "kc.profile"; + public static final String ENV_PROFILE = "KC_PROFILE"; + public static final String DEV_PROFILE_VALUE = "dev"; + public static int getServerStartupTimeout() { String timeout = System.getProperty("jboss.as.management.blocking.timeout"); if (timeout != null) { @@ -57,4 +61,17 @@ public static boolean isJavaInFipsMode() { return false; } + public static boolean isDevMode() { + return DEV_PROFILE_VALUE.equalsIgnoreCase(getProfile()); + } + + public static String getProfile() { + String profile = System.getProperty(PROFILE); + + if (profile != null) { + return profile; + } + + return System.getenv(ENV_PROFILE); + } } diff --git a/core/pom.xml b/core/pom.xml index c057066ccc4..5d1f8600b63 100755 --- a/core/pom.xml +++ b/core/pom.xml @@ -54,6 +54,10 @@ com.fasterxml.jackson.core jackson-databind + + com.fasterxml.jackson.datatype + jackson-datatype-jdk8 + org.jboss.logging jboss-logging diff --git a/core/src/main/java/org/keycloak/util/JsonSerialization.java b/core/src/main/java/org/keycloak/util/JsonSerialization.java index e321d11151f..e082ac54ba2 100755 --- a/core/src/main/java/org/keycloak/util/JsonSerialization.java +++ b/core/src/main/java/org/keycloak/util/JsonSerialization.java @@ -24,6 +24,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import java.io.IOException; import java.io.InputStream; @@ -41,6 +42,7 @@ public class JsonSerialization { public static final ObjectMapper sysPropertiesAwareMapper = new ObjectMapper(new SystemPropertiesJsonParserFactory()); static { + mapper.registerModule(new Jdk8Module()); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); prettyMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); diff --git a/js/apps/account-ui/index.html b/js/apps/account-ui/index.html deleted file mode 100644 index f284617802d..00000000000 --- a/js/apps/account-ui/index.html +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - Account Management - - - -
-
-
- - - - - -
-

Loading the account console

-
-
-
-
- - - - - diff --git a/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/index.ftl b/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/index.ftl new file mode 100644 index 00000000000..1cc5a4d4e9c --- /dev/null +++ b/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/index.ftl @@ -0,0 +1,139 @@ + + + + + + + + + ${properties.title!'Account Management'} + + + <#if devServerUrl?has_content> + + + + + + <#if entryStyles?has_content> + <#list entryStyles as style> + + + + <#if properties.styles?has_content> + <#list properties.styles?split(' ') as style> + + + + <#if entryScript?has_content> + + + <#if properties.scripts?has_content> + <#list properties.scripts?split(' ') as script> + + + + <#if entryImports?has_content> + <#list entryImports as import> + + + + + +
+
+
+ + + + + +
+

Loading the Account Console

+
+
+
+
+ + + + diff --git a/js/apps/account-ui/playwright.config.ts b/js/apps/account-ui/playwright.config.ts index 706eeb49dd2..8580ab472ad 100644 --- a/js/apps/account-ui/playwright.config.ts +++ b/js/apps/account-ui/playwright.config.ts @@ -1,5 +1,6 @@ import { defineConfig, devices } from "@playwright/test"; -import { getRootPath } from "./src/utils/getRootPath"; + +import { getAccountUrl } from "./test/utils"; /** * See https://playwright.dev/docs/test-configuration. @@ -16,7 +17,7 @@ export default defineConfig({ }, use: { - baseURL: `http://localhost:8080${getRootPath()}`, + baseURL: getAccountUrl(), trace: "on-first-retry", }, diff --git a/js/apps/account-ui/pom.xml b/js/apps/account-ui/pom.xml index 9378e6035a6..203fad0206f 100644 --- a/js/apps/account-ui/pom.xml +++ b/js/apps/account-ui/pom.xml @@ -94,110 +94,6 @@ - - com.google.code.maven-replacer-plugin - maven-replacer-plugin - - - process-resources - - replace - - - - - dist/index.html - target/classes/theme/keycloak.v3/account/index.ftl - false - - - src="./ - src="${resourceUrl}/ - - - href="./ - href="${resourceUrl}/ - - - ]]> - ]]> - - - ]]> - ]]> - - - Account Management]]> - -${properties.title!"Account Management"} - -]]> - - - ]]> - - - { - "authUrl": "${authUrl}", - "authServerUrl": "${authServerUrl}", - "realm": "${realm.name}", - "clientId": "${clientId}", - "resourceUrl": "${resourceUrl}", - "logo": "${properties.logo!""}", - "logoUrl": "${properties.logoUrl!""}", - "baseUrl": "${baseUrl}", - "locale": "${locale}", - "referrerName": "${referrerName!""}", - "referrerUrl": "${referrer_uri!""}", - "features": { - "isRegistrationEmailAsUsername": ${realm.registrationEmailAsUsername?c}, - "isEditUserNameAllowed": ${realm.editUsernameAllowed?c}, - "isInternationalizationEnabled": ${realm.isInternationalizationEnabled()?c}, - "isLinkedAccountsEnabled": ${realm.identityFederationEnabled?c}, - "isMyResourcesEnabled": ${(realm.userManagedAccessAllowed && isAuthorizationEnabled)?c}, - "deleteAccountAllowed": ${deleteAccountAllowed?c}, - "updateEmailFeatureEnabled": ${updateEmailFeatureEnabled?c}, - "updateEmailActionEnabled": ${updateEmailActionEnabled?c}, - "isViewGroupsEnabled": ${isViewGroupsEnabled?c}, - "isOid4VciEnabled": ${isOid4VciEnabled?c} - } - } - - -]]> - - - - ]]> - - - <#list properties.scripts?split(' ') as script> - - - - <#if properties.styles?has_content> - <#list properties.styles?split(' ') as style> - - - - -]]> - - - - - \ No newline at end of file diff --git a/js/apps/account-ui/src/utils/getRootPath.ts b/js/apps/account-ui/src/utils/getRootPath.ts deleted file mode 100644 index 819df7055d8..00000000000 --- a/js/apps/account-ui/src/utils/getRootPath.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { generatePath } from "react-router-dom"; -import { DEFAULT_REALM, ROOT_PATH } from "../constants"; - -export const getRootPath = (realm = DEFAULT_REALM) => - generatePath(ROOT_PATH, { realm }); diff --git a/js/apps/account-ui/test/account-security/linked-accounts.spec.ts b/js/apps/account-ui/test/account-security/linked-accounts.spec.ts index 5d8eca7bafa..a6fdfe3dade 100644 --- a/js/apps/account-ui/test/account-security/linked-accounts.spec.ts +++ b/js/apps/account-ui/test/account-security/linked-accounts.spec.ts @@ -13,8 +13,8 @@ import { findClientByClientId, inRealm, } from "../admin-client"; +import { SERVER_URL } from "../constants"; import groupsIdPClient from "../realms/groups-idp.json" assert { type: "json" }; -import { getKeycloakServerUrl } from "../utils"; const realm = "groups"; @@ -32,7 +32,6 @@ test.describe("Account linking", () => { groupIdPClientId = await createClient( groupsIdPClient as ClientRepresentation, ); - const baseUrl = getKeycloakServerUrl(); const idp: IdentityProviderRepresentation = { alias: "master-idp", providerId: "oidc", @@ -41,12 +40,12 @@ test.describe("Account linking", () => { clientId: "groups-idp", clientSecret: "H0JaTc7VBu3HJR26vrzMxgidfJmgI5Dw", validateSignature: "false", - tokenUrl: `${baseUrl}/realms/master/protocol/openid-connect/token`, - jwksUrl: `${baseUrl}/realms/master/protocol/openid-connect/certs`, - issuer: `${baseUrl}/realms/master`, - authorizationUrl: `${baseUrl}/realms/master/protocol/openid-connect/auth`, - logoutUrl: `${baseUrl}/realms/master/protocol/openid-connect/logout`, - userInfoUrl: `${baseUrl}/realms/master/protocol/openid-connect/userinfo`, + tokenUrl: `${SERVER_URL}/realms/master/protocol/openid-connect/token`, + jwksUrl: `${SERVER_URL}/realms/master/protocol/openid-connect/certs`, + issuer: `${SERVER_URL}/realms/master`, + authorizationUrl: `${SERVER_URL}/realms/master/protocol/openid-connect/auth`, + logoutUrl: `${SERVER_URL}/realms/master/protocol/openid-connect/logout`, + userInfoUrl: `${SERVER_URL}/realms/master/protocol/openid-connect/userinfo`, }, }; diff --git a/js/apps/account-ui/test/admin-client.ts b/js/apps/account-ui/test/admin-client.ts index 7824a0532e5..30a1f2628be 100644 --- a/js/apps/account-ui/test/admin-client.ts +++ b/js/apps/account-ui/test/admin-client.ts @@ -5,11 +5,10 @@ import RealmRepresentation from "@keycloak/keycloak-admin-client/lib/defs/realmR import type { UserProfileConfig } from "@keycloak/keycloak-admin-client/lib/defs/userProfileMetadata"; import UserRepresentation from "@keycloak/keycloak-admin-client/lib/defs/userRepresentation"; -import { DEFAULT_REALM } from "../src/constants"; -import { getKeycloakServerUrl } from "./utils"; +import { DEFAULT_REALM, SERVER_URL } from "./constants"; const adminClient = new KeycloakAdminClient({ - baseUrl: getKeycloakServerUrl(), + baseUrl: SERVER_URL, realmName: DEFAULT_REALM, }); diff --git a/js/apps/account-ui/test/applications.spec.ts b/js/apps/account-ui/test/applications.spec.ts index dee8bb9bfda..d509e6de142 100644 --- a/js/apps/account-ui/test/applications.spec.ts +++ b/js/apps/account-ui/test/applications.spec.ts @@ -1,12 +1,11 @@ import { expect, test } from "@playwright/test"; -import { getRootPath } from "../src/utils/getRootPath"; import { login } from "./login"; -import { getAccountUrl, getAdminUrl } from "./utils"; +import { getAccountUrl, getAdminUrl, getRootPath } from "./utils"; test.describe("Applications test", () => { test.beforeEach(async ({ page }) => { // Sign out all devices before each test - await login(page, "admin", "admin"); + await login(page); await page.getByTestId("accountSecurity").click(); await page.getByTestId("account-security/device-activity").click(); @@ -21,13 +20,13 @@ test.describe("Applications test", () => { }); test("Single application", async ({ page }) => { - await login(page, "admin", "admin"); + await login(page); await page.getByTestId("applications").click(); await expect(page.getByTestId("applications-list-item")).toHaveCount(1); await expect(page.getByTestId("applications-list-item")).toContainText( - process.env.CI ? "Account Console" : "security-admin-console-v2", + "Account Console", ); }); @@ -41,17 +40,15 @@ test.describe("Applications test", () => { const page1 = await context1.newPage(); const page2 = await context2.newPage(); - await login(page1, "admin", "admin"); - await login(page2, "admin", "admin"); + await login(page1); + await login(page2); await page1.getByTestId("applications").click(); await expect(page1.getByTestId("applications-list-item")).toHaveCount(1); await expect( page1.getByTestId("applications-list-item").nth(0), - ).toContainText( - process.env.CI ? "Account Console" : "security-admin-console-v2", - ); + ).toContainText("Account Console"); } finally { await context1.close(); await context2.close(); @@ -59,12 +56,7 @@ test.describe("Applications test", () => { }); test("Two applications", async ({ page }) => { - test.skip( - !process.env.CI, - "Skip this test if not running with regular Keycloak", - ); - - await login(page, "admin", "admin"); + await login(page); // go to admin console await page.goto("/"); diff --git a/js/apps/account-ui/src/constants.ts b/js/apps/account-ui/test/constants.ts similarity index 76% rename from js/apps/account-ui/src/constants.ts rename to js/apps/account-ui/test/constants.ts index fbbb6766940..9f9d3a85da7 100644 --- a/js/apps/account-ui/src/constants.ts +++ b/js/apps/account-ui/test/constants.ts @@ -1,4 +1,5 @@ -export const DEFAULT_REALM = "master"; +export const SERVER_URL = "http://localhost:8080"; export const ROOT_PATH = "/realms/:realm/account"; +export const DEFAULT_REALM = "master"; export const ADMIN_USER = "admin"; export const ADMIN_PASSWORD = "admin"; diff --git a/js/apps/account-ui/test/login.ts b/js/apps/account-ui/test/login.ts index 43ec188ee69..893c7cc9673 100644 --- a/js/apps/account-ui/test/login.ts +++ b/js/apps/account-ui/test/login.ts @@ -1,11 +1,12 @@ import { Page } from "@playwright/test"; -import { DEFAULT_REALM } from "../src/constants"; -import { getRootPath } from "../src/utils/getRootPath"; + +import { ADMIN_PASSWORD, ADMIN_USER, DEFAULT_REALM } from "./constants"; +import { getRootPath } from "./utils"; export const login = async ( page: Page, - username: string, - password: string, + username = ADMIN_USER, + password = ADMIN_PASSWORD, realm = DEFAULT_REALM, queryParams?: Record, ) => { diff --git a/js/apps/account-ui/test/referrer.spec.ts b/js/apps/account-ui/test/referrer.spec.ts index d99560497ac..74db8b0ef33 100644 --- a/js/apps/account-ui/test/referrer.spec.ts +++ b/js/apps/account-ui/test/referrer.spec.ts @@ -1,10 +1,8 @@ import { expect, test } from "@playwright/test"; + +import { ADMIN_PASSWORD, ADMIN_USER, DEFAULT_REALM } from "./constants"; import { login } from "./login"; import { getAdminUrl } from "./utils"; -import { ADMIN_PASSWORD, ADMIN_USER, DEFAULT_REALM } from "../src/constants"; - -// NOTE: This test suite will only pass when running a production build, as the referrer is extracted on the server side. -// This will change once https://github.com/keycloak/keycloak/pull/27311 has been merged. test.describe("Signing in with referrer link", () => { test("shows a referrer link when a matching client exists", async ({ diff --git a/js/apps/account-ui/test/utils.ts b/js/apps/account-ui/test/utils.ts index f7aebfbba2c..efdb06e47fe 100644 --- a/js/apps/account-ui/test/utils.ts +++ b/js/apps/account-ui/test/utils.ts @@ -1,18 +1,14 @@ -import { getRootPath } from "../src/utils/getRootPath"; +import { generatePath } from "react-router-dom"; -function getTestServerUrl(): string { - return process.env.KEYCLOAK_SERVER ?? "http://localhost:8080"; -} - -export function getKeycloakServerUrl(): string { - // In CI, the Keycloak server is running in the same server as tested console, while in dev, it is running on a different port - return process.env.CI ? getTestServerUrl() : "http://localhost:8180"; -} +import { DEFAULT_REALM, ROOT_PATH, SERVER_URL } from "./constants"; export function getAccountUrl() { - return getTestServerUrl() + getRootPath(); + return SERVER_URL + getRootPath(); } export function getAdminUrl() { - return getKeycloakServerUrl() + "/admin/master/console/"; + return SERVER_URL + "/admin/master/console/"; } + +export const getRootPath = (realm = DEFAULT_REALM) => + generatePath(ROOT_PATH, { realm }); diff --git a/js/apps/account-ui/vite.config.ts b/js/apps/account-ui/vite.config.ts index 718b494da68..51ea7015997 100644 --- a/js/apps/account-ui/vite.config.ts +++ b/js/apps/account-ui/vite.config.ts @@ -4,8 +4,6 @@ import { defineConfig, loadEnv } from "vite"; import { checker } from "vite-plugin-checker"; import dts from "vite-plugin-dts"; -import { getRootPath } from "./src/utils/getRootPath"; - // https://vitejs.dev/config/ export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd(), ""); @@ -28,8 +26,8 @@ export default defineConfig(({ mode }) => { return { base: "", server: { - port: 8080, - open: getRootPath(), + origin: "http://localhost:5173", + port: 5173, }, build: { ...lib, @@ -37,7 +35,9 @@ export default defineConfig(({ mode }) => { target: "esnext", modulePreload: false, cssMinify: "lightningcss", + manifest: true, rollupOptions: { + input: "src/main.tsx", external, }, }, diff --git a/js/apps/admin-ui/cypress/e2e/identity_providers_oidc_test.spec.ts b/js/apps/admin-ui/cypress/e2e/identity_providers_oidc_test.spec.ts index 2df1f7a86c3..a593a96a103 100644 --- a/js/apps/admin-ui/cypress/e2e/identity_providers_oidc_test.spec.ts +++ b/js/apps/admin-ui/cypress/e2e/identity_providers_oidc_test.spec.ts @@ -1,17 +1,18 @@ -import Masthead from "../support/pages/admin-ui/Masthead"; -import SidebarPage from "../support/pages/admin-ui/SidebarPage"; +import { SERVER_URL } from "../support/constants"; import LoginPage from "../support/pages/LoginPage"; -import { keycloakBefore } from "../support/util/keycloak_hooks"; import ListingPage from "../support/pages/admin-ui/ListingPage"; -import CreateProviderPage from "../support/pages/admin-ui/manage/identity_providers/CreateProviderPage"; -import ModalUtils from "../support/util/ModalUtils"; +import Masthead from "../support/pages/admin-ui/Masthead"; +import SidebarPage from "../support/pages/admin-ui/SidebarPage"; import AddMapperPage from "../support/pages/admin-ui/manage/identity_providers/AddMapperPage"; -import ProviderBaseGeneralSettingsPage from "../support/pages/admin-ui/manage/identity_providers/ProviderBaseGeneralSettingsPage"; +import CreateProviderPage from "../support/pages/admin-ui/manage/identity_providers/CreateProviderPage"; import ProviderBaseAdvancedSettingsPage, { ClientAssertionSigningAlg, ClientAuthentication, PromptSelect, } from "../support/pages/admin-ui/manage/identity_providers/ProviderBaseAdvancedSettingsPage"; +import ProviderBaseGeneralSettingsPage from "../support/pages/admin-ui/manage/identity_providers/ProviderBaseGeneralSettingsPage"; +import ModalUtils from "../support/util/ModalUtils"; +import { keycloakBefore } from "../support/util/keycloak_hooks"; describe("OIDC identity provider test", () => { const loginPage = new LoginPage(); @@ -27,9 +28,8 @@ describe("OIDC identity provider test", () => { const deletePrompt = "Delete provider?"; const deleteSuccessMsg = "Provider successfully deleted."; - const keycloakServer = Cypress.env("KEYCLOAK_SERVER"); - const discoveryUrl = `${keycloakServer}/realms/master/.well-known/openid-configuration`; - const authorizationUrl = `${keycloakServer}/realms/master/protocol/openid-connect/auth`; + const discoveryUrl = `${SERVER_URL}/realms/master/.well-known/openid-configuration`; + const authorizationUrl = `${SERVER_URL}/realms/master/protocol/openid-connect/auth`; describe("OIDC Identity provider creation", () => { const oidcProviderName = "oidc"; diff --git a/js/apps/admin-ui/cypress/e2e/identity_providers_saml_test.spec.ts b/js/apps/admin-ui/cypress/e2e/identity_providers_saml_test.spec.ts index f8e79d6dd14..32b935f5f49 100644 --- a/js/apps/admin-ui/cypress/e2e/identity_providers_saml_test.spec.ts +++ b/js/apps/admin-ui/cypress/e2e/identity_providers_saml_test.spec.ts @@ -1,12 +1,13 @@ -import Masthead from "../support/pages/admin-ui/Masthead"; -import SidebarPage from "../support/pages/admin-ui/SidebarPage"; +import { SERVER_URL } from "../support/constants"; import LoginPage from "../support/pages/LoginPage"; -import { keycloakBefore } from "../support/util/keycloak_hooks"; import ListingPage from "../support/pages/admin-ui/ListingPage"; -import CreateProviderPage from "../support/pages/admin-ui/manage/identity_providers/CreateProviderPage"; -import ModalUtils from "../support/util/ModalUtils"; +import Masthead from "../support/pages/admin-ui/Masthead"; +import SidebarPage from "../support/pages/admin-ui/SidebarPage"; import AddMapperPage from "../support/pages/admin-ui/manage/identity_providers/AddMapperPage"; +import CreateProviderPage from "../support/pages/admin-ui/manage/identity_providers/CreateProviderPage"; import ProviderSAMLSettings from "../support/pages/admin-ui/manage/identity_providers/social/ProviderSAMLSettings"; +import ModalUtils from "../support/util/ModalUtils"; +import { keycloakBefore } from "../support/util/keycloak_hooks"; describe("SAML identity provider test", () => { const loginPage = new LoginPage(); @@ -28,8 +29,7 @@ describe("SAML identity provider test", () => { const classRefName = "acClassRef-1"; const declRefName = "acDeclRef-1"; - const keycloakServer = Cypress.env("KEYCLOAK_SERVER"); - const samlDiscoveryUrl = `${keycloakServer}/realms/master/protocol/saml/descriptor`; + const samlDiscoveryUrl = `${SERVER_URL}/realms/master/protocol/saml/descriptor`; const samlDisplayName = "saml"; describe("SAML identity provider creation", () => { diff --git a/js/apps/admin-ui/cypress/e2e/realm_settings_general_tab_test.spec.ts b/js/apps/admin-ui/cypress/e2e/realm_settings_general_tab_test.spec.ts index 4eff70a0e24..dd7e2c71f50 100644 --- a/js/apps/admin-ui/cypress/e2e/realm_settings_general_tab_test.spec.ts +++ b/js/apps/admin-ui/cypress/e2e/realm_settings_general_tab_test.spec.ts @@ -1,10 +1,11 @@ import { v4 as uuid } from "uuid"; -import SidebarPage from "../support/pages/admin-ui/SidebarPage"; +import { SERVER_URL } from "../support/constants"; import LoginPage from "../support/pages/LoginPage"; -import RealmSettingsPage from "../support/pages/admin-ui/manage/realm_settings/RealmSettingsPage"; import Masthead from "../support/pages/admin-ui/Masthead"; -import { keycloakBefore } from "../support/util/keycloak_hooks"; +import SidebarPage from "../support/pages/admin-ui/SidebarPage"; +import RealmSettingsPage from "../support/pages/admin-ui/manage/realm_settings/RealmSettingsPage"; import adminClient from "../support/util/AdminClient"; +import { keycloakBefore } from "../support/util/keycloak_hooks"; const loginPage = new LoginPage(); const sidebarPage = new SidebarPage(); @@ -138,9 +139,7 @@ describe("Realm settings general tab tests", () => { .should( "have.attr", "href", - `${Cypress.env( - "KEYCLOAK_SERVER", - )}/realms/${realmName}/.well-known/openid-configuration`, + `${SERVER_URL}/realms/${realmName}/.well-known/openid-configuration`, ) .should("have.attr", "target", "_blank") .should("have.attr", "rel", "noreferrer noopener"); @@ -163,9 +162,7 @@ describe("Realm settings general tab tests", () => { .should( "have.attr", "href", - `${Cypress.env( - "KEYCLOAK_SERVER", - )}/realms/${realmName}/protocol/saml/descriptor`, + `${SERVER_URL}/realms/${realmName}/protocol/saml/descriptor`, ) .should("have.attr", "target", "_blank") .should("have.attr", "rel", "noreferrer noopener"); diff --git a/js/apps/admin-ui/cypress/support/constants.ts b/js/apps/admin-ui/cypress/support/constants.ts new file mode 100644 index 00000000000..74c2fae875a --- /dev/null +++ b/js/apps/admin-ui/cypress/support/constants.ts @@ -0,0 +1 @@ +export const SERVER_URL = "http://localhost:8080"; diff --git a/js/apps/admin-ui/cypress/support/e2e.ts b/js/apps/admin-ui/cypress/support/e2e.ts index 3bfd6d1f363..d076cec9fd3 100644 --- a/js/apps/admin-ui/cypress/support/e2e.ts +++ b/js/apps/admin-ui/cypress/support/e2e.ts @@ -18,8 +18,3 @@ import "./commands"; // Alternatively you can use CommonJS syntax: // require('./commands') - -// Set Keycloak server to development path if not set. -if (!Cypress.env("KEYCLOAK_SERVER")) { - Cypress.env("KEYCLOAK_SERVER", "http://localhost:8180"); -} diff --git a/js/apps/admin-ui/cypress/support/util/AdminClient.ts b/js/apps/admin-ui/cypress/support/util/AdminClient.ts index 01b99561439..5cc9cafc30b 100644 --- a/js/apps/admin-ui/cypress/support/util/AdminClient.ts +++ b/js/apps/admin-ui/cypress/support/util/AdminClient.ts @@ -9,10 +9,11 @@ import type { UserProfileConfig } from "@keycloak/keycloak-admin-client/lib/defs import type UserRepresentation from "@keycloak/keycloak-admin-client/lib/defs/userRepresentation"; import { Credentials } from "@keycloak/keycloak-admin-client/lib/utils/auth"; import { merge } from "lodash-es"; +import { SERVER_URL } from "../constants"; class AdminClient { readonly #client = new KeycloakAdminClient({ - baseUrl: Cypress.env("KEYCLOAK_SERVER"), + baseUrl: SERVER_URL, realmName: "master", }); diff --git a/js/apps/admin-ui/index.html b/js/apps/admin-ui/index.html deleted file mode 100644 index 90461c50256..00000000000 --- a/js/apps/admin-ui/index.html +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - Keycloak Administration UI - - - -
-
-
- - - - - -
-

Loading the Admin UI

-
-
-
-
- - - - - diff --git a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/index.ftl b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/index.ftl new file mode 100644 index 00000000000..a216ae052a9 --- /dev/null +++ b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/index.ftl @@ -0,0 +1,126 @@ + + + + + + + + + ${properties.title!'Keycloak Administration Console'} + + + <#if devServerUrl?has_content> + + + + + + <#if entryStyles?has_content> + <#list entryStyles as style> + + + + <#if properties.styles?has_content> + <#list properties.styles?split(' ') as style> + + + + <#if entryScript?has_content> + + + <#if properties.scripts?has_content> + <#list properties.scripts?split(' ') as script> + + + + <#if entryImports?has_content> + <#list entryImports as import> + + + + + +
+
+
+ + + + + +
+

Loading the Administration Console

+
+
+
+
+ + + + diff --git a/js/apps/admin-ui/pom.xml b/js/apps/admin-ui/pom.xml index adcc43a6580..4e7a668c893 100644 --- a/js/apps/admin-ui/pom.xml +++ b/js/apps/admin-ui/pom.xml @@ -70,92 +70,6 @@ com.github.eirslett frontend-maven-plugin - - com.google.code.maven-replacer-plugin - maven-replacer-plugin - - - process-resources - - replace - - - - - dist/index.html - target/classes/theme/keycloak.v2/admin/index.ftl - false - - - src="./ - src="${resourceUrl}/ - - - href="./ - href="${resourceUrl}/ - - - ]]> - ]]> - - - ]]> - ]]> - - - Keycloak Administration UI]]> - -${properties.title!"Keycloak Administration UI"} - -]]> - - - ]]> - - - { - "authUrl": "${authUrl}", - "authServerUrl": "${authServerUrl}", - "realm": "${loginRealm!"master"}", - "clientId": "${clientId}", - "resourceUrl": "${resourceUrl}", - "logo": "${properties.logo!""}", - "logoUrl": "${properties.logoUrl!""}", - "consoleBaseUrl": "${consoleBaseUrl}", - "masterRealm": "${masterRealm}", - "resourceVersion": "${resourceVersion}" - } - - -]]> - - - - ]]> - - - <#list properties.styles?split(' ') as style> - - - - -]]> - - - - - \ No newline at end of file diff --git a/js/apps/admin-ui/src/authentication/__tests__/FlowDiagram.test.tsx b/js/apps/admin-ui/src/authentication/__tests__/FlowDiagram.test.tsx deleted file mode 100644 index daf6f57c2ee..00000000000 --- a/js/apps/admin-ui/src/authentication/__tests__/FlowDiagram.test.tsx +++ /dev/null @@ -1,637 +0,0 @@ -// eslint-disable-next-line no-restricted-imports, @typescript-eslint/no-unused-vars -import * as React from "react"; -import { render } from "@testing-library/react"; -import { FlowDiagram } from "../components/FlowDiagram"; -import { describe, expect, it, beforeEach } from "vitest"; -import { ExecutionList } from "../execution-model"; - -// mock react-flow -// code from https://reactflow.dev/learn/advanced-use/testing -class ResizeObserver { - callback: globalThis.ResizeObserverCallback; - - constructor(callback: globalThis.ResizeObserverCallback) { - this.callback = callback; - } - - observe(target: Element) { - this.callback([{ target } as globalThis.ResizeObserverEntry], this); - } - - // eslint-disable-next-line @typescript-eslint/no-empty-function - unobserve() {} - // eslint-disable-next-line @typescript-eslint/no-empty-function - disconnect() {} -} - -class DOMMatrixReadOnly { - m22: number; - constructor(transform: string) { - const scale = transform.match(/scale\(([1-9.])\)/)?.[1]; - this.m22 = scale !== undefined ? +scale : 1; - } -} - -// Only run the shim once when requested -let init = false; - -export const mockReactFlow = () => { - if (init) return; - init = true; - - global.ResizeObserver = ResizeObserver; - - // @ts-ignore - global.DOMMatrixReadOnly = DOMMatrixReadOnly; - - Object.defineProperties(global.HTMLElement.prototype, { - offsetHeight: { - get() { - return parseFloat(this.style.height) || 1; - }, - }, - offsetWidth: { - get() { - return parseFloat(this.style.width) || 1; - }, - }, - }); - - (global.SVGElement as any).prototype.getBBox = () => ({ - x: 0, - y: 0, - width: 0, - height: 0, - }); -}; - -describe("", () => { - beforeEach(() => { - mockReactFlow(); - }); - - const reactFlowTester = (container: HTMLElement) => ({ - expectEdgeLabels: (expectedEdges: string[]) => { - const edges = Array.from( - container.getElementsByClassName("react-flow__edge"), - ); - expect( - edges.map((edge) => edge.getAttribute("aria-label")).sort(), - ).toEqual(expectedEdges.sort()); - }, - expectNodeIds: (expectedNodes: string[]) => { - const nodes = Array.from( - container.getElementsByClassName("react-flow__node"), - ); - expect(nodes.map((node) => node.getAttribute("data-id")).sort()).toEqual( - expectedNodes.sort(), - ); - }, - }); - - it("should render a flow with one required step", () => { - const executionList = new ExecutionList([ - { id: "single", displayName: "Single", level: 0 }, - ]); - - const { container } = render(); - - // const nodes = Array.from(container.getElementsByClassName("react-flow__node")); - const testHelper = reactFlowTester(container); - - const expectedEdges = [ - "Edge from start to single", - "Edge from single to end", - ]; - testHelper.expectEdgeLabels(expectedEdges); - - const expectedNodes = new Set(["start", "single", "end"]); - testHelper.expectNodeIds(Array.from(expectedNodes)); - }); - - it("should render a start connected to end with no steps", () => { - const executionList = new ExecutionList([]); - - const { container } = render(); - - const testHelper = reactFlowTester(container); - - const expectedEdges = ["Edge from start to end"]; - testHelper.expectEdgeLabels(expectedEdges); - - const expectedNodes = new Set(["start", "end"]); - testHelper.expectNodeIds(Array.from(expectedNodes)); - }); - - it("should render two branches with two alternative steps", () => { - const executionList = new ExecutionList([ - { - id: "alt1", - displayName: "Alt1", - requirement: "ALTERNATIVE", - }, - { - id: "alt2", - displayName: "Alt2", - requirement: "ALTERNATIVE", - }, - ]); - - const { container } = render(); - - const testHelper = reactFlowTester(container); - - const expectedEdges = [ - "Edge from start to alt1", - "Edge from alt1 to end", - "Edge from alt1 to alt2", - "Edge from alt2 to end", - ]; - testHelper.expectEdgeLabels(expectedEdges); - - const expectedNodes = new Set(["start", "alt1", "alt2", "end"]); - testHelper.expectNodeIds(Array.from(expectedNodes)); - }); - - it("should render a flow with a subflow", () => { - const executionList = new ExecutionList([ - { - id: "requiredElement", - displayName: "Required Element", - requirement: "REQUIRED", - level: 0, - }, - { - id: "subflow", - displayName: "Subflow", - requirement: "REQUIRED", - level: 0, - }, - { - id: "subElement", - displayName: "Sub Element", - requirement: "REQUIRED", - level: 1, - }, - ]); - - const { container } = render(); - - const testHelper = reactFlowTester(container); - const expectedNodes = ["start", "requiredElement", "subElement", "end"]; - testHelper.expectNodeIds(expectedNodes); - - const expectedEdges = [ - "Edge from start to requiredElement", - "Edge from requiredElement to subElement", - "Edge from subElement to end", - ]; - testHelper.expectEdgeLabels(expectedEdges); - }); - - it("should render a flow with a subflow with alternative steps", () => { - const executionList = new ExecutionList([ - { - id: "requiredElement", - displayName: "Required Element", - requirement: "REQUIRED", - level: 0, - }, - { - id: "subflow", - displayName: "Subflow", - requirement: "REQUIRED", - level: 0, - }, - { - id: "subElement1", - displayName: "Sub Element", - requirement: "ALTERNATIVE", - level: 1, - }, - { - id: "subElement2", - displayName: "Sub Element", - requirement: "ALTERNATIVE", - level: 1, - }, - ]); - - const { container } = render(); - - const testHelper = reactFlowTester(container); - const expectedEdges = [ - "Edge from start to requiredElement", - "Edge from requiredElement to subElement1", - "Edge from subElement1 to end", - "Edge from subElement1 to subElement2", - "Edge from subElement2 to end", - ]; - testHelper.expectEdgeLabels(expectedEdges); - - const expectedNodes = [ - "start", - "requiredElement", - "subElement1", - "subElement2", - "end", - ]; - testHelper.expectNodeIds(expectedNodes); - }); - - it("should render a flow with a subflow with alternative steps and combine to a required step", () => { - const executionList = new ExecutionList([ - { - id: "requiredElement", - displayName: "Required Element", - requirement: "REQUIRED", - level: 0, - }, - { - id: "subflow", - displayName: "Subflow", - requirement: "REQUIRED", - level: 0, - }, - { - id: "subElement1", - displayName: "Sub Element", - requirement: "ALTERNATIVE", - level: 1, - }, - { - id: "subElement2", - displayName: "Sub Element", - requirement: "ALTERNATIVE", - level: 1, - }, - { - id: "finalStep", - displayName: "Final Step", - requirement: "REQUIRED", - level: 0, - }, - ]); - - const { container } = render(); - - const testHelper = reactFlowTester(container); - const expectedEdges = [ - "Edge from start to requiredElement", - "Edge from requiredElement to subElement1", - "Edge from subElement1 to finalStep", - "Edge from subElement1 to subElement2", - "Edge from subElement2 to finalStep", - "Edge from finalStep to end", - ]; - testHelper.expectEdgeLabels(expectedEdges); - - const expectedNodes = [ - "start", - "requiredElement", - "subElement1", - "subElement2", - "finalStep", - "end", - ]; - testHelper.expectNodeIds(expectedNodes); - }); - - it("should render a flow with a conditional subflow followed by a required step", () => { - const executionList = new ExecutionList([ - { - id: "chooseUser", - displayName: "Required Element", - requirement: "REQUIRED", - level: 0, - }, - { - id: "sendReset", - displayName: "Send Reset", - requirement: "REQUIRED", - level: 0, - }, - { - id: "conditionalOTP", - displayName: "Conditional OTP", - requirement: "CONDITIONAL", - level: 0, - }, - { - id: "conditionOtpConfigured", - displayName: "Condition - User Configured", - requirement: "REQUIRED", - level: 1, - }, - { - id: "otpForm", - displayName: "OTP Form", - requirement: "REQUIRED", - level: 1, - }, - { - id: "resetPassword", - displayName: "Reset Password", - requirement: "REQUIRED", - level: 0, - }, - ]); - - const { container } = render(); - - const testHelper = reactFlowTester(container); - const expectedNodes = [ - "start", - "chooseUser", - "sendReset", - "conditionOtpConfigured", - "otpForm", - "resetPassword", - "end", - ]; - testHelper.expectNodeIds(expectedNodes); - - const expectedEdges = [ - "Edge from start to chooseUser", - "Edge from chooseUser to sendReset", - "Edge from sendReset to conditionOtpConfigured", - "Edge from conditionOtpConfigured to otpForm", - "Edge from conditionOtpConfigured to resetPassword", - "Edge from otpForm to resetPassword", - "Edge from resetPassword to end", - ]; - testHelper.expectEdgeLabels(expectedEdges); - }); - - it("should render a complex flow with serial conditionals", () => { - // flow inspired by ![conditional flow PR](https://github.com/keycloak/keycloak/pull/28481) - const executionList = new ExecutionList([ - { - id: "exampleForms", - displayName: "Example Forms", - requirement: "ALTERNATIVE", - level: 0, - }, - { - id: "usernamePasswordForm", - displayName: "Username Password Form", - requirement: "REQUIRED", - level: 1, - }, - { - id: "conditionalOTP", - displayName: "Conditional OTP", - requirement: "CONDITIONAL", - level: 1, - }, - { - id: "conditionUserConfigured", - displayName: "Condition - User Configured", - requirement: "REQUIRED", - level: 2, - }, - { - id: "conditionUserAttribute", - displayName: "Condition - User Attribute", - requirement: "REQUIRED", - level: 2, - }, - { - id: "otpForm", - displayName: "OTP Form", - requirement: "REQUIRED", - level: 2, - }, - { - id: "confirmLink", - displayName: "Confirm Link", - requirement: "REQUIRED", - level: 2, - }, - { - id: "conditionalReviewProfile", - displayName: "Conditional Review Profile", - requirement: "CONDITIONAL", - level: 0, - }, - { - id: "conditionLoa", - displayName: "Condition - Loa", - requirement: "REQUIRED", - level: 1, - }, - { - id: "reviewProfile", - displayName: "Review Profile", - requirement: "REQUIRED", - level: 1, - }, - ]); - - const { container } = render(); - - const testHelper = reactFlowTester(container); - - const expectedNodes = [ - "start", - "usernamePasswordForm", - "conditionUserConfigured", - "conditionUserAttribute", - "otpForm", - "confirmLink", - "conditionLoa", - "reviewProfile", - "end", - ]; - testHelper.expectNodeIds(expectedNodes); - - const expectedEdges = [ - "Edge from start to usernamePasswordForm", - "Edge from usernamePasswordForm to conditionUserConfigured", - "Edge from conditionUserConfigured to conditionUserAttribute", - "Edge from conditionUserConfigured to end", - "Edge from conditionUserAttribute to otpForm", - "Edge from conditionUserAttribute to end", - "Edge from otpForm to confirmLink", - "Edge from confirmLink to end", - "Edge from usernamePasswordForm to conditionLoa", - "Edge from conditionLoa to reviewProfile", - "Edge from conditionLoa to end", - "Edge from reviewProfile to end", - ]; - testHelper.expectEdgeLabels(expectedEdges); - }); - - it("should render the default first broker login flow", () => { - const executionList = new ExecutionList([ - { - id: "reviewProfile", - displayName: "Review Profile", - requirement: "REQUIRED", - level: 0, - }, - { - id: "createOrLink", - displayName: "User creation or linking", - requirement: "REQUIRED", - level: 0, - }, - { - id: "createUnique", - displayName: "Create User If Unique", - requirement: "ALTERNATIVE", - level: 1, - }, - { - id: "existingAccount", - displayName: "Handle Existing Account", - requirement: "ALTERNATIVE", - level: 1, - }, - { - id: "confirmLink", - displayName: "Confirm link existing account", - requirement: "REQUIRED", - level: 2, - }, - { - id: "accountVerification", - displayName: "Account verification options", - requirement: "REQUIRED", - level: 2, - }, - { - id: "emailVerify", - displayName: "Verify existing account by Email", - requirement: "ALTERNATIVE", - level: 3, - }, - { - id: "reauthVerify", - displayName: "Verify Existing Account by Re-authentication", - requirement: "ALTERNATIVE", - level: 3, - }, - { - id: "usernamePassword", - displayName: - "Username Password Form for identity provider reauthentication", - requirement: "REQUIRED", - level: 4, - }, - { - id: "conditionalOtp", - displayName: "First broker login - Conditional OTP", - requirement: "CONDITIONAL", - level: 4, - }, - { - id: "conditionUserConfigured", - displayName: "Condition - user configured", - requirement: "REQUIRED", - level: 5, - }, - { - id: "otpForm", - displayName: "OTP Form", - requirement: "REQUIRED", - level: 5, - }, - ]); - - const { container } = render(); - - const testHelper = reactFlowTester(container); - - const expectedNodes = [ - "start", - "reviewProfile", - "createUnique", - "confirmLink", - "usernamePassword", - "conditionUserConfigured", - "otpForm", - "emailVerify", - "end", - ]; - testHelper.expectNodeIds(expectedNodes); - - const expectedEdges = [ - "Edge from start to reviewProfile", - "Edge from reviewProfile to createUnique", - "Edge from createUnique to confirmLink", - "Edge from createUnique to end", - "Edge from confirmLink to emailVerify", - "Edge from emailVerify to usernamePassword", - "Edge from usernamePassword to conditionUserConfigured", - "Edge from conditionUserConfigured to otpForm", - "Edge from conditionUserConfigured to end", - "Edge from otpForm to end", - "Edge from emailVerify to end", - ]; - testHelper.expectEdgeLabels(expectedEdges); - }); - - it("should hide disabled steps", () => { - const executionList = new ExecutionList([ - { - id: "disabled", - displayName: "Disabled", - requirement: "DISABLED", - }, - { - id: "required", - displayName: "Required", - requirement: "REQUIRED", - }, - ]); - - const { container } = render(); - - const testHelper = reactFlowTester(container); - - const expectedNodes = ["start", "required", "end"]; - testHelper.expectNodeIds(expectedNodes); - - const expectedEdges = [ - "Edge from start to required", - "Edge from required to end", - ]; - testHelper.expectEdgeLabels(expectedEdges); - }); - - it("should hide disabled subflow", () => { - const executionList = new ExecutionList([ - { - id: "required", - displayName: "Required", - requirement: "REQUIRED", - level: 0, - }, - { - id: "subflow", - displayName: "Subflow", - requirement: "DISABLED", - level: 0, - }, - { - id: "subElement", - displayName: "Sub Element", - requirement: "REQUIRED", - level: 1, - }, - ]); - - const { container } = render(); - - const testHelper = reactFlowTester(container); - const expectedNodes = ["start", "required", "end"]; - testHelper.expectNodeIds(expectedNodes); - - const expectedEdges = [ - "Edge from start to required", - "Edge from required to end", - ]; - testHelper.expectEdgeLabels(expectedEdges); - }); -}); diff --git a/js/apps/admin-ui/vite.config.ts b/js/apps/admin-ui/vite.config.ts index cc77e1d4a1e..0d7b511bef9 100644 --- a/js/apps/admin-ui/vite.config.ts +++ b/js/apps/admin-ui/vite.config.ts @@ -6,14 +6,17 @@ import { checker } from "vite-plugin-checker"; export default defineConfig({ base: "", server: { - port: 8080, + origin: "http://localhost:5174", + port: 5174, }, build: { sourcemap: true, target: "esnext", modulePreload: false, cssMinify: "lightningcss", + manifest: true, rollupOptions: { + input: "src/main.tsx", external: ["react", "react/jsx-runtime", "react-dom"], }, }, diff --git a/js/apps/keycloak-server/README.md b/js/apps/keycloak-server/README.md index f8d93ef1f25..45fbeef8f44 100644 --- a/js/apps/keycloak-server/README.md +++ b/js/apps/keycloak-server/README.md @@ -6,22 +6,39 @@ This app allows you to run a local development version of the Keycloak server. First, ensure that all dependencies are installed locally using PNPM by running: -```bash +```sh pnpm install ``` After the dependencies are installed we can start the Keycloak server by running the following command: -```bash +```sh pnpm start ``` -This will download the [Nightly version](https://github.com/keycloak/keycloak/releases/tag/nightly) of the Keycloak server and run it locally on port `8180`. If a previously downloaded version was found in the `server/` directory then that one will be used instead. If you want to download the latest Nightly version you can remove the server directory before running the command to start the server. +If you want to run the server against a local development Vite server, you'll have to pass the `--admin-dev` or `--account-dev` flag: + +```sh +pnpm start --admin-dev +pnpm start --account-dev +``` + +The above commands will download the [Nightly version](https://github.com/keycloak/keycloak/releases/tag/nightly) of the Keycloak server and run it locally on port `8080`. If a previously downloaded version was found in the `server/` directory then that one will be used instead. If you want to download the latest Nightly version you can remove the server directory before running the command to start the server: + +```sh +pnpm delete-server +``` + +Or if you just want to clear the data so you can start fresh without downloading the server again: + +```sh +pnpm delete-data +``` If you want to run with a local Quarkus distribution of Keycloak for development purposes, you can do so by running this command instead: -```bash -pnpm start -- --local +```sh +pnpm start --local ``` **All other arguments will be passed through to the underlying Keycloak server.** diff --git a/js/apps/keycloak-server/package.json b/js/apps/keycloak-server/package.json index 7e55fd26bc4..ed44fd5ecce 100644 --- a/js/apps/keycloak-server/package.json +++ b/js/apps/keycloak-server/package.json @@ -2,20 +2,11 @@ "name": "keycloak-server", "type": "module", "scripts": { - "start": "wireit", + "start": "node ./scripts/start-server.js", "delete-data": "rm -r ./server/data", "delete-server": "rm -r ./server" }, - "wireit": { - "start": { - "command": "node ./scripts/start-server.js", - "dependencies": [ - "../../libs/keycloak-admin-client:build" - ] - } - }, "dependencies": { - "@keycloak/keycloak-admin-client": "workspace:*", "@octokit/rest": "^20.1.1", "@types/gunzip-maybe": "^1.4.2", "@types/tar-fs": "^2.0.4", diff --git a/js/apps/keycloak-server/scripts/security-admin-console-v2.json b/js/apps/keycloak-server/scripts/security-admin-console-v2.json deleted file mode 100644 index 0a734768375..00000000000 --- a/js/apps/keycloak-server/scripts/security-admin-console-v2.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "clientId": "security-admin-console-v2", - "rootUrl": "http://localhost:8080/", - "adminUrl": "http://localhost:8080/", - "surrogateAuthRequired": false, - "enabled": true, - "alwaysDisplayInConsole": false, - "clientAuthenticatorType": "client-secret", - "redirectUris": [ - "http://localhost:8080/*" - ], - "webOrigins": [ - "http://localhost:8080" - ], - "notBefore": 0, - "bearerOnly": false, - "consentRequired": false, - "standardFlowEnabled": true, - "implicitFlowEnabled": false, - "directAccessGrantsEnabled": true, - "serviceAccountsEnabled": false, - "publicClient": true, - "frontchannelLogout": false, - "protocol": "openid-connect", - "attributes": { - "security.admin.console": "true" - }, - "authenticationFlowBindingOverrides": {}, - "fullScopeAllowed": true, - "nodeReRegistrationTimeout": -1, - "defaultClientScopes": [ - "web-origins", - "role_list", - "roles", - "profile", - "email" - ], - "optionalClientScopes": [ - "address", - "phone", - "offline_access", - "microprofile-jwt" - ], - "access": { - "view": true, - "configure": true, - "manage": true - } -} diff --git a/js/apps/keycloak-server/scripts/start-server.js b/js/apps/keycloak-server/scripts/start-server.js index 513358ce487..6e2014082ff 100755 --- a/js/apps/keycloak-server/scripts/start-server.js +++ b/js/apps/keycloak-server/scripts/start-server.js @@ -1,10 +1,8 @@ #!/usr/bin/env node -import KcAdminClient from "@keycloak/keycloak-admin-client"; import { Octokit } from "@octokit/rest"; import gunzip from "gunzip-maybe"; import { spawn } from "node:child_process"; import fs from "node:fs"; -import { readFile } from "node:fs/promises"; import path from "node:path"; import { pipeline } from "node:stream/promises"; import { fileURLToPath } from "node:url"; @@ -18,13 +16,17 @@ const LOCAL_DIST_NAME = "keycloak-999.0.0-SNAPSHOT.tar.gz"; const SCRIPT_EXTENSION = process.platform === "win32" ? ".bat" : ".sh"; const ADMIN_USERNAME = "admin"; const ADMIN_PASSWORD = "admin"; -const AUTH_DELAY = 10000; -const AUTH_RETRY_LIMIT = 3; const options = { local: { type: "boolean", }, + "account-dev": { + type: "boolean", + }, + "admin-dev": { + type: "boolean", + }, }; await startServer(); @@ -34,30 +36,37 @@ async function startServer() { await downloadServer(scriptArgs.local); + const env = { + KEYCLOAK_ADMIN: ADMIN_USERNAME, + KEYCLOAK_ADMIN_PASSWORD: ADMIN_PASSWORD, + ...process.env, + }; + + if (scriptArgs["account-dev"]) { + env.KC_ACCOUNT_VITE_URL = "http://localhost:5173"; + } + + if (scriptArgs["admin-dev"]) { + env.KC_ADMIN_VITE_URL = "http://localhost:5174"; + } + console.info("Starting server…"); + const child = spawn( path.join(SERVER_DIR, `bin/kc${SCRIPT_EXTENSION}`), [ "start-dev", - "--http-port=8180", `--features="login2,account3,admin-fine-grained-authz,transient-users,oid4vc-vci"`, ...keycloakArgs, ], { shell: true, - env: { - KEYCLOAK_ADMIN: ADMIN_USERNAME, - KEYCLOAK_ADMIN_PASSWORD: ADMIN_PASSWORD, - ...process.env, - }, + env, }, ); child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr); - - await wait(AUTH_DELAY); - await importClient(); } function handleArgs(args) { @@ -102,35 +111,6 @@ async function downloadServer(local) { await extractTarball(assetStream, SERVER_DIR, { strip: 1 }); } -async function importClient() { - const adminClient = new KcAdminClient({ - baseUrl: "http://127.0.0.1:8180", - realmName: "master", - }); - - await authenticateAdminClient(adminClient); - - console.info("Checking if client already exists…"); - - const adminConsoleClient = await adminClient.clients.find({ - clientId: "security-admin-console-v2", - }); - - if (adminConsoleClient.length > 0) { - console.info("Client already exists, skipping import."); - return; - } - - console.info("Importing client…"); - - const configPath = path.join(DIR_NAME, "security-admin-console-v2.json"); - const config = JSON.parse(await readFile(configPath, "utf-8")); - - await adminClient.clients.create(config); - - console.info("Client imported successfully."); -} - async function getNightlyAsset() { const api = new Octokit(); const release = await api.repos.getReleaseByTag({ @@ -157,36 +137,3 @@ async function getAssetAsStream(asset) { function extractTarball(stream, path, options) { return pipeline(stream, gunzip(), extract(path, options)); } - -async function authenticateAdminClient( - adminClient, - numRetries = AUTH_RETRY_LIMIT, -) { - console.log("Authenticating admin client…"); - - try { - await adminClient.auth({ - username: ADMIN_USERNAME, - password: ADMIN_PASSWORD, - grantType: "password", - clientId: "admin-cli", - }); - } catch (error) { - if (numRetries === 0) { - throw error; - } - - console.info( - `Authentication failed, retrying in ${AUTH_DELAY / 1000} seconds.`, - ); - - await wait(AUTH_DELAY); - await authenticateAdminClient(adminClient, numRetries - 1); - } - - console.log("Admin client authenticated successfully."); -} - -async function wait(delay) { - return new Promise((resolve) => setTimeout(() => resolve(), delay)); -} diff --git a/js/libs/ui-shared/src/context/environment.ts b/js/libs/ui-shared/src/context/environment.ts index 62e8fed7bc2..528e37d377c 100644 --- a/js/libs/ui-shared/src/context/environment.ts +++ b/js/libs/ui-shared/src/context/environment.ts @@ -20,25 +20,21 @@ export type BaseEnvironment = { }; /** - * Extracts the environment variables that are passed if the application is running as a Keycloak theme and combines them with the provided defaults. - * These variables are injected by Keycloak into the `index.ftl` as a script tag, the contents of which can be parsed as JSON. + * Extracts the environment variables from the document, these variables are injected by Keycloak as a script tag, the contents of which can be parsed as JSON. * - * @argument defaults - The default values to fall to if a value is not present in the environment. + * @argument defaults - The default values to fall to if a value is not found in the environment. */ export function getInjectedEnvironment(defaults: T): T { const element = document.getElementById("environment"); - let env = {} as T; + const contents = element?.textContent; + + if (typeof contents !== "string") { + throw new Error("Environment variables not found in the document."); + } - // Attempt to parse the contents as JSON and return its value. try { - // If the element cannot be found, return an empty record. - if (element?.textContent) { - env = JSON.parse(element.textContent); - } + return { ...defaults, ...JSON.parse(contents) }; } catch (error) { - console.error("Unable to parse environment variables."); + throw new Error("Unable to parse environment variables as JSON."); } - - // Return the merged environment variables with the defaults. - return { ...defaults, ...env }; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a6df0628ffa..83d701a6215 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -298,9 +298,6 @@ importers: js/apps/keycloak-server: dependencies: - '@keycloak/keycloak-admin-client': - specifier: workspace:* - version: link:../../libs/keycloak-admin-client '@octokit/rest': specifier: ^20.1.1 version: 20.1.1 diff --git a/quarkus/deployment/src/main/java/org/keycloak/quarkus/deployment/KeycloakProcessor.java b/quarkus/deployment/src/main/java/org/keycloak/quarkus/deployment/KeycloakProcessor.java index cb39a811ac8..e3e110e0182 100644 --- a/quarkus/deployment/src/main/java/org/keycloak/quarkus/deployment/KeycloakProcessor.java +++ b/quarkus/deployment/src/main/java/org/keycloak/quarkus/deployment/KeycloakProcessor.java @@ -541,10 +541,10 @@ void persistBuildTimeProperties(BuildProducer resour Configuration.markAsOptimized(properties); } - String profile = Environment.getProfile(); + String profile = org.keycloak.common.util.Environment.getProfile(); if (profile != null) { - properties.put(Environment.PROFILE, profile); + properties.put(org.keycloak.common.util.Environment.PROFILE, profile); properties.put(LaunchMode.current().getProfileKey(), profile); } diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/Environment.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/Environment.java index 0ad19dadf61..b8a20581ab2 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/Environment.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/Environment.java @@ -43,11 +43,8 @@ public final class Environment { public static final String IMPORT_EXPORT_MODE = "import_export"; - public static final String PROFILE ="kc.profile"; - public static final String ENV_PROFILE ="KC_PROFILE"; public static final String DATA_PATH = File.separator + "data"; public static final String DEFAULT_THEMES_PATH = File.separator + "themes"; - public static final String DEV_PROFILE_VALUE = "dev"; public static final String PROD_PROFILE_VALUE = "prod"; public static final String LAUNCH_MODE = "kc.launch.mode"; @@ -103,18 +100,8 @@ public static String getCommand() { return "kc.sh"; } - public static String getProfile() { - String profile = System.getProperty(PROFILE); - - if (profile == null) { - profile = System.getenv(ENV_PROFILE); - } - - return profile; - } - public static void setProfile(String profile) { - System.setProperty(PROFILE, profile); + System.setProperty(org.keycloak.common.util.Environment.PROFILE, profile); System.setProperty(LaunchMode.current().getProfileKey(), profile); System.setProperty(SmallRyeConfig.SMALLRYE_CONFIG_PROFILE, profile); if (isTestLaunchMode()) { @@ -123,15 +110,15 @@ public static void setProfile(String profile) { } public static String getCurrentOrPersistedProfile() { - String profile = getProfile(); + String profile = org.keycloak.common.util.Environment.getProfile(); if(profile == null) { - profile = PersistedConfigSource.getInstance().getValue(PROFILE); + profile = PersistedConfigSource.getInstance().getValue(org.keycloak.common.util.Environment.PROFILE); } return profile; } public static String getProfileOrDefault(String defaultProfile) { - String profile = getProfile(); + String profile = org.keycloak.common.util.Environment.getProfile(); if (profile == null) { profile = defaultProfile; @@ -141,19 +128,19 @@ public static String getProfileOrDefault(String defaultProfile) { } public static boolean isDevMode() { - if (DEV_PROFILE_VALUE.equalsIgnoreCase(getProfile())) { + if (org.keycloak.common.util.Environment.isDevMode()) { return true; } - return DEV_PROFILE_VALUE.equals(getBuildTimeProperty(PROFILE).orElse(null)); + return org.keycloak.common.util.Environment.DEV_PROFILE_VALUE.equals(getBuildTimeProperty(org.keycloak.common.util.Environment.PROFILE).orElse(null)); } public static boolean isDevProfile(){ - return Optional.ofNullable(getProfile()).orElse("").equalsIgnoreCase(DEV_PROFILE_VALUE); + return Optional.ofNullable(org.keycloak.common.util.Environment.getProfile()).orElse("").equalsIgnoreCase(org.keycloak.common.util.Environment.DEV_PROFILE_VALUE); } public static boolean isImportExportMode() { - return IMPORT_EXPORT_MODE.equalsIgnoreCase(getProfile()); + return IMPORT_EXPORT_MODE.equalsIgnoreCase(org.keycloak.common.util.Environment.getProfile()); } public static boolean isWindows() { @@ -161,7 +148,7 @@ public static boolean isWindows() { } public static void forceDevProfile() { - setProfile(DEV_PROFILE_VALUE); + setProfile(org.keycloak.common.util.Environment.DEV_PROFILE_VALUE); } public static Map getProviderFiles() { diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/Messages.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/Messages.java index 8364ebefaea..8a4e5614c38 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/Messages.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/Messages.java @@ -32,7 +32,7 @@ private Messages() { public static String httpsConfigurationNotSet() { StringBuilder builder = new StringBuilder("Key material not provided to setup HTTPS. Please configure your keys/certificates"); - if (!Environment.DEV_PROFILE_VALUE.equals(Environment.getProfile())) { + if (!org.keycloak.common.util.Environment.DEV_PROFILE_VALUE.equals(org.keycloak.common.util.Environment.getProfile())) { builder.append(" or start the server in development mode"); } builder.append("."); @@ -44,7 +44,7 @@ public static void cliExecutionError(CommandLine cmd, String message, Throwable } public static String devProfileNotAllowedError(String cmd) { - return String.format("You can not '%s' the server in %s mode. Please re-build the server first, using 'kc.sh build' for the default production mode.%n", cmd, Environment.getKeycloakModeFromProfile(Environment.DEV_PROFILE_VALUE)); + return String.format("You can not '%s' the server in %s mode. Please re-build the server first, using 'kc.sh build' for the default production mode.%n", cmd, Environment.getKeycloakModeFromProfile(org.keycloak.common.util.Environment.DEV_PROFILE_VALUE)); } public static String invalidLogLevel(String logLevel) { diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Picocli.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Picocli.java index 4e639cf9d4e..879817314e9 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Picocli.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Picocli.java @@ -168,7 +168,7 @@ private static int runReAugmentationIfNeeded(List cliArgs, CommandLine c } if (currentCommandName.equals(StartDev.NAME)) { - String profile = Environment.getProfile(); + String profile = org.keycloak.common.util.Environment.getProfile(); if (profile == null) { // force the server image to be set with the dev profile @@ -461,7 +461,7 @@ private static void outputDisabledProperties(Set properties, boolean bui } private static boolean hasConfigChanges(CommandLine cmdCommand) { - Optional currentProfile = ofNullable(Environment.getProfile()); + Optional currentProfile = ofNullable(org.keycloak.common.util.Environment.getProfile()); Optional persistedProfile = getBuildTimeProperty("kc.profile"); if (!persistedProfile.orElse("").equals(currentProfile.orElse(""))) { diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/Start.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/Start.java index 691249feb3e..7effd9b10a0 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/Start.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/Start.java @@ -65,7 +65,7 @@ private void devProfileNotAllowedError() { } public static boolean isDevProfileNotAllowed() { - Optional currentProfile = Optional.ofNullable(Environment.getProfile()); + Optional currentProfile = Optional.ofNullable(org.keycloak.common.util.Environment.getProfile()); Optional persistedProfile = getRawPersistedProperty("kc.profile"); setProfile(currentProfile.orElse(persistedProfile.orElse("prod"))); diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/Configuration.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/Configuration.java index b1b2ae28cfd..3d95a101a54 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/Configuration.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/Configuration.java @@ -88,10 +88,10 @@ public static Optional getBuildTimeProperty(String name) { } if (value.isEmpty()) { - String profile = Environment.getProfile(); + String profile = org.keycloak.common.util.Environment.getProfile(); if (profile == null) { - profile = getConfig().getRawValue(Environment.PROFILE); + profile = getConfig().getRawValue(org.keycloak.common.util.Environment.PROFILE); } value = getRawPersistedProperty("%" + profile + "." + name); diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/KeycloakConfigSourceProvider.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/KeycloakConfigSourceProvider.java index ba702dad3ef..516f86d36ac 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/KeycloakConfigSourceProvider.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/KeycloakConfigSourceProvider.java @@ -42,7 +42,7 @@ public class KeycloakConfigSourceProvider implements ConfigSourceProvider, Confi } private static void initializeSources() { - String profile = Environment.getProfile(); + String profile = org.keycloak.common.util.Environment.getProfile(); if (profile != null) { System.setProperty("quarkus.profile", profile); diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/PropertyMappers.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/PropertyMappers.java index 38401210ce2..c31904ab1d2 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/PropertyMappers.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/PropertyMappers.java @@ -83,7 +83,7 @@ public static boolean isBuildTimeProperty(String name) { && !ConfigArgsConfigSource.CLI_ARGS.equals(name) && !"kc.home.dir".equals(name) && !"kc.config.file".equals(name) - && !Environment.PROFILE.equals(name) + && !org.keycloak.common.util.Environment.PROFILE.equals(name) && !"kc.show.config".equals(name) && !"kc.show.config.runtime".equals(name) && !"kc.config-file".equals(name); diff --git a/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/test/ConfigurationTest.java b/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/test/ConfigurationTest.java index 6f16837907d..9107e99b090 100644 --- a/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/test/ConfigurationTest.java +++ b/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/test/ConfigurationTest.java @@ -185,7 +185,7 @@ public void testDefaultValue() { @Test public void testKeycloakProfilePropertySubstitution() { - System.setProperty(Environment.PROFILE, "user-profile"); + System.setProperty(org.keycloak.common.util.Environment.PROFILE, "user-profile"); assertEquals("http://filepropprofile.unittest", initConfig("hostname", "default").get("frontendUrl")); } @@ -430,11 +430,11 @@ public void testClusterConfig() { Assert.assertEquals("cache-ispn.xml", initConfig("connectionsInfinispan", "quarkus").get("configFile")); // If explicitly set, then it is always used regardless of the profile - System.clearProperty(Environment.PROFILE); + System.clearProperty(org.keycloak.common.util.Environment.PROFILE); ConfigArgsConfigSource.setCliArgs("--cache=cluster-foo.xml"); Assert.assertEquals("cluster-foo.xml", initConfig("connectionsInfinispan", "quarkus").get("configFile")); - System.setProperty(Environment.PROFILE, "dev"); + System.setProperty(org.keycloak.common.util.Environment.PROFILE, "dev"); Assert.assertEquals("cluster-foo.xml", initConfig("connectionsInfinispan", "quarkus").get("configFile")); ConfigArgsConfigSource.setCliArgs("--cache-stack=foo"); diff --git a/services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java b/services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java index 16e45713d7a..f7ffc3af697 100644 --- a/services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java +++ b/services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java @@ -1,29 +1,14 @@ package org.keycloak.services.resources.account; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; -import java.util.Scanner; -import java.util.function.Function; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.core.Response; -import jakarta.ws.rs.core.UriBuilder; import jakarta.ws.rs.core.UriInfo; -import org.jboss.logging.Logger; import org.jboss.resteasy.reactive.NoCache; import org.keycloak.authentication.requiredactions.DeleteAccount; import org.keycloak.common.Profile; import org.keycloak.common.Version; -import org.keycloak.events.EventStoreProvider; +import org.keycloak.common.util.Environment; import org.keycloak.models.AccountRoles; import org.keycloak.models.ClientModel; import org.keycloak.models.Constants; @@ -40,6 +25,7 @@ import org.keycloak.services.resource.AccountResourceProvider; import org.keycloak.services.resources.RealmsResource; import org.keycloak.services.util.ResolveRelative; +import org.keycloak.services.util.ViteManifest; import org.keycloak.services.validation.Validation; import org.keycloak.theme.FreeMarkerException; import org.keycloak.theme.Theme; @@ -49,6 +35,19 @@ import org.keycloak.util.JsonSerialization; import org.keycloak.utils.MediaType; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.Scanner; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + /** * Created by st on 29/03/17. */ @@ -161,6 +160,26 @@ public Response getMainPage() throws IOException, FreeMarkerException { RequiredActionProviderModel updateEmailActionProvider = realm.getRequiredActionProviderByAlias(UserModel.RequiredAction.UPDATE_EMAIL.name()); map.put("updateEmailActionEnabled", updateEmailActionProvider != null && updateEmailActionProvider.isEnabled()); + final var devServerUrl = Environment.isDevMode() ? System.getenv(ViteManifest.ACCOUNT_VITE_URL) : null; + + if (devServerUrl != null) { + map.put("devServerUrl", devServerUrl); + } + + final var manifestFile = theme.getResourceAsStream(ViteManifest.MANIFEST_FILE_PATH); + + if (devServerUrl == null && manifestFile != null) { + final var manifest = ViteManifest.parseFromInputStream(manifestFile); + final var entryChunk = manifest.getEntryChunk(); + final var entryStyles = entryChunk.css().orElse(new String[] {}); + final var entryScript = entryChunk.file(); + final var entryImports = entryChunk.imports().orElse(new String[] {}); + + map.put("entryStyles", entryStyles); + map.put("entryScript", entryScript); + map.put("entryImports", entryImports); + } + FreeMarkerProvider freeMarkerUtil = session.getProvider(FreeMarkerProvider.class); String result = freeMarkerUtil.processTemplate(map, "index.ftl", theme); Response.ResponseBuilder builder = Response.status(Response.Status.OK).type(MediaType.TEXT_HTML_UTF_8).language(Locale.ENGLISH).entity(result); diff --git a/services/src/main/java/org/keycloak/services/resources/admin/AdminConsole.java b/services/src/main/java/org/keycloak/services/resources/admin/AdminConsole.java index 0a44e244d82..3c010360f8d 100644 --- a/services/src/main/java/org/keycloak/services/resources/admin/AdminConsole.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/AdminConsole.java @@ -18,12 +18,21 @@ import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.ws.rs.ForbiddenException; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.NotAuthorizedException; +import jakarta.ws.rs.NotFoundException; +import jakarta.ws.rs.OPTIONS; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; import org.jboss.resteasy.reactive.NoCache; import org.keycloak.Config; import org.keycloak.common.ClientConnection; import org.keycloak.common.Profile; import org.keycloak.common.Version; +import org.keycloak.common.util.Environment; import org.keycloak.common.util.UriUtils; import org.keycloak.headers.SecurityHeadersProvider; import org.keycloak.http.HttpRequest; @@ -42,20 +51,13 @@ import org.keycloak.services.managers.AuthenticationManager; import org.keycloak.services.managers.ClientManager; import org.keycloak.services.managers.RealmManager; +import org.keycloak.services.util.ViteManifest; import org.keycloak.theme.FreeMarkerException; import org.keycloak.theme.Theme; import org.keycloak.theme.freemarker.FreeMarkerProvider; import org.keycloak.urls.UrlType; import org.keycloak.utils.MediaType; -import jakarta.ws.rs.GET; -import jakarta.ws.rs.NotAuthorizedException; -import jakarta.ws.rs.NotFoundException; -import jakarta.ws.rs.OPTIONS; -import jakarta.ws.rs.Path; -import jakarta.ws.rs.Produces; -import jakarta.ws.rs.QueryParam; -import jakarta.ws.rs.core.Response; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; @@ -358,6 +360,26 @@ public Response getMainPage() throws IOException, FreeMarkerException { map.put("clientId", Constants.ADMIN_CONSOLE_CLIENT_ID); map.put("properties", theme.getProperties()); + final var devServerUrl = Environment.isDevMode() ? System.getenv(ViteManifest.ADMIN_VITE_URL) : null; + + if (devServerUrl != null) { + map.put("devServerUrl", devServerUrl); + } + + final var manifestFile = theme.getResourceAsStream(".vite/manifest.json"); + + if (devServerUrl == null && manifestFile != null) { + final var manifest = ViteManifest.parseFromInputStream(manifestFile); + final var entryChunk = manifest.getEntryChunk(); + final var entryStyles = entryChunk.css().orElse(new String[] {}); + final var entryScript = entryChunk.file(); + final var entryImports = entryChunk.imports().orElse(new String[] {}); + + map.put("entryStyles", entryStyles); + map.put("entryScript", entryScript); + map.put("entryImports", entryImports); + } + FreeMarkerProvider freeMarkerUtil = session.getProvider(FreeMarkerProvider.class); String result = freeMarkerUtil.processTemplate(map, "index.ftl", theme); Response.ResponseBuilder builder = Response.status(Response.Status.OK).type(MediaType.TEXT_HTML_UTF_8).language(Locale.ENGLISH).entity(result); diff --git a/services/src/main/java/org/keycloak/services/util/Chunk.java b/services/src/main/java/org/keycloak/services/util/Chunk.java new file mode 100644 index 00000000000..58a1d5e782a --- /dev/null +++ b/services/src/main/java/org/keycloak/services/util/Chunk.java @@ -0,0 +1,36 @@ +package org.keycloak.services.util; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Optional; + +/** + * Represents a chunk from the Vite build manifest (see {@link ViteManifest}). + */ +public record Chunk ( + @JsonProperty(required = true) + String file, + + @JsonProperty + Optional src, + + @JsonProperty + Optional name, + + @JsonProperty + Optional isEntry, + + @JsonProperty + Optional isDynamicEntry, + + @JsonProperty + Optional imports, + + @JsonProperty + Optional dynamicImports, + + @JsonProperty + Optional assets, + + @JsonProperty Optional css +){} diff --git a/services/src/main/java/org/keycloak/services/util/ViteManifest.java b/services/src/main/java/org/keycloak/services/util/ViteManifest.java new file mode 100644 index 00000000000..74396c935a3 --- /dev/null +++ b/services/src/main/java/org/keycloak/services/util/ViteManifest.java @@ -0,0 +1,42 @@ +package org.keycloak.services.util; + +import com.fasterxml.jackson.core.type.TypeReference; +import org.keycloak.util.JsonSerialization; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Optional; + +/** + * This class is used to parse the Vite manifest file which is generated by the build, this file contains + * a mapping of non-hashed asset filenames to their hashed versions, which can then be used to render the + * correct asset links for scripts, styles, etc. + * + * @see Vite documentation — Backend Integration + */ +public class ViteManifest { + public static final String MANIFEST_FILE_PATH = ".vite/manifest.json"; + public static final String ACCOUNT_VITE_URL = "KC_ACCOUNT_VITE_URL"; + public static final String ADMIN_VITE_URL = "KC_ADMIN_VITE_URL"; + + private final HashMap manifest; + + private ViteManifest(HashMap value) { + this.manifest = value; + } + + public static ViteManifest parseFromInputStream(InputStream input) throws IOException { + final var typeRef = new TypeReference>() {}; + final var value = JsonSerialization.readValue(input, typeRef); + + return new ViteManifest(value); + } + + public Chunk getEntryChunk() { + return manifest.values().stream() + .filter(chunk -> chunk.isEntry().orElse(false)) + .findFirst() + .orElseThrow(); + } +} From 7c297efbd9d93725fd04e1a57cbd2821a51154ff Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Thu, 13 Jun 2024 09:42:38 +0200 Subject: [PATCH 008/103] Migration of sessions in KC25 should run only on migration, not on imports (#30388) Closes #30351 Signed-off-by: Alexander Schwartz --- .../org/keycloak/migration/migrators/MigrateTo25_0_0.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/model/storage-private/src/main/java/org/keycloak/migration/migrators/MigrateTo25_0_0.java b/model/storage-private/src/main/java/org/keycloak/migration/migrators/MigrateTo25_0_0.java index 11a0cded4d3..4888ea8a0eb 100644 --- a/model/storage-private/src/main/java/org/keycloak/migration/migrators/MigrateTo25_0_0.java +++ b/model/storage-private/src/main/java/org/keycloak/migration/migrators/MigrateTo25_0_0.java @@ -45,6 +45,12 @@ public ModelVersion getVersion() { @Override public void migrate(KeycloakSession session) { + // Can be null during store model tests. + if (session.sessions() != null) { + // Offer a migration for persistent user sessions which was added in KC25. + session.sessions().migrate(VERSION.toString()); + } + session.realms().getRealmsStream().forEach(realm -> migrateRealm(session, realm)); } @@ -66,8 +72,6 @@ protected void migrateRealm(KeycloakSession session, RealmModel realm) { LOG.warnf("Client scope '%s' already exists in the realm '%s'. Please migrate this realm manually if you need basic claims in your tokens.", basicScope.getName(), realm.getName()); } - // offer a migration for persistent user sessions which was added in KC25 - session.sessions().migrate(VERSION.toString()); } } From bab06f63de3542b1d3206569198da83723da1813 Mon Sep 17 00:00:00 2001 From: Ryan Emerson Date: Thu, 13 Jun 2024 09:37:44 +0100 Subject: [PATCH 009/103] Pin Ansible version for Aurora Store IT tests to 9.x.y stream Closes #30201 Signed-off-by: Ryan Emerson --- .github/scripts/ansible/aws_ec2.sh | 2 +- .github/workflows/ci.yml | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/scripts/ansible/aws_ec2.sh b/.github/scripts/ansible/aws_ec2.sh index 2677461d592..d6ab3c03213 100755 --- a/.github/scripts/ansible/aws_ec2.sh +++ b/.github/scripts/ansible/aws_ec2.sh @@ -12,7 +12,7 @@ REGION=$2 case $OPERATION in requirements) ansible-galaxy collection install -r requirements.yml - pip3 install --user boto3 botocore + pip3 install --user "ansible==9.*" boto3 botocore ;; create|delete|start|stop) if [ -f "env.yml" ]; then ANSIBLE_CUSTOM_VARS_ARG="-e @env.yml"; fi diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cd5ec8c80bd..6982f6d2fd5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -424,7 +424,6 @@ jobs: export CLUSTER_NAME=keycloak_$(git rev-parse --short HEAD) echo "ec2_cluster=${CLUSTER_NAME}" >> $GITHUB_OUTPUT ./aws_ec2.sh requirements - pipx inject ansible-core boto3 botocore ./aws_ec2.sh create ${REGION} ./keycloak_ec2_installer.sh ${REGION} /tmp/keycloak.zip ./mvn_ec2_runner.sh ${REGION} "clean install -B -DskipTests -Pdistribution" From 1f56a9e48bf96c3bcb18dfc6cd93e3dd16f281f1 Mon Sep 17 00:00:00 2001 From: rmartinc Date: Fri, 14 Jun 2024 12:12:48 +0200 Subject: [PATCH 010/103] Improvements for ldap test authentication Closes #30434 Signed-off-by: rmartinc (cherry picked from commit c51640546d1488e4af9b7e66026720a18d580fb4) --- .../idm/TestLdapConnectionRepresentation.java | 8 ++- .../LDAPServerCapabilitiesManager.java | 17 ++++++- .../UserFederationLdapConnectionTest.java | 50 +++++++++++++++++++ 3 files changed, 72 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/org/keycloak/representations/idm/TestLdapConnectionRepresentation.java b/core/src/main/java/org/keycloak/representations/idm/TestLdapConnectionRepresentation.java index fbf75feedb0..715ac6f6590 100644 --- a/core/src/main/java/org/keycloak/representations/idm/TestLdapConnectionRepresentation.java +++ b/core/src/main/java/org/keycloak/representations/idm/TestLdapConnectionRepresentation.java @@ -16,10 +16,15 @@ public TestLdapConnectionRepresentation() { } public TestLdapConnectionRepresentation(String action, String connectionUrl, String bindDn, String bindCredential, String useTruststoreSpi, String connectionTimeout) { - this(action, connectionUrl, bindDn, bindCredential, useTruststoreSpi, connectionTimeout, null, null); + this(action, connectionUrl, bindDn, bindCredential, useTruststoreSpi, connectionTimeout, null, null, null); } public TestLdapConnectionRepresentation(String action, String connectionUrl, String bindDn, String bindCredential, String useTruststoreSpi, String connectionTimeout, String startTls, String authType) { + this(action, connectionUrl, bindDn, bindCredential, useTruststoreSpi, connectionTimeout, startTls, authType, null); + } + + public TestLdapConnectionRepresentation(String action, String connectionUrl, String bindDn, String bindCredential, + String useTruststoreSpi, String connectionTimeout, String startTls, String authType, String componentId) { this.action = action; this.connectionUrl = connectionUrl; this.bindDn = bindDn; @@ -28,6 +33,7 @@ public TestLdapConnectionRepresentation(String action, String connectionUrl, Str this.connectionTimeout = connectionTimeout; this.startTls = startTls; this.authType = authType; + this.componentId = componentId; } public String getAction() { diff --git a/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java b/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java index 224e1eaaff7..e43da438764 100755 --- a/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java +++ b/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java @@ -16,12 +16,15 @@ */ package org.keycloak.services.managers; +import java.net.URI; import java.util.Collections; +import java.util.Objects; import java.util.Set; import javax.naming.ldap.LdapContext; import org.jboss.logging.Logger; import org.keycloak.common.util.MultivaluedHashMap; +import org.keycloak.component.ComponentModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.LDAPConstants; import org.keycloak.models.RealmModel; @@ -30,6 +33,7 @@ import org.keycloak.services.ServicesLogger; import org.keycloak.storage.ldap.LDAPConfig; import org.keycloak.representations.idm.LDAPCapabilityRepresentation; +import org.keycloak.storage.ldap.idm.model.LDAPDn; import org.keycloak.storage.ldap.idm.store.ldap.LDAPContextManager; import org.keycloak.storage.ldap.idm.store.ldap.LDAPIdentityStore; import org.keycloak.storage.ldap.mappers.membership.group.GroupTreeResolver; @@ -63,8 +67,17 @@ private static int parseConnectionTimeout(String connectionTimeout) { public static LDAPConfig buildLDAPConfig(TestLdapConnectionRepresentation config, RealmModel realm) { String bindCredential = config.getBindCredential(); - if (config.getComponentId() != null && ComponentRepresentation.SECRET_VALUE.equals(bindCredential)) { - bindCredential = realm.getComponent(config.getComponentId()).getConfig().getFirst(LDAPConstants.BIND_CREDENTIAL); + if (config.getComponentId() != null && !LDAPConstants.AUTH_TYPE.equals(LDAPConstants.AUTH_TYPE_NONE) + && ComponentRepresentation.SECRET_VALUE.equals(bindCredential)) { + // check the connection URL and the bind DN are the same to allow using the same configured password + ComponentModel component = realm.getComponent(config.getComponentId()); + if (component != null) { + LDAPConfig ldapConfig = new LDAPConfig(component.getConfig()); + if (Objects.equals(URI.create(config.getConnectionUrl()), URI.create(ldapConfig.getConnectionUrl())) + && Objects.equals(LDAPDn.fromString(config.getBindDn()), LDAPDn.fromString(ldapConfig.getBindDN()))) { + bindCredential = ldapConfig.getBindCredential(); + } + } } MultivaluedHashMap configMap = new MultivaluedHashMap<>(); configMap.putSingle(LDAPConstants.AUTH_TYPE, config.getAuthType()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserFederationLdapConnectionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserFederationLdapConnectionTest.java index 07a69e8b13a..37f9462523a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserFederationLdapConnectionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserFederationLdapConnectionTest.java @@ -18,11 +18,13 @@ package org.keycloak.testsuite.admin; import java.util.List; +import java.util.Map; import org.hamcrest.Matchers; import org.junit.ClassRule; import org.junit.Test; import org.keycloak.models.LDAPConstants; +import org.keycloak.representations.idm.ComponentRepresentation; import org.keycloak.representations.idm.LDAPCapabilityRepresentation; import org.keycloak.representations.idm.TestLdapConnectionRepresentation; import org.keycloak.services.managers.LDAPServerCapabilitiesManager; @@ -147,6 +149,54 @@ public void testLdapConnectionMoreServers() { } + @Test + public void testLdapConnectionComponentAlreadyCreated() { + // create ldap componnet model using ldaps + Map cfg = ldapRule.getConfig(); + cfg.put(LDAPConstants.CONNECTION_URL, "ldaps://localhost:10636"); + cfg.put(LDAPConstants.START_TLS, "false"); + cfg.put(LDAPConstants.USE_TRUSTSTORE_SPI, "true"); + String ldapModelId = testingClient.testing().ldap(REALM_NAME).createLDAPProvider(cfg, false); + try { + // test passing everything with password included + Response response = realm.testLDAPConnection(new TestLdapConnectionRepresentation(LDAPServerCapabilitiesManager.TEST_AUTHENTICATION, + cfg.get(LDAPConstants.CONNECTION_URL), cfg.get(LDAPConstants.BIND_DN), cfg.get(LDAPConstants.BIND_CREDENTIAL), + cfg.get(LDAPConstants.USE_TRUSTSTORE_SPI), cfg.get(LDAPConstants.CONNECTION_TIMEOUT), + cfg.get(LDAPConstants.START_TLS), cfg.get(LDAPConstants.AUTH_TYPE), ldapModelId)); + assertStatus(response, 204); + + // test passing the secret but not changing anything + response = realm.testLDAPConnection(new TestLdapConnectionRepresentation(LDAPServerCapabilitiesManager.TEST_AUTHENTICATION, + cfg.get(LDAPConstants.CONNECTION_URL), cfg.get(LDAPConstants.BIND_DN), ComponentRepresentation.SECRET_VALUE, + cfg.get(LDAPConstants.USE_TRUSTSTORE_SPI), cfg.get(LDAPConstants.CONNECTION_TIMEOUT), + cfg.get(LDAPConstants.START_TLS), cfg.get(LDAPConstants.AUTH_TYPE), ldapModelId)); + assertStatus(response, 204); + + // test passing the secret and changing the connection timeout which is allowed + response = realm.testLDAPConnection(new TestLdapConnectionRepresentation(LDAPServerCapabilitiesManager.TEST_AUTHENTICATION, + cfg.get(LDAPConstants.CONNECTION_URL), cfg.get(LDAPConstants.BIND_DN), ComponentRepresentation.SECRET_VALUE, + cfg.get(LDAPConstants.USE_TRUSTSTORE_SPI), "1000", + cfg.get(LDAPConstants.START_TLS), cfg.get(LDAPConstants.AUTH_TYPE), ldapModelId)); + assertStatus(response, 204); + + // test passing the secret but modifying the connection URL to plain ldap (different URL) + response = realm.testLDAPConnection(new TestLdapConnectionRepresentation(LDAPServerCapabilitiesManager.TEST_AUTHENTICATION, + "ldap://localhost:10389", cfg.get(LDAPConstants.BIND_DN), ComponentRepresentation.SECRET_VALUE, + cfg.get(LDAPConstants.USE_TRUSTSTORE_SPI), cfg.get(LDAPConstants.CONNECTION_TIMEOUT), + cfg.get(LDAPConstants.START_TLS), cfg.get(LDAPConstants.AUTH_TYPE), ldapModelId)); + assertStatus(response, 400); + + // test passing the secret but modifying the user DN + response = realm.testLDAPConnection(new TestLdapConnectionRepresentation(LDAPServerCapabilitiesManager.TEST_AUTHENTICATION, + cfg.get(LDAPConstants.CONNECTION_URL), "uid=anotheradmin,ou=people,dc=keycloak,dc=org", ComponentRepresentation.SECRET_VALUE, + cfg.get(LDAPConstants.USE_TRUSTSTORE_SPI), cfg.get(LDAPConstants.CONNECTION_TIMEOUT), + cfg.get(LDAPConstants.START_TLS), cfg.get(LDAPConstants.AUTH_TYPE), ldapModelId)); + assertStatus(response, 400); + } finally { + adminClient.realm(REALM_NAME).components().removeComponent(ldapModelId); + } + } + @Test public void testLdapCapabilities() { From 9ebf709f834826351d9ebccb5ed207adabc5c642 Mon Sep 17 00:00:00 2001 From: Erik Jan de Wit Date: Wed, 19 Jun 2024 10:44:58 +0200 Subject: [PATCH 011/103] removed useless cell formatter (#30422) (#30551) fixes: #30306 Signed-off-by: Erik Jan de Wit (cherry picked from commit bdf6dff279fc29ce5c3a7a7b8a6062edde6e0c7a) --- js/apps/admin-ui/src/events/EventsSection.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/js/apps/admin-ui/src/events/EventsSection.tsx b/js/apps/admin-ui/src/events/EventsSection.tsx index 7dbf72a5cff..20c45a3b991 100644 --- a/js/apps/admin-ui/src/events/EventsSection.tsx +++ b/js/apps/admin-ui/src/events/EventsSection.tsx @@ -28,7 +28,7 @@ import { Tooltip, } from "@patternfly/react-core"; import { CheckCircleIcon, WarningTriangleIcon } from "@patternfly/react-icons"; -import { cellWidth, expandable } from "@patternfly/react-table"; +import { cellWidth } from "@patternfly/react-table"; import { pickBy } from "lodash-es"; import { useState } from "react"; import { Controller, FormProvider, useForm } from "react-hook-form"; @@ -468,7 +468,6 @@ export default function EventsSection() { { name: "time", displayKey: "time", - cellFormatters: [expandable], cellRenderer: (row) => formatDate(new Date(row.time!), FORMAT_DATE_AND_TIME), }, From 554cdc6db026b81591b83a6e8346890a53bbb4c8 Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Wed, 19 Jun 2024 09:54:02 +0100 Subject: [PATCH 012/103] backport for issue-30510 (#30524) Signed-off-by: Agnieszka Gancarczyk Co-authored-by: Agnieszka Gancarczyk --- .../dropdown-panel/DropdownPanel.tsx | 11 ++++++- .../dropdown-panel/dropdown-panel.css | 15 ++++++--- .../UserDataTableAttributeSearchForm.tsx | 4 ++- js/apps/admin-ui/src/events/AdminEvents.tsx | 8 +++-- .../admin-ui/src/realm-settings/ThemesTab.tsx | 2 +- .../localization/EffectiveMessageBundles.tsx | 33 +++++++++++-------- js/apps/admin-ui/src/util.ts | 9 ++--- 7 files changed, 56 insertions(+), 26 deletions(-) diff --git a/js/apps/admin-ui/src/components/dropdown-panel/DropdownPanel.tsx b/js/apps/admin-ui/src/components/dropdown-panel/DropdownPanel.tsx index b37951c1872..b40230501df 100644 --- a/js/apps/admin-ui/src/components/dropdown-panel/DropdownPanel.tsx +++ b/js/apps/admin-ui/src/components/dropdown-panel/DropdownPanel.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef } from "react"; import { Icon } from "@patternfly/react-core"; import { CaretDownIcon } from "@patternfly/react-icons"; +import { mediaQuery } from "../../util"; import "./dropdown-panel.css"; type DropdownPanelProps = { @@ -63,7 +64,15 @@ const DropdownPanel: React.FC = ({ {searchDropdownOpen && ( -
{children}
+
+ {children} +
)} ); diff --git a/js/apps/admin-ui/src/components/dropdown-panel/dropdown-panel.css b/js/apps/admin-ui/src/components/dropdown-panel/dropdown-panel.css index 243a9d5cf34..4d57ed3797f 100644 --- a/js/apps/admin-ui/src/components/dropdown-panel/dropdown-panel.css +++ b/js/apps/admin-ui/src/components/dropdown-panel/dropdown-panel.css @@ -1,9 +1,8 @@ .kc-dropdown-panel { background-color: transparent; - padding: var(--pf-v5-global--spacer--form-element) var(--pf-v5-global--spacer--sm) - var(--pf-v5-global--spacer--form-element) var(--pf-v5-global--spacer--sm); - border-color: var(--pf-v5-global--BorderColor--300) - var(--pf-v5-global--BorderColor--300) var(--pf-v5-global--BorderColor--200) + padding: var(--pf-v5-global--spacer--form-element) var(--pf-v5-global--spacer--sm) var(--pf-v5-global--spacer--form-element) + var(--pf-v5-global--spacer--sm); + border-color: var(--pf-v5-global--BorderColor--300) var(--pf-v5-global--BorderColor--300) var(--pf-v5-global--BorderColor--200) var(--pf-v5-global--BorderColor--300); border-width: var(--pf-v5-global--BorderWidth--sm); border-style: solid; @@ -36,3 +35,11 @@ padding: 0.75rem; z-index: 1; } + +.light-mode { + background-color: var(--pf-v5-global--Color--light-100); +} + +.dark-mode { + background-color: var(--pf-v5-global--BackgroundColor--300); +} diff --git a/js/apps/admin-ui/src/components/users/UserDataTableAttributeSearchForm.tsx b/js/apps/admin-ui/src/components/users/UserDataTableAttributeSearchForm.tsx index 06fdfc42010..3761bda28ef 100644 --- a/js/apps/admin-ui/src/components/users/UserDataTableAttributeSearchForm.tsx +++ b/js/apps/admin-ui/src/components/users/UserDataTableAttributeSearchForm.tsx @@ -162,7 +162,9 @@ export function UserDataTableAttributeSearchForm({ setSelectAttributeKeyOpen(false); setValue("name", option.name!); }} - /> + > + {label(t, option.displayName!, option.name)} + ))} ); diff --git a/js/apps/admin-ui/src/events/AdminEvents.tsx b/js/apps/admin-ui/src/events/AdminEvents.tsx index ea820c495ba..20b52befc3b 100644 --- a/js/apps/admin-ui/src/events/AdminEvents.tsx +++ b/js/apps/admin-ui/src/events/AdminEvents.tsx @@ -333,7 +333,9 @@ export const AdminEvents = () => { } > {resourceTypes?.map((option) => ( - + + {option} + ))} )} @@ -399,7 +401,9 @@ export const AdminEvents = () => { + > + {option} + ))} )} diff --git a/js/apps/admin-ui/src/realm-settings/ThemesTab.tsx b/js/apps/admin-ui/src/realm-settings/ThemesTab.tsx index 09571f609ca..1dcde7f11f8 100644 --- a/js/apps/admin-ui/src/realm-settings/ThemesTab.tsx +++ b/js/apps/admin-ui/src/realm-settings/ThemesTab.tsx @@ -163,7 +163,7 @@ export const RealmSettingsThemesTab = ({ isOpen={adminUIThemeOpen} placeholderText={t("selectATheme")} data-testid="select-admin-theme" - aria-label="selectAdminTheme" + aria-label={t("selectAdminTheme")} > {themeTypes.admin .filter((theme) => theme.name !== "base") diff --git a/js/apps/admin-ui/src/realm-settings/localization/EffectiveMessageBundles.tsx b/js/apps/admin-ui/src/realm-settings/localization/EffectiveMessageBundles.tsx index ec127fe63db..d7215e47af1 100644 --- a/js/apps/admin-ui/src/realm-settings/localization/EffectiveMessageBundles.tsx +++ b/js/apps/admin-ui/src/realm-settings/localization/EffectiveMessageBundles.tsx @@ -229,6 +229,7 @@ export const EffectiveMessageBundles = ({ (value || "").length > 0, }} @@ -252,7 +253,7 @@ export const EffectiveMessageBundles = ({ field.onChange(""); }} isOpen={selectThemesOpen} - aria-labelledby={t("theme")} + aria-label={t("selectTheme")} chipGroupComponent={ , + > + {t("selectTheme")} + , ].concat( themeNames.map((option) => ( - + + {option} + )), )} @@ -292,6 +295,7 @@ export const EffectiveMessageBundles = ({ (value || "").length > 0, }} @@ -315,7 +319,7 @@ export const EffectiveMessageBundles = ({ field.onChange(""); }} isOpen={selectThemeTypeOpen} - aria-labelledby={t("themeType")} + aria-label={t("selectThemeType")} chipGroupComponent={ , + > + {t("selectThemeType")} + , ].concat( themeTypes.map((option) => ( - + + {option} + )), )} @@ -351,6 +357,7 @@ export const EffectiveMessageBundles = ({ (value || "").length > 0, }} @@ -397,11 +404,11 @@ export const EffectiveMessageBundles = ({ {[ , + > + {t("selectLanguage")} + , ].concat( combinedLocales.map((option) => ( diff --git a/js/apps/admin-ui/src/util.ts b/js/apps/admin-ui/src/util.ts index 72133853499..98c620d7024 100644 --- a/js/apps/admin-ui/src/util.ts +++ b/js/apps/admin-ui/src/util.ts @@ -84,9 +84,10 @@ export function convertAttributeNameToForm( name: string, ): PathValue> { const index = name.indexOf("."); - return `${name.substring(0, index)}.${beerify( - name.substring(index + 1), - )}` as PathValue>; + return `${name.substring(0, index)}.${beerify(name.substring(index + 1))}` as PathValue< + T, + Path + >; } export const beerify = (name: T) => @@ -183,7 +184,7 @@ export const localeToDisplayName = (locale: string, displayLocale: string) => { }; const DARK_MODE_CLASS = "pf-v5-theme-dark"; -const mediaQuery = +export const mediaQuery = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)"); updateDarkMode(mediaQuery?.matches); From 2f9e94ece740a6bdc929a1ca37cd34ea86a76301 Mon Sep 17 00:00:00 2001 From: Pedro Ruivo Date: Wed, 19 Jun 2024 08:59:51 +0100 Subject: [PATCH 013/103] Update to Infinispan 15.0.5.Final Closes #30557 Signed-off-by: Pedro Ruivo --- .../high-availability/examples/generated/ispn-single.yaml | 2 +- .../high-availability/examples/generated/ispn-site-a.yaml | 2 +- .../high-availability/examples/generated/ispn-site-b.yaml | 2 +- pom.xml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/guides/high-availability/examples/generated/ispn-single.yaml b/docs/guides/high-availability/examples/generated/ispn-single.yaml index 9bff526727e..e92fe9f3add 100644 --- a/docs/guides/high-availability/examples/generated/ispn-single.yaml +++ b/docs/guides/high-availability/examples/generated/ispn-single.yaml @@ -224,7 +224,7 @@ spec: expose: type: Route configMapName: "cluster-config" - image: quay.io/infinispan/server:15.0.4.Final + image: quay.io/infinispan/server:15.0.5.Final configListener: enabled: false container: diff --git a/docs/guides/high-availability/examples/generated/ispn-site-a.yaml b/docs/guides/high-availability/examples/generated/ispn-site-a.yaml index 88782afe45f..daa88e8912d 100644 --- a/docs/guides/high-availability/examples/generated/ispn-site-a.yaml +++ b/docs/guides/high-availability/examples/generated/ispn-site-a.yaml @@ -363,7 +363,7 @@ spec: expose: type: Route configMapName: "cluster-config" - image: quay.io/infinispan/server:15.0.4.Final + image: quay.io/infinispan/server:15.0.5.Final configListener: enabled: false container: diff --git a/docs/guides/high-availability/examples/generated/ispn-site-b.yaml b/docs/guides/high-availability/examples/generated/ispn-site-b.yaml index 854c4afd29f..eb2b36fc0ee 100644 --- a/docs/guides/high-availability/examples/generated/ispn-site-b.yaml +++ b/docs/guides/high-availability/examples/generated/ispn-site-b.yaml @@ -363,7 +363,7 @@ spec: expose: type: Route configMapName: "cluster-config" - image: quay.io/infinispan/server:15.0.4.Final + image: quay.io/infinispan/server:15.0.5.Final configListener: enabled: false container: diff --git a/pom.xml b/pom.xml index 6058aacef1b..b1099022087 100644 --- a/pom.xml +++ b/pom.xml @@ -93,7 +93,7 @@ 2.2.224 6.2.13.Final 6.2.13.Final - 15.0.4.Final + 15.0.5.Final 2.1.1 From 49ffc040a03557c411f7da5799fde054d9c65f7a Mon Sep 17 00:00:00 2001 From: Stefan Guilhen Date: Wed, 19 Jun 2024 07:36:06 -0300 Subject: [PATCH 014/103] issue keycloak/keycloak#30300 (#30530) Closes #30300 Signed-off-by: Nicola Beghin (cherry picked from commit 5192275780f2d73f6b1d83bfe6f3996e3b36f314) Co-authored-by: Nicola Beghin --- .../main/resources/META-INF/jpa-changelog-25.0.0.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/model/jpa/src/main/resources/META-INF/jpa-changelog-25.0.0.xml b/model/jpa/src/main/resources/META-INF/jpa-changelog-25.0.0.xml index 9700f5312d4..af1cb735cac 100644 --- a/model/jpa/src/main/resources/META-INF/jpa-changelog-25.0.0.xml +++ b/model/jpa/src/main/resources/META-INF/jpa-changelog-25.0.0.xml @@ -118,10 +118,7 @@ - - - - + @@ -131,7 +128,10 @@ - + + + + From 2abd570531acf09e0935494b172c44be81f61b75 Mon Sep 17 00:00:00 2001 From: Pedro Igor Date: Tue, 18 Jun 2024 12:49:47 -0300 Subject: [PATCH 015/103] Internal read-only attributes have precedence over unmanaged attribute policy Closes #30240 Signed-off-by: Pedro Igor --- .../userprofile/DefaultAttributes.java | 8 +++--- ...ountRestServiceReadOnlyAttributesTest.java | 27 +++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultAttributes.java b/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultAttributes.java index 82609bceeb3..d752bbe79e9 100644 --- a/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultAttributes.java +++ b/server-spi-private/src/main/java/org/keycloak/userprofile/DefaultAttributes.java @@ -94,14 +94,14 @@ public DefaultAttributes(UserProfileContext context, Map attributes, @Override public boolean isReadOnly(String name) { - if (!isManagedAttribute(name)) { - return !isAllowEditUnmanagedAttribute(); - } - if (isReadOnlyFromMetadata(name) || isReadOnlyInternalAttribute(name)) { return true; } + if (!isManagedAttribute(name)) { + return !isAllowEditUnmanagedAttribute(); + } + return getMetadata(name) == null; } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceReadOnlyAttributesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceReadOnlyAttributesTest.java index 2a0c3030c04..7f5cfa8f273 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceReadOnlyAttributesTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/account/AccountRestServiceReadOnlyAttributesTest.java @@ -38,6 +38,7 @@ import org.keycloak.representations.userprofile.config.UPAttribute; import org.keycloak.representations.userprofile.config.UPAttributePermissions; import org.keycloak.representations.userprofile.config.UPConfig; +import org.keycloak.representations.userprofile.config.UPConfig.UnmanagedAttributePolicy; import org.keycloak.services.messages.Messages; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.broker.util.SimpleHttpDefault; @@ -47,6 +48,7 @@ import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** @@ -144,6 +146,31 @@ public void testUpdateProfileCannotUpdateReadOnlyAttributes() throws IOException testAccountUpdateAttributeExpectSuccess("deniedSomeAdmin"); } + @Test + public void testUpdateProfileCannotUpdateReadOnlyAttributesUnmanagedEnabled() throws IOException { + UPConfig configuration = testRealm().users().userProfile().getConfiguration(); + UnmanagedAttributePolicy unmanagedAttributePolicy = configuration.getUnmanagedAttributePolicy(); + configuration.setUnmanagedAttributePolicy(UnmanagedAttributePolicy.ENABLED); + getCleanup().addCleanup(() -> { + configuration.setUnmanagedAttributePolicy(unmanagedAttributePolicy); + testRealm().users().userProfile().update(configuration); + }); + testRealm().users().userProfile().update(configuration); + UserRepresentation user = SimpleHttpDefault.doGet(getAccountUrl(null), httpClient).auth(tokenUtil.getToken()).asJson(UserRepresentation.class); + UserResource adminUserResource = ApiUtil.findUserByUsernameId(testRealm(), user.getUsername()); + org.keycloak.representations.idm.UserRepresentation adminUserRep = adminUserResource.toRepresentation(); + adminUserRep.singleAttribute("deniedFoo", "foo"); + adminUserResource.update(adminUserRep); + adminUserResource = ApiUtil.findUserByUsernameId(testRealm(), user.getUsername()); + adminUserRep = adminUserResource.toRepresentation(); + assertEquals("foo", adminUserRep.getAttributes().get("deniedFoo").get(0)); + assertNull(user.getAttributes()); + updateAndGet(user); + adminUserResource = ApiUtil.findUserByUsernameId(testRealm(), user.getUsername()); + adminUserRep = adminUserResource.toRepresentation(); + assertEquals("foo", adminUserRep.getAttributes().get("deniedFoo").get(0)); + } + private void testAccountUpdateAttributeExpectFailure(String attrName) throws IOException { testAccountUpdateAttributeExpectFailure(attrName, false); } From f3c30ca462bdf62d704c895d21b3dbab125e4e5d Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Wed, 19 Jun 2024 15:32:53 +0200 Subject: [PATCH 016/103] Fix the website on https://www.keycloak.org/server/db showing some asciidoc related `ifeval` text (#30569) Closes #30417 Signed-off-by: Wim Deblauwe Signed-off-by: Alexander Schwartz Co-authored-by: Wim Deblauwe --- docs/guides/server/db.adoc | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/docs/guides/server/db.adoc b/docs/guides/server/db.adoc index 060b2e6c911..ffd6f24ef0c 100644 --- a/docs/guides/server/db.adoc +++ b/docs/guides/server/db.adoc @@ -32,9 +32,22 @@ only exists for development use-cases. The `dev-file` database is not suitable f == Installing a database driver -Database drivers are shipped as part of {project_name} except for the Oracle Database<@profile.ifProduct> and Microsoft SQL Server drivers. +Database drivers are shipped as part of {project_name} except for the +<@profile.ifProduct> +Oracle Database and Microsoft SQL Server drivers. + +<@profile.ifCommunity> +Oracle Database driver. + -Install the necessary missing driver manually if you want to connect to one of these databases or skip this section if you want to connect to a different database for which the database driver is already included. +Install the necessary missing driver manually if you want to connect to +<@profile.ifProduct> +one of these databases + +<@profile.ifCommunity> +this database + +or skip this section if you want to connect to a different database for which the database driver is already included. === Installing the Oracle Database driver @@ -268,7 +281,7 @@ The maximum timeout for this lock is 900 seconds. If a node waits on this lock f <@kc.start parameters="--spi-dblock-jpa-lock-wait-timeout 900"/> == Using Database Vendors with XA transaction support -{project_name} uses non-XA transactions and the appropriate database drivers by default. +{project_name} uses non-XA transactions and the appropriate database drivers by default. If you wish to use the XA transaction support offered by your driver, enter the following command: @@ -278,7 +291,7 @@ If you wish to use the XA transaction support offered by your driver, enter the NOTE: Certain vendors, such as Azure SQL and MariaDB Galera, do not support or rely on the XA transaction mechanism. -XA recovery defaults to enabled and will use the file system location `KEYCLOAK_HOME/data/transaction-logs` to store transaction logs. +XA recovery defaults to enabled and will use the file system location `KEYCLOAK_HOME/data/transaction-logs` to store transaction logs. NOTE: Enabling XA transactions in a containerized environment does not fully support XA recovery unless stable storage is available at that path. From cd7a376ff2052801dce7cb8a8a6ba45b8063ebdd Mon Sep 17 00:00:00 2001 From: rmartinc Date: Tue, 18 Jun 2024 16:25:11 +0200 Subject: [PATCH 017/103] Remove the timeout in authChecker when page is unloaded Closes #30334 Signed-off-by: rmartinc (cherry picked from commit 9a0fcf59824af34825a05f8c3fe74139bf180e8a) --- .../base/login/resources/js/authChecker.js | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/themes/src/main/resources/theme/base/login/resources/js/authChecker.js b/themes/src/main/resources/theme/base/login/resources/js/authChecker.js index c5938c3e89a..51e2579e009 100644 --- a/themes/src/main/resources/theme/base/login/resources/js/authChecker.js +++ b/themes/src/main/resources/theme/base/login/resources/js/authChecker.js @@ -1,6 +1,17 @@ const CHECK_INTERVAL_MILLISECS = 2000; const initialSession = getSession(); +let timeout; + +// Remove the timeout when unloading to avoid execution of the +// checkCookiesAndSetTimer when the page is already submitted +addEventListener("beforeunload", () => { + if (timeout) { + clearTimeout(timeout); + timeout = undefined; + } +}); + export function checkCookiesAndSetTimer(loginRestartUrl) { if (initialSession) { // We started with a session, so there is nothing to do, exit. @@ -11,9 +22,9 @@ export function checkCookiesAndSetTimer(loginRestartUrl) { if (!session) { // The session is not present, check again later. - setTimeout( + timeout = setTimeout( () => checkCookiesAndSetTimer(loginRestartUrl), - CHECK_INTERVAL_MILLISECS + CHECK_INTERVAL_MILLISECS, ); } else { // Redirect to the login restart URL. This can typically automatically login user due the SSO @@ -29,7 +40,9 @@ function getCookieByName(name) { for (const cookie of document.cookie.split(";")) { const [key, value] = cookie.split("=").map((value) => value.trim()); if (key === name) { - return value.startsWith('"') && value.endsWith('"') ? value.slice(1, -1) : value; + return value.startsWith('"') && value.endsWith('"') + ? value.slice(1, -1) + : value; } } return null; From 96e7809b232442e9f74cf8f8768caf50d23d4867 Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Wed, 19 Jun 2024 17:18:15 +0100 Subject: [PATCH 018/103] Backport to fix Frontend URL realm setting label (#30575) Signed-off-by: Agnieszka Gancarczyk Co-authored-by: Agnieszka Gancarczyk --- js/apps/admin-ui/src/realm-settings/GeneralTab.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/apps/admin-ui/src/realm-settings/GeneralTab.tsx b/js/apps/admin-ui/src/realm-settings/GeneralTab.tsx index 2abac57ea7a..3df720b26bd 100644 --- a/js/apps/admin-ui/src/realm-settings/GeneralTab.tsx +++ b/js/apps/admin-ui/src/realm-settings/GeneralTab.tsx @@ -183,7 +183,7 @@ function RealmSettingsGeneralTabForm({ Date: Wed, 19 Jun 2024 21:50:19 +0200 Subject: [PATCH 019/103] Use correct host URL for Admin Console requests (#30535) (#30579) Closes #30432 Signed-off-by: Jon Koops (cherry picked from commit 77fb3c4dd472b1b1b284dc5b6597d7b1e64879d1) --- .../topics/changes/changes-25_0_0.adoc | 19 ++--- js/apps/account-ui/README.md | 2 +- .../theme/keycloak.v3/account/index.ftl | 1 + js/apps/account-ui/src/api.ts | 14 ++-- js/apps/account-ui/src/api/methods.ts | 2 +- js/apps/account-ui/src/api/request.ts | 2 +- js/apps/account-ui/src/environment.ts | 32 +-------- js/apps/account-ui/src/i18n.ts | 2 +- .../theme/keycloak.v2/admin/index.ftl | 2 + js/apps/admin-ui/src/admin-client.ts | 2 +- js/apps/admin-ui/src/environment.ts | 29 +++----- js/apps/admin-ui/src/i18n/i18n.ts | 2 +- .../add/SamlConnectSettings.tsx | 2 +- .../add/SamlGeneralSettings.tsx | 2 +- .../ui-shared/src/context/KeycloakContext.tsx | 2 +- js/libs/ui-shared/src/context/environment.ts | 24 +++++-- .../resources/account/AccountConsole.java | 38 ++++++---- .../resources/admin/AdminConsole.java | 70 ++++++++----------- 18 files changed, 110 insertions(+), 137 deletions(-) diff --git a/docs/documentation/upgrading/topics/changes/changes-25_0_0.adoc b/docs/documentation/upgrading/topics/changes/changes-25_0_0.adoc index 0dfa4ed8388..1e2dbd88983 100644 --- a/docs/documentation/upgrading/topics/changes/changes-25_0_0.adoc +++ b/docs/documentation/upgrading/topics/changes/changes-25_0_0.adoc @@ -445,22 +445,15 @@ If you wish to use Oracle DB, you must manually install a version of the Oracle = Deprecated theme variables -The following variables were deprecated in the Account theme: +The following variables were deprecated in the Admin theme and will be removed in a future version: -* `authUrl`. Use `authServerUrl` instead. +* `authServerUrl`. Use `serverBaseUrl` instead. +* `authUrl`. Use `adminBaseUrl` instead. -The following variables from the environment script injected into the page of the Account theme are deprecated: +The following variables were deprecated in the Account theme and will be removed in a future version: -* `authUrl`. Use `authServerUrl` instead. -* `features.isInternationalizationEnabled`. Do not use this variable. - -The following variables were deprecated in the Admin theme: - -* `authUrl`. Do not use this variable. - -The following variables from the environment script injected into the page of the Admin theme are deprecated: - -* `authUrl`. Do not use this variable. +* `authServerUrl`. Use `serverBaseUrl` instead, note `serverBaseUrl` does not include trailing slash. +* `authUrl`. Use `serverBaseUrl` instead, note `serverBaseUrl` does not include trailing slash. = Methods to get and set current refresh token in client session are now deprecated diff --git a/js/apps/account-ui/README.md b/js/apps/account-ui/README.md index 9d03f353f3b..c7802611de7 100644 --- a/js/apps/account-ui/README.md +++ b/js/apps/account-ui/README.md @@ -22,7 +22,7 @@ import { KeycloakProvider } from "@keycloak/keycloak-account-ui"; //... diff --git a/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/index.ftl b/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/index.ftl index 1cc5a4d4e9c..47332e2b589 100644 --- a/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/index.ftl +++ b/js/apps/account-ui/maven-resources/theme/keycloak.v3/account/index.ftl @@ -110,6 +110,7 @@ + * ``` */ -export function getInjectedEnvironment(defaults: T): T { +export function getInjectedEnvironment(): T { const element = document.getElementById("environment"); const contents = element?.textContent; @@ -33,7 +43,7 @@ export function getInjectedEnvironment(defaults: T): T { } try { - return { ...defaults, ...JSON.parse(contents) }; + return JSON.parse(contents); } catch (error) { throw new Error("Unable to parse environment variables as JSON."); } diff --git a/services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java b/services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java index f7ffc3af697..cebfe97f643 100644 --- a/services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java +++ b/services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java @@ -96,22 +96,34 @@ public void close() { @NoCache @Path("{any:.*}") public Response getMainPage() throws IOException, FreeMarkerException { - UriInfo uriInfo = session.getContext().getUri(UrlType.FRONTEND); - URI accountBaseUrl = uriInfo.getBaseUriBuilder().path(RealmsResource.class).path(realm.getName()) - .path(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).path("/").build(realm); - - Map map = new HashMap<>(); - - URI adminBaseUri = session.getContext().getUri(UrlType.ADMIN).getBaseUri(); - URI authUrl = uriInfo.getBaseUri(); - var authServerUrl = authUrl.getPath().endsWith("/") ? authUrl : authUrl + "/"; - // TODO: The 'authUrl' variable is deprecated and only exists to provide backwards compatibility for older themes, it should be removed in a future version. - map.put("authUrl", authServerUrl); - map.put("authServerUrl", authServerUrl); + // Get the URI info of the server and admin console. + final var serverUriInfo = session.getContext().getUri(UrlType.FRONTEND); + final var adminUriInfo = session.getContext().getUri(UrlType.ADMIN); + + // Get the base URLs of the server and admin console. + final var serverBaseUri = serverUriInfo.getBaseUri(); + final var adminBaseUri = adminUriInfo.getBaseUri(); + + // Strip any trailing slashes from the URLs. + final var serverBaseUrl = serverBaseUri.toString().replaceFirst("/+$", ""); + + final var map = new HashMap(); + final var accountBaseUrl = serverUriInfo.getBaseUriBuilder() + .path(RealmsResource.class) + .path(realm.getName()) + .path(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID) + .path("/") + .build(realm); + + map.put("serverBaseUrl", serverBaseUrl); + // TODO: Some variables are deprecated and only exist to provide backwards compatibility for older themes, they should be removed in a future version. + // Note that these should be removed from the template of the Account Console as well. + map.put("authUrl", serverBaseUrl + "/"); // Superseded by 'serverBaseUrl', remove in the future. + map.put("authServerUrl", serverBaseUrl + "/"); // Superseded by 'serverBaseUrl', remove in the future. map.put("baseUrl", accountBaseUrl.getPath().endsWith("/") ? accountBaseUrl : accountBaseUrl + "/"); map.put("realm", realm); map.put("clientId", Constants.ACCOUNT_CONSOLE_CLIENT_ID); - map.put("resourceUrl", Urls.themeRoot(authUrl).getPath() + "/" + Constants.ACCOUNT_MANAGEMENT_CLIENT_ID + "/" + theme.getName()); + map.put("resourceUrl", Urls.themeRoot(serverBaseUri).getPath() + "/" + Constants.ACCOUNT_MANAGEMENT_CLIENT_ID + "/" + theme.getName()); map.put("resourceCommonUrl", Urls.themeRoot(adminBaseUri).getPath() + "/common/keycloak"); map.put("resourceVersion", Version.RESOURCES_VERSION); diff --git a/services/src/main/java/org/keycloak/services/resources/admin/AdminConsole.java b/services/src/main/java/org/keycloak/services/resources/admin/AdminConsole.java index 3c010360f8d..9c24070d237 100644 --- a/services/src/main/java/org/keycloak/services/resources/admin/AdminConsole.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/AdminConsole.java @@ -313,47 +313,39 @@ protected RealmModel getAdminstrationRealm(RealmManager realmManager) { } /** - * Main page of this realm's admin console - * - * @return - * @throws URISyntaxException + * Main page of this realm's admin console. */ @GET @NoCache public Response getMainPage() throws IOException, FreeMarkerException { - if (!session.getContext().getUri(UrlType.ADMIN).getRequestUri().getPath().endsWith("/")) { - return Response.status(302).location(session.getContext().getUri(UrlType.ADMIN).getRequestUriBuilder().path("/").build()).build(); - } else { - Theme theme = AdminRoot.getTheme(session, realm); - - Map map = new HashMap<>(); - - URI adminBaseUri = session.getContext().getUri(UrlType.ADMIN).getBaseUri(); - String adminBaseUrl = adminBaseUri.toString(); - if (adminBaseUrl.endsWith("/")) { - adminBaseUrl = adminBaseUrl.substring(0, adminBaseUrl.length() - 1); - } - - String kcJsRelativeBasePath = adminBaseUri.getPath(); + final var baseUriInfo = session.getContext().getUri(UrlType.FRONTEND); + final var adminUriInfo = session.getContext().getUri(UrlType.ADMIN); - if(!kcJsRelativeBasePath.endsWith("/")) { - kcJsRelativeBasePath = kcJsRelativeBasePath + "/"; - } - - URI authServerBaseUri = session.getContext().getUri(UrlType.FRONTEND).getBaseUri(); - - String authServerBaseUrl = authServerBaseUri.toString(); - if (authServerBaseUrl.endsWith("/")) { - authServerBaseUrl = authServerBaseUrl.substring(0, authServerBaseUrl.length() - 1); - } - - map.put("authServerUrl", authServerBaseUrl); - // TODO: The 'authUrl' variable is deprecated and only exists to provide backwards compatibility for older themes, it should be removed in a future version. - map.put("authUrl", adminBaseUrl); + // Redirect to a URL with a trailing slash if the current URL doesn't have one. + if (!adminUriInfo.getRequestUri().getPath().endsWith("/")) { + return Response.status(302).location(adminUriInfo.getRequestUriBuilder().path("/").build()).build(); + } else { + // Get the base URLs of the server and admin console. + final var serverBaseUri = baseUriInfo.getBaseUri(); + final var adminBaseUri = adminUriInfo.getBaseUri(); + + // Strip any trailing slashes from the URLs. + final var serverBaseUrl = serverBaseUri.toString().replaceFirst("/+$", ""); + final var adminBaseUrl = adminBaseUri.toString().replaceFirst("/+$", ""); + + final var map = new HashMap(); + final var theme = AdminRoot.getTheme(session, realm); + + map.put("serverBaseUrl", serverBaseUrl); + map.put("adminBaseUrl", adminBaseUrl); + // TODO: Some variables are deprecated and only exist to provide backwards compatibility for older themes, they should be removed in a future version. + // Note that these should be removed from the template of the Administration Console as well. + map.put("authServerUrl", serverBaseUrl); // Superseded by 'serverBaseUrl', remove in the future. + map.put("authUrl", adminBaseUrl); // Superseded by 'adminBaseUrl', remove in the future. map.put("consoleBaseUrl", Urls.adminConsoleRoot(adminBaseUri, realm.getName()).getPath()); map.put("resourceUrl", Urls.themeRoot(adminBaseUri).getPath() + "/admin/" + theme.getName()); map.put("resourceCommonUrl", Urls.themeRoot(adminBaseUri).getPath() + "/common/keycloak"); - map.put("keycloakJsUrl", kcJsRelativeBasePath + "js/keycloak.js?version=" + Version.RESOURCES_VERSION); + map.put("keycloakJsUrl", adminBaseUrl + "/js/keycloak.js?version=" + Version.RESOURCES_VERSION); map.put("masterRealm", Config.getAdminRealm()); map.put("resourceVersion", Version.RESOURCES_VERSION); map.put("loginRealm", realm.getName()); @@ -380,13 +372,13 @@ public Response getMainPage() throws IOException, FreeMarkerException { map.put("entryImports", entryImports); } - FreeMarkerProvider freeMarkerUtil = session.getProvider(FreeMarkerProvider.class); - String result = freeMarkerUtil.processTemplate(map, "index.ftl", theme); - Response.ResponseBuilder builder = Response.status(Response.Status.OK).type(MediaType.TEXT_HTML_UTF_8).language(Locale.ENGLISH).entity(result); + final var freeMarkerUtil = session.getProvider(FreeMarkerProvider.class); + final var result = freeMarkerUtil.processTemplate(map, "index.ftl", theme); + final var builder = Response.status(Response.Status.OK).type(MediaType.TEXT_HTML_UTF_8).language(Locale.ENGLISH).entity(result); - // Replace CSP if admin is hosted on different URL - if (!adminBaseUri.equals(authServerBaseUri)) { - session.getProvider(SecurityHeadersProvider.class).options().allowFrameSrc(UriUtils.getOrigin(authServerBaseUri)); + // Allow iframes to be embedded from the server if the admin console is running on a different URL. + if (!adminBaseUri.equals(serverBaseUri)) { + session.getProvider(SecurityHeadersProvider.class).options().allowFrameSrc(UriUtils.getOrigin(serverBaseUri)); } return builder.build(); From 6d072448e9c95027a94d96986aa2777eba08509f Mon Sep 17 00:00:00 2001 From: Hynek Mlnarik Date: Thu, 20 Jun 2024 08:09:03 +0200 Subject: [PATCH 020/103] Fix partial_import_test Fixes: keycloak#30492 Signed-off-by: Hynek Mlnarik --- js/apps/admin-ui/cypress/e2e/partial_import_test.spec.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/js/apps/admin-ui/cypress/e2e/partial_import_test.spec.ts b/js/apps/admin-ui/cypress/e2e/partial_import_test.spec.ts index 46247c2f081..ad1b1b47dbd 100644 --- a/js/apps/admin-ui/cypress/e2e/partial_import_test.spec.ts +++ b/js/apps/admin-ui/cypress/e2e/partial_import_test.spec.ts @@ -119,6 +119,8 @@ describe("Partial import test", () => { //clear button should be disabled if there is nothing in the dialog modal.clearButton().should("be.disabled"); + modal.textArea().get(".view-lines").should("have.text", ""); + modal.textArea().get(".view-lines").click(); modal.textArea().type("{}", { force: true }); modal.textArea().get(".view-lines").should("have.text", "{}"); modal.clearButton().should("not.be.disabled"); From 3b3ca601bb759b31f88e96c22388318df071e27a Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Thu, 20 Jun 2024 17:01:41 +0200 Subject: [PATCH 021/103] Remove AUTO_SERVER H2 default JDBC property (#30560) This avoids problems if the hostname can't be resolved by InetAddress.getLocalHost() Closes #26042 Signed-off-by: Alexander Schwartz --- .github/workflows/ci.yml | 2 +- .../main/java/org/keycloak/config/database/Database.java | 2 +- .../runtime/configuration/test/ConfigurationTest.java | 2 +- testsuite/integration-arquillian/HOW-TO-RUN.md | 6 +++--- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6982f6d2fd5..aea299ea3c4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -533,7 +533,7 @@ jobs: - name: Run cluster tests run: | - ./mvnw test ${{ env.SUREFIRE_RETRY }} -Pauth-server-cluster-quarkus -Dsession.cache.owners=2 -Dtest=**.cluster.** -pl testsuite/integration-arquillian/tests/base 2>&1 | misc/log/trimmer.sh + ./mvnw test ${{ env.SUREFIRE_RETRY }} -Pauth-server-cluster-quarkus,db-postgres -Dsession.cache.owners=2 -Dtest=**.cluster.** -pl testsuite/integration-arquillian/tests/base 2>&1 | misc/log/trimmer.sh - name: Upload JVM Heapdumps if: always() diff --git a/quarkus/config-api/src/main/java/org/keycloak/config/database/Database.java b/quarkus/config-api/src/main/java/org/keycloak/config/database/Database.java index 1b363191069..af28909ef11 100644 --- a/quarkus/config-api/src/main/java/org/keycloak/config/database/Database.java +++ b/quarkus/config-api/src/main/java/org/keycloak/config/database/Database.java @@ -123,7 +123,7 @@ public String apply(String alias) { if ("dev-file".equalsIgnoreCase(alias)) { return addH2NonKeywords("jdbc:h2:file:${kc.home.dir:${kc.db-url-path:" + escapeReplacements(System.getProperty("user.home")) + "}}" + escapeReplacements(File.separator) + "${kc.data.dir:data}" + escapeReplacements(File.separator) + "h2" + escapeReplacements(File.separator) - + "keycloakdb${kc.db-url-properties:;;AUTO_SERVER=TRUE}"); + + "keycloakdb${kc.db-url-properties:}"); } return addH2NonKeywords("jdbc:h2:mem:keycloakdb${kc.db-url-properties:}"); } diff --git a/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/test/ConfigurationTest.java b/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/test/ConfigurationTest.java index 9107e99b090..94df7eb84c0 100644 --- a/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/test/ConfigurationTest.java +++ b/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/test/ConfigurationTest.java @@ -292,7 +292,7 @@ public void testDatabaseDefaults() { .toString() .replaceFirst(isWindows() ? "file:///" : "file://", ""); - assertEquals("jdbc:h2:file:" + userHomeUri + "data/h2/keycloakdb;;AUTO_SERVER=TRUE;NON_KEYWORDS=VALUE", config.getConfigValue("quarkus.datasource.jdbc.url").getValue()); + assertEquals("jdbc:h2:file:" + userHomeUri + "data/h2/keycloakdb;NON_KEYWORDS=VALUE", config.getConfigValue("quarkus.datasource.jdbc.url").getValue()); ConfigArgsConfigSource.setCliArgs("--db=dev-mem"); config = createConfig(); diff --git a/testsuite/integration-arquillian/HOW-TO-RUN.md b/testsuite/integration-arquillian/HOW-TO-RUN.md index 50a1cae3fde..ade4e7ba8db 100644 --- a/testsuite/integration-arquillian/HOW-TO-RUN.md +++ b/testsuite/integration-arquillian/HOW-TO-RUN.md @@ -357,17 +357,17 @@ Make sure the `testsuite/integration-arquillian/servers/auth-server/quarkus` mod mvn -f testsuite/integration-arquillian/servers/auth-server/quarkus/pom.xml clean install \ -Pauth-server-cluster-quarkus -Run tests using the `auth-server-cluster-quarkus` profile: +Run tests using the `auth-server-cluster-quarkus` profile and with a database which is not H2: mvn -f testsuite/integration-arquillian/tests/base/pom.xml clean install \ - -Pauth-server-cluster-quarkus \ + -Pauth-server-cluster-quarkus,db-postgres \ -Dsession.cache.owners=2 \ -Dtest=AuthenticationSessionFailoverClusterTest Alternatively, you can perform both steps using the following command: mvn -f testsuite/integration-arquillian/pom.xml clean install \ - -Pauth-server-cluster-quarkus \ + -Pauth-server-cluster-quarkus,db-postgres \ -Dsession.cache.owners=2 \ -Dtest=AuthenticationSessionFailoverClusterTest From aee8801079e9b27786e737492108d8e1dd25e381 Mon Sep 17 00:00:00 2001 From: miikuru002 <38484391+miikuru002@users.noreply.github.com> Date: Thu, 20 Jun 2024 05:41:33 -0500 Subject: [PATCH 022/103] Fix invalid parameter for Spanish translation Closes #30591 Signed-off-by: J. Ortega --- .../theme/base/email/messages/messages_es.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/themes/src/main/resources-community/theme/base/email/messages/messages_es.properties b/themes/src/main/resources-community/theme/base/email/messages/messages_es.properties index f41b033a647..bd00018b689 100644 --- a/themes/src/main/resources-community/theme/base/email/messages/messages_es.properties +++ b/themes/src/main/resources-community/theme/base/email/messages/messages_es.properties @@ -28,7 +28,7 @@ emailTestBody=Este es un mensaje de prueba emailTestBodyHtml=

Este es un mensaje de prueba

identityProviderLinkSubject=Enlace {0} identityProviderLinkBody=Alguien quiere vincular su cuenta "{1}" con la cuenta "{0}" del usuario {2}. Si ha sido usted, haga clic en el siguiente enlace para vincular las cuentas \n\n{3}\n\nEste enlace expirará en {5}.\n\nSi no desea vincular la cuenta, simplemente ignore este mensaje. Si vincula las cuentas, podrá iniciar sesión en {1} a través de {0}. -identityProviderLinkBodyHtml=

Alguien quiere vincular su {1} cuenta con {0} cuenta del usuario {2}. Si ha sido usted, haga clic en el siguiente enlace para vincular las cuentas

Enlace para confirmar el vínculo de cuentas

Este enlace expirará en {5}.

Si no desea vincular la cuenta, simplemente ignore este mensaje. Si vincula las cuentas, podrá iniciar sesión en {1} a través de {0}.

+identityProviderLinkBodyHtml=

Alguien quiere vincular su {1} cuenta con {0} cuenta del usuario {2}. Si ha sido usted, haga clic en el siguiente enlace para vincular las cuentas

Enlace para confirmar el vínculo de cuentas

Este enlace expirará en {5}.

Si no desea vincular la cuenta, simplemente ignore este mensaje. Si vincula las cuentas, podrá iniciar sesión en {1} a través de {0}.

requiredAction.CONFIGURE_TOTP=Configurar OTP requiredAction.TERMS_AND_CONDITIONS=Términos y condiciones From 864445fe0255f57c2deec0a8e833432778e30b95 Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Mon, 24 Jun 2024 10:38:32 +0100 Subject: [PATCH 023/103] Backport fixed tooltip message (#30562) Signed-off-by: Agnieszka Gancarczyk Co-authored-by: Agnieszka Gancarczyk --- .../src/user-federation/ldap/mappers/LdapMapperDetails.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/apps/admin-ui/src/user-federation/ldap/mappers/LdapMapperDetails.tsx b/js/apps/admin-ui/src/user-federation/ldap/mappers/LdapMapperDetails.tsx index 05305f89fdf..c7e90a43deb 100644 --- a/js/apps/admin-ui/src/user-federation/ldap/mappers/LdapMapperDetails.tsx +++ b/js/apps/admin-ui/src/user-federation/ldap/mappers/LdapMapperDetails.tsx @@ -219,7 +219,7 @@ export default function LdapMapperDetails() { From ce28e6785c5a5656797a552b6f43cfc280ffc17d Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Mon, 24 Jun 2024 12:51:35 +0100 Subject: [PATCH 024/103] backport to add missing help messages on tokens tab (#30691) Signed-off-by: Agnieszka Gancarczyk Co-authored-by: Agnieszka Gancarczyk --- .../admin/messages/messages_en.properties | 6 ++++- .../admin-ui/src/realm-settings/TokensTab.tsx | 24 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties index 7cdf677a820..21c1f40bb11 100644 --- a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties +++ b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties @@ -3197,4 +3197,8 @@ noResultsFound=No results found linkedOrganization=Linked organization send=Send redirectWhenEmailMatches=Redirect when email domain matches -redirectWhenEmailMatchesHelp=Automatically redirect the user to this identity provider when the email domain matches the domain \ No newline at end of file +redirectWhenEmailMatchesHelp=Automatically redirect the user to this identity provider when the email domain matches the domain +emailVerificationHelp=Specifies independent timeout for email verification. +idpAccountEmailVerificationHelp=Specifies independent timeout for IdP account email verification. +forgotPasswordHelp=Specifies independent timeout for forgot password. +executeActionsHelp=Specifies independent timeout for execute actions. \ No newline at end of file diff --git a/js/apps/admin-ui/src/realm-settings/TokensTab.tsx b/js/apps/admin-ui/src/realm-settings/TokensTab.tsx index 47bb2233428..0abbf96e265 100644 --- a/js/apps/admin-ui/src/realm-settings/TokensTab.tsx +++ b/js/apps/admin-ui/src/realm-settings/TokensTab.tsx @@ -517,6 +517,12 @@ export const RealmSettingsTokensTab = ({ label={t("emailVerification")} fieldId="emailVerification" id="email-verification" + labelIcon={ + + } > + } > + } > + } > Date: Tue, 25 Jun 2024 10:39:33 +0200 Subject: [PATCH 025/103] Fix usage of management port in the documentation (#30653) (#30732) Health and metrics endpoints are documented as being served on port 8443 instead of 9000 in [the guide about Running Keycloak in a container](https://www.keycloak.org/server/containers#_starting_the_optimized_keycloak_container_image). Closes #30652 Signed-off-by: julien Co-authored-by: julien-sarik <45511956+julien-sarik@users.noreply.github.com> --- docs/guides/server/containers.adoc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/guides/server/containers.adoc b/docs/guides/server/containers.adoc index a6b9a5221fd..be2cdc01645 100644 --- a/docs/guides/server/containers.adoc +++ b/docs/guides/server/containers.adoc @@ -133,7 +133,7 @@ To start the image, run: [source, bash] ---- -podman|docker run --name mykeycloak -p 8443:8443 \ +podman|docker run --name mykeycloak -p 8443:8443 -p 9000:9000 \ -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=change_me \ mykeycloak \ start --optimized @@ -141,9 +141,9 @@ podman|docker run --name mykeycloak -p 8443:8443 \ {project_name} starts in production mode, using only secured HTTPS communication, and is available on `https://localhost:8443`. -Health check endpoints are available at `https://localhost:8443/health`, `https://localhost:8443/health/ready` and `https://localhost:8443/health/live`. +Health check endpoints are available at `https://localhost:9000/health`, `https://localhost:9000/health/ready` and `https://localhost:9000/health/live`. -Opening up `https://localhost:8443/metrics` leads to a page containing operational metrics that could be used by your monitoring solution. +Opening up `https://localhost:9000/metrics` leads to a page containing operational metrics that could be used by your monitoring solution. == Exposing the container to a different port From 394ea13f531ddb75276fd4ed6468629bd6261cad Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Tue, 25 Jun 2024 12:31:10 +0100 Subject: [PATCH 026/103] backport to fix username display in the users dropdown on create/edit user policy (#30737) Signed-off-by: Agnieszka Gancarczyk Co-authored-by: Agnieszka Gancarczyk --- js/apps/admin-ui/src/clients/authorization/policy/User.tsx | 1 + js/apps/admin-ui/src/components/users/UserSelect.tsx | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/js/apps/admin-ui/src/clients/authorization/policy/User.tsx b/js/apps/admin-ui/src/clients/authorization/policy/User.tsx index 1a64d523a0b..db654e064ab 100644 --- a/js/apps/admin-ui/src/clients/authorization/policy/User.tsx +++ b/js/apps/admin-ui/src/clients/authorization/policy/User.tsx @@ -9,6 +9,7 @@ export const User = () => { label="users" helpText={t("policyUsers")} defaultValue={[]} + variant="typeaheadMulti" isRequired /> ); diff --git a/js/apps/admin-ui/src/components/users/UserSelect.tsx b/js/apps/admin-ui/src/components/users/UserSelect.tsx index db1cde18688..962fe459f10 100644 --- a/js/apps/admin-ui/src/components/users/UserSelect.tsx +++ b/js/apps/admin-ui/src/components/users/UserSelect.tsx @@ -154,7 +154,10 @@ export const UserSelect = ({ ); }} > - {selection} + { + users.find((u) => u?.id === selection) + ?.username + } ), )} From b28d291cce77684397cb0ea66d8d6a8c2bda23e5 Mon Sep 17 00:00:00 2001 From: Steven Hawkins Date: Tue, 25 Jun 2024 08:29:33 -0400 Subject: [PATCH 027/103] docs: remove reference to features-disabled=default (#30612) (#30740) closes: #29761 Signed-off-by: Steve Hawkins (cherry picked from commit 1983bfc9b1c27629557e067a76c96478a3358e77) --- docs/guides/server/features.adoc | 5 ----- 1 file changed, 5 deletions(-) diff --git a/docs/guides/server/features.adoc b/docs/guides/server/features.adoc index 2f78a6ca771..5f1029915db 100644 --- a/docs/guides/server/features.adoc +++ b/docs/guides/server/features.adoc @@ -40,11 +40,6 @@ For example to disable `impersonation`, enter this command: <@kc.build parameters="--features-disabled=\"impersonation\""/> -You can disable all default features by entering this command: - -<@kc.build parameters="--features-disabled=\"default\""/> - -This command can be used in combination with `features` to explicitly set what features should be available. It is not allowed to have a feature in both the `features-disabled` list and the `features` list. When a feature is disabled all versions of that feature are disabled. From a6073e36380a9830681016cf2a6e698ef89a874a Mon Sep 17 00:00:00 2001 From: ReneZeidler Date: Tue, 25 Jun 2024 15:27:52 +0200 Subject: [PATCH 028/103] Fix current page highlight in Account UI sidebar navigation (#30403) (#30409) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Correctly set the isActive attribute for NavItems in the PageNav. Also corrects the link for the "Personal info" page in the content.json (no double slash) Fixes #30383 Signed-off-by: René Zeidler --- js/apps/account-ui/public/content.json | 2 +- js/apps/account-ui/src/root/PageNav.tsx | 17 ++++++++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/js/apps/account-ui/public/content.json b/js/apps/account-ui/public/content.json index 3a6e3515fa4..423160303a5 100644 --- a/js/apps/account-ui/public/content.json +++ b/js/apps/account-ui/public/content.json @@ -1,5 +1,5 @@ [ - { "label": "personalInfo", "path": "/" }, + { "label": "personalInfo", "path": "" }, { "label": "accountSecurity", "children": [ diff --git a/js/apps/account-ui/src/root/PageNav.tsx b/js/apps/account-ui/src/root/PageNav.tsx index 0463401e462..228ce279acd 100644 --- a/js/apps/account-ui/src/root/PageNav.tsx +++ b/js/apps/account-ui/src/root/PageNav.tsx @@ -17,7 +17,6 @@ import { } from "react"; import { useTranslation } from "react-i18next"; import { - To, matchPath, useHref, useLinkClickHandler, @@ -92,7 +91,7 @@ function NavMenuItem({ menuItem }: NavMenuItemProps) { if ("path" in menuItem) { return ( - + {t(menuItem.label)} ); @@ -116,31 +115,35 @@ function NavMenuItem({ menuItem }: NavMenuItemProps) { ); } +function getFullUrl(path: string) { + return `${new URL(environment.baseUrl).pathname}${path}`; +} + function matchMenuItem(currentPath: string, menuItem: MenuItem): boolean { if ("path" in menuItem) { - return !!matchPath(menuItem.path, currentPath); + return !!matchPath(getFullUrl(menuItem.path), currentPath); } return menuItem.children.some((child) => matchMenuItem(currentPath, child)); } type NavLinkProps = { - to: To; + path: string; isActive: boolean; }; export const NavLink = ({ - to, + path, isActive, children, }: PropsWithChildren) => { - const menuItemPath = `${new URL(environment.baseUrl).pathname}${to}`; + const menuItemPath = getFullUrl(path); const href = useHref(menuItemPath); const handleClick = useLinkClickHandler(menuItemPath); return ( From e447d29da2ae92957b9dcfb26502cdef971f3ba7 Mon Sep 17 00:00:00 2001 From: Douglas Palmer Date: Mon, 24 Jun 2024 15:33:41 -0700 Subject: [PATCH 029/103] Broken external links Closes #30717 Signed-off-by: Douglas Palmer --- docs/documentation/securing_apps/topics/saml/java/logout.adoc | 2 +- .../server_admin/topics/authentication/kerberos.adoc | 4 ++-- .../server_admin/topics/user-federation/sssd.adoc | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/documentation/securing_apps/topics/saml/java/logout.adoc b/docs/documentation/securing_apps/topics/saml/java/logout.adoc index 15166c52238..7ba190d5b3f 100644 --- a/docs/documentation/securing_apps/topics/saml/java/logout.adoc +++ b/docs/documentation/securing_apps/topics/saml/java/logout.adoc @@ -64,7 +64,7 @@ share HTTP sessions). To cover this case, the SAML session cache described <<_saml_logout_in_cluster,above>> needs to be replicated not only within individual clusters but across all the data centers for example -https://access.redhat.com/documentation/en-us/red_hat_data_grid/6.6/html/administration_and_configuration_guide/chap-externalize_sessions#Externalize_HTTP_Session_from_JBoss_EAP_6.x_to_JBoss_Data_Grid[via standalone Infinispan/JDG server]: +https://docs.redhat.com/en/documentation/red_hat_data_grid/6.6/html/administration_and_configuration_guide/chap-externalize_sessions#Externalize_HTTP_Session_from_JBoss_EAP_6.x_to_JBoss_Data_Grid[via standalone Infinispan/JDG server]: 1. A cache has to be added to the standalone Infinispan/JDG server. diff --git a/docs/documentation/server_admin/topics/authentication/kerberos.adoc b/docs/documentation/server_admin/topics/authentication/kerberos.adoc index 84e255714e8..56a3a411459 100644 --- a/docs/documentation/server_admin/topics/authentication/kerberos.adoc +++ b/docs/documentation/server_admin/topics/authentication/kerberos.adoc @@ -118,7 +118,7 @@ User profile information, such as first name, last name, and email, are not prov ==== Setup and configuration of client machines -Client machines must have a Kerberos client and set up the `krb5.conf` as described <<_server_setup, above>>. The client machines must also enable SPNEGO login support in their browser. See link:https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/system-level_authentication_guide/configuring_applications_for_sso[configuring Firefox for Kerberos] if you are using the Firefox browser. +Client machines must have a Kerberos client and set up the `krb5.conf` as described <<_server_setup, above>>. The client machines must also enable SPNEGO login support in their browser. See link:https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/7/html/system-level_authentication_guide/configuring_applications_for_sso[configuring Firefox for Kerberos] if you are using the Firefox browser. The `.mydomain.org` URI must be in the `network.negotiate-auth.trusted-uris` configuration option. @@ -168,7 +168,7 @@ Configure `forwardable` Kerberos tickets in `krb5.conf` file and add support for [WARNING] ==== -Credential delegation has security implications, so use it only if necessary and only with HTTPS. See https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/system-level_authentication_guide/configuring_applications_for_sso[this article] for more details and an example. +Credential delegation has security implications, so use it only if necessary and only with HTTPS. See https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/7/html/system-level_authentication_guide/configuring_applications_for_sso[this article] for more details and an example. ==== ==== Cross-realm trust diff --git a/docs/documentation/server_admin/topics/user-federation/sssd.adoc b/docs/documentation/server_admin/topics/user-federation/sssd.adoc index 6e94e4ae98d..d7a1cac7bad 100644 --- a/docs/documentation/server_admin/topics/user-federation/sssd.adoc +++ b/docs/documentation/server_admin/topics/user-federation/sssd.adoc @@ -3,9 +3,9 @@ === SSSD and FreeIPA Identity Management integration -{project_name} includes the https://fedoraproject.org/wiki/Features/SSSD[System Security Services Daemon (SSSD)] plugin. SSSD is part of the Fedora and Red Hat Enterprise Linux (RHEL), and it provides access to multiple identities and authentication providers. SSSD also provides benefits such as failover and offline support. For more information, see https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/system-level_authentication_guide/sssd[the Red Hat Enterprise Linux Identity Management documentation]. +{project_name} includes the https://fedoraproject.org/wiki/Features/SSSD[System Security Services Daemon (SSSD)] plugin. SSSD is part of the Fedora and Red Hat Enterprise Linux (RHEL), and it provides access to multiple identities and authentication providers. SSSD also provides benefits such as failover and offline support. For more information, see https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/7/html/system-level_authentication_guide/sssd[the Red Hat Enterprise Linux Identity Management documentation]. -SSSD integrates with the FreeIPA identity management (IdM) server, providing authentication and access control. With this integration, {project_name} can authenticate against privileged access management (PAM) services and retrieve user data from SSSD. For more information about using Red Hat Identity Management in Linux environments, see https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/linux_domain_identity_authentication_and_policy_guide/index[the Red Hat Enterprise Linux Identity Management documentation]. +SSSD integrates with the FreeIPA identity management (IdM) server, providing authentication and access control. With this integration, {project_name} can authenticate against privileged access management (PAM) services and retrieve user data from SSSD. For more information about using Red Hat Identity Management in Linux environments, see https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/7/html/linux_domain_identity_authentication_and_policy_guide/index[the Red Hat Enterprise Linux Identity Management documentation]. image:images/keycloak-sssd-freeipa-integration-overview.png[] From 224cf44973f37e5cdf8aa35a1a6b9a9c2b6aab73 Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Tue, 25 Jun 2024 18:43:30 +0100 Subject: [PATCH 030/103] backport for issue-30199 (#30522) Co-authored-by: Agnieszka Gancarczyk --- .../cypress/e2e/partial_import_test.spec.ts | 2 +- .../partial-import-test-data/client-only.json | 21 +++++++++--------- .../realm-settings/NewAttributeSettings.tsx | 2 ++ .../localization/RealmOverrides.tsx | 22 ++++++++++++++----- .../user-profile/AttributesGroupForm.tsx | 2 ++ 5 files changed, 31 insertions(+), 18 deletions(-) diff --git a/js/apps/admin-ui/cypress/e2e/partial_import_test.spec.ts b/js/apps/admin-ui/cypress/e2e/partial_import_test.spec.ts index ad1b1b47dbd..279f43a5aa9 100644 --- a/js/apps/admin-ui/cypress/e2e/partial_import_test.spec.ts +++ b/js/apps/admin-ui/cypress/e2e/partial_import_test.spec.ts @@ -110,7 +110,7 @@ describe("Partial import test", () => { modal.importButton().click(); cy.contains("One record added"); - cy.contains("customer-portal"); + cy.contains("customer-portal3"); modal.closeButton().click(); }); diff --git a/js/apps/admin-ui/cypress/fixtures/partial-import-test-data/client-only.json b/js/apps/admin-ui/cypress/fixtures/partial-import-test-data/client-only.json index fa7b64ad8bd..b051e3a1fae 100644 --- a/js/apps/admin-ui/cypress/fixtures/partial-import-test-data/client-only.json +++ b/js/apps/admin-ui/cypress/fixtures/partial-import-test-data/client-only.json @@ -1,13 +1,12 @@ { - "clients": [ - { - "clientId": "customer-portal", - "enabled": true, - "adminUrl": "/customer-portal", - "baseUrl": "/customer-portal", - "redirectUris": [ - "/customer-portal/*" - ], - "secret": "password" - }] + "clients": [ + { + "clientId": "customer-portal3", + "enabled": true, + "adminUrl": "/customer-portal", + "baseUrl": "/customer-portal", + "redirectUris": ["/customer-portal/*"], + "secret": "password" + } + ] } diff --git a/js/apps/admin-ui/src/realm-settings/NewAttributeSettings.tsx b/js/apps/admin-ui/src/realm-settings/NewAttributeSettings.tsx index f906af097c0..97ac03ae029 100644 --- a/js/apps/admin-ui/src/realm-settings/NewAttributeSettings.tsx +++ b/js/apps/admin-ui/src/realm-settings/NewAttributeSettings.tsx @@ -31,6 +31,7 @@ import { AttributeAnnotations } from "./user-profile/attribute/AttributeAnnotati import { AttributeGeneralSettings } from "./user-profile/attribute/AttributeGeneralSettings"; import { AttributePermission } from "./user-profile/attribute/AttributePermission"; import { AttributeValidations } from "./user-profile/attribute/AttributeValidations"; +import { i18n } from "../i18n/i18n"; type TranslationForm = { locale: string; @@ -394,6 +395,7 @@ export default function NewAttributeSettings() { }); await saveTranslations(); + i18n.reloadResources(); navigate(toUserProfile({ realm: realmName, tab: "attributes" })); addAlert(t("createAttributeSuccess"), AlertVariant.success); diff --git a/js/apps/admin-ui/src/realm-settings/localization/RealmOverrides.tsx b/js/apps/admin-ui/src/realm-settings/localization/RealmOverrides.tsx index b9cde01c58c..845e96bad1f 100644 --- a/js/apps/admin-ui/src/realm-settings/localization/RealmOverrides.tsx +++ b/js/apps/admin-ui/src/realm-settings/localization/RealmOverrides.tsx @@ -49,7 +49,7 @@ import { ListEmptyState } from "../../components/list-empty-state/ListEmptyState import { PaginatingTableToolbar } from "../../components/table-toolbar/PaginatingTableToolbar"; import { useRealm } from "../../context/realm-context/RealmContext"; import { useWhoAmI } from "../../context/whoami/WhoAmI"; -import { DEFAULT_LOCALE } from "../../i18n/i18n"; +import { DEFAULT_LOCALE, i18n } from "../../i18n/i18n"; import { localeToDisplayName } from "../../util"; import { AddTranslationModal } from "../AddTranslationModal"; @@ -218,6 +218,8 @@ export const RealmOverrides = ({ refreshTable(); translationForm.setValue("key", ""); translationForm.setValue("value", ""); + i18n.reloadResources(); + addAlert(t("addTranslationSuccess"), AlertVariant.success); } catch (error) { addError(t("addTranslationError"), error); @@ -238,15 +240,22 @@ export const RealmOverrides = ({ onConfirm: async () => { try { for (const key of selectedRowKeys) { - await adminClient.realms.deleteRealmLocalizationTexts({ - realm: currentRealm!, - selectedLocale: selectMenuLocale, - key: key, - }); + delete ( + i18n.store.data[whoAmI.getLocale()]["translation"] as Record< + string, + string + > + )[key], + await adminClient.realms.deleteRealmLocalizationTexts({ + realm: currentRealm!, + selectedLocale: selectMenuLocale, + key: key, + }); } setAreAllRowsSelected(false); setSelectedRowKeys([]); refreshTable(); + addAlert(t("deleteAllTranslationsSuccess"), AlertVariant.success); } catch (error) { addError("deleteAllTranslationsError", error); @@ -309,6 +318,7 @@ export const RealmOverrides = ({ }, value, ); + i18n.reloadResources(); addAlert(t("updateTranslationSuccess"), AlertVariant.success); setTableRows(newRows); diff --git a/js/apps/admin-ui/src/realm-settings/user-profile/AttributesGroupForm.tsx b/js/apps/admin-ui/src/realm-settings/user-profile/AttributesGroupForm.tsx index 14aaf3e87f2..3581e6a41a1 100644 --- a/js/apps/admin-ui/src/realm-settings/user-profile/AttributesGroupForm.tsx +++ b/js/apps/admin-ui/src/realm-settings/user-profile/AttributesGroupForm.tsx @@ -40,6 +40,7 @@ import { AddTranslationsDialog, TranslationsType, } from "./attribute/AddTranslationsDialog"; +import { i18n } from "../../i18n/i18n"; function parseAnnotations(input: Record): KeyValueType[] { return Object.entries(input).reduce((p, [key, value]) => { @@ -346,6 +347,7 @@ export default function AttributesGroupForm() { if (success) { await saveTranslations(); + i18n.reloadResources(); navigate(toUserProfile({ realm: realmName, tab: "attributes-group" })); } }; From 70604719d2a4394d41575079b392ab658d6a52ee Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Wed, 26 Jun 2024 13:30:03 +0100 Subject: [PATCH 031/103] backport to restore multivalued switch on create attribute (#30813) Signed-off-by: Agnieszka Gancarczyk Co-authored-by: Agnieszka Gancarczyk --- .../user-profile/attribute/AttributeGeneralSettings.tsx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/js/apps/admin-ui/src/realm-settings/user-profile/attribute/AttributeGeneralSettings.tsx b/js/apps/admin-ui/src/realm-settings/user-profile/attribute/AttributeGeneralSettings.tsx index 0520484501b..7d77b526ab7 100644 --- a/js/apps/admin-ui/src/realm-settings/user-profile/attribute/AttributeGeneralSettings.tsx +++ b/js/apps/admin-ui/src/realm-settings/user-profile/attribute/AttributeGeneralSettings.tsx @@ -42,6 +42,7 @@ import { AddTranslationsDialog, TranslationsType, } from "./AddTranslationsDialog"; +import { DefaultSwitchControl } from "../../../components/SwitchControl"; import "../../realm-settings-section.css"; @@ -271,6 +272,11 @@ export const AttributeGeneralSettings = ({ )} + Date: Wed, 26 Jun 2024 17:50:58 +0200 Subject: [PATCH 032/103] Describe mTLS overrides for the management interface (#30814) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #30094 Signed-off-by: Martin Bartoš --- docs/guides/server/enabletls.adoc | 4 ++++ docs/guides/server/management-interface.adoc | 6 +++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/guides/server/enabletls.adoc b/docs/guides/server/enabletls.adoc index 41e9371cc86..b98429b890e 100644 --- a/docs/guides/server/enabletls.adoc +++ b/docs/guides/server/enabletls.adoc @@ -81,4 +81,8 @@ Using the value `required` sets up {project_name} to always ask for certificates Be aware that this is the basic certificate configuration for mTLS use cases where {project_name} acts as server. When {project_name} acts as client instead, e.g. when {project_name} tries to get a token from a token endpoint of a brokered identity provider that is secured by mTLS, you need to set up the HttpClient to provide the right certificates in the keystore for the outgoing request. To configure mTLS in these scenarios, see <@links.server id="outgoinghttp"/>. +NOTE: Management interface properties are inherited from the main HTTP server, including mTLS settings. +It means when mTLS is set, it is also enabled for the management interface. +To override the behavior, use the `https-management-client-auth` property. + diff --git a/docs/guides/server/management-interface.adoc b/docs/guides/server/management-interface.adoc index 453ddabed9e..d575832c85c 100644 --- a/docs/guides/server/management-interface.adoc +++ b/docs/guides/server/management-interface.adoc @@ -14,10 +14,10 @@ The most significant advantage might be seen in Kubernetes environments as the s == Management interface configuration The management interface is turned on by default, so management endpoints such as `/metrics`, and `/health` are exposed on the default management port `9000`. +The management interface provides a set of options and is fully configurable. In order to change the port for the management interface, you can use the {project_name} option `http-management-port`. -The management interface provides a set of options and is fully configurable. -If these options for the management HTTP server are not explicitly set, their values are automatically inherited from the default HTTP server. +NOTE: If management interface properties are not explicitly set, their values are automatically inherited from the default HTTP server. You can change the relative path of the management interface, as the prefix path for the management endpoints can be different. You can achieve it via the {project_name} option `http-management-relative-path`. @@ -48,4 +48,4 @@ Beware, the `legacy-observability-interface` option is deprecated and will be re It only allows you to give more time for the migration. ==== - \ No newline at end of file + From 843e4e533e432eaf87101a1724b4fdbbf0f56cce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Barto=C5=A1?= Date: Wed, 26 Jun 2024 17:51:32 +0200 Subject: [PATCH 033/103] New operator failing on health checks (#30830) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #30355 Signed-off-by: Martin Bartoš Co-authored-by: Václav Muzikář --- docs/guides/operator/advanced-configuration.adoc | 12 ++++++++---- docs/guides/operator/customizing-keycloak.adoc | 8 ++++---- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/guides/operator/advanced-configuration.adoc b/docs/guides/operator/advanced-configuration.adoc index e0572e5ef01..aa6769eb0e9 100644 --- a/docs/guides/operator/advanced-configuration.adoc +++ b/docs/guides/operator/advanced-configuration.adoc @@ -118,7 +118,7 @@ The `unsupported` field of the CR contains highly experimental configuration opt ==== Pod Template The Pod Template is a raw API representation that is used for the Deployment Template. -This field is a temporary workaround in case no supported field exists at the top level of the CR for your use case. +This field is a temporary workaround in case no supported field exists at the top level of the CR for your use case. The Operator merges the fields of the provided template with the values generated by the Operator for the specific Deployment. With this feature, you have access to a high level of customizations. However, no guarantee exists that the Deployment will work as expected. @@ -204,7 +204,7 @@ It is achieved by providing certain JVM options. For more details, see <@links.server id="containers" />. -== Management Interface +=== Management Interface To change the port of the management interface, use the first-class citizen field `httpManagement.port` in the Keycloak CR. To change the properties of the management interface, you can do it by providing `additionalOptions` field. @@ -225,6 +225,10 @@ spec: value: /management ---- +NOTE: If you are using a custom image, the Operator is *unaware* of any configuration options that might've been specified there. +For instance, it may cause that the management interface uses the `https` schema, but the Operator accesses it via `http` when the TLS settings is specified in the custom image. +To ensure proper TLS configuration, use the `tlsSecret` and `truststores` fields in the Keycloak CR so that the Operator can reflect that. + === Truststores If you need to provide trusted certificates, the Keycloak CR provides a top level feature for configuring the server's truststore as discussed in <@links.server id="keycloak-truststore"/>. @@ -259,7 +263,7 @@ stringData: ... ------ -When running on a Kubernetes or OpenShift environment well-known locations of trusted certificates are included automatically. -This includes /var/run/secrets/kubernetes.io/serviceaccount/ca.crt and the /var/run/secrets/kubernetes.io/serviceaccount/service-ca.crt when present. +When running on a Kubernetes or OpenShift environment well-known locations of trusted certificates are included automatically. +This includes `/var/run/secrets/kubernetes.io/serviceaccount/ca.crt` and the `/var/run/secrets/kubernetes.io/serviceaccount/service-ca.crt` when present. diff --git a/docs/guides/operator/customizing-keycloak.adoc b/docs/guides/operator/customizing-keycloak.adoc index d773b66bab7..3f12b45b046 100644 --- a/docs/guides/operator/customizing-keycloak.adoc +++ b/docs/guides/operator/customizing-keycloak.adoc @@ -43,10 +43,10 @@ spec: hostname: test.keycloak.org ---- -[NOTE] -==== -With custom images, every build time option passed either through a dedicated field or the `additionalOptions` is ignored. -==== +NOTE: With custom images, every build time option passed either through a dedicated field or the `additionalOptions` is ignored. + +NOTE: The Operator is *unaware* of any configuration options that are specified in a custom image. +Use the Keycloak CR for any configuration that requires Operator awareness, namely the TLS and HTTP(S) settings reflected when configuring services and probes. === Non-optimized custom image From 601b5a7e7820e5bfc4018313c104fa7f0af59582 Mon Sep 17 00:00:00 2001 From: Jon Koops Date: Wed, 26 Jun 2024 18:07:54 +0200 Subject: [PATCH 034/103] Use the Keycloak server URL for common resources Closes #30541 Signed-off-by: Jon Koops (cherry picked from commit cd0dbdf2647c7328cafb6f9dc194c8196244d432) --- .../services/resources/account/AccountConsole.java | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java b/services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java index cebfe97f643..778a5e022a8 100644 --- a/services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java +++ b/services/src/main/java/org/keycloak/services/resources/account/AccountConsole.java @@ -96,15 +96,9 @@ public void close() { @NoCache @Path("{any:.*}") public Response getMainPage() throws IOException, FreeMarkerException { - // Get the URI info of the server and admin console. final var serverUriInfo = session.getContext().getUri(UrlType.FRONTEND); - final var adminUriInfo = session.getContext().getUri(UrlType.ADMIN); - - // Get the base URLs of the server and admin console. final var serverBaseUri = serverUriInfo.getBaseUri(); - final var adminBaseUri = adminUriInfo.getBaseUri(); - - // Strip any trailing slashes from the URLs. + // Strip any trailing slashes from the URL. final var serverBaseUrl = serverBaseUri.toString().replaceFirst("/+$", ""); final var map = new HashMap(); @@ -124,7 +118,7 @@ public Response getMainPage() throws IOException, FreeMarkerException { map.put("realm", realm); map.put("clientId", Constants.ACCOUNT_CONSOLE_CLIENT_ID); map.put("resourceUrl", Urls.themeRoot(serverBaseUri).getPath() + "/" + Constants.ACCOUNT_MANAGEMENT_CLIENT_ID + "/" + theme.getName()); - map.put("resourceCommonUrl", Urls.themeRoot(adminBaseUri).getPath() + "/common/keycloak"); + map.put("resourceCommonUrl", Urls.themeRoot(serverBaseUri).getPath() + "/common/keycloak"); map.put("resourceVersion", Version.RESOURCES_VERSION); String[] referrer = getReferrer(); From a091c6e2fe90a3a1b399c77f817e56ad196b9935 Mon Sep 17 00:00:00 2001 From: Hynek Mlnarik Date: Wed, 26 Jun 2024 09:37:05 +0200 Subject: [PATCH 035/103] Conditionally show Client Offline Session Max Fixes: #30521 Signed-off-by: Hynek Mlnarik (cherry picked from commit f65af84191cd296e6303dc360c9e5e05bc6acc32) --- .../admin-ui/cypress/e2e/clients_test.spec.ts | 26 +++++++++++++++++++ .../realm_settings/RealmSettingsPage.ts | 12 +++++++++ .../src/clients/advanced/AdvancedSettings.tsx | 15 +++++++++++ .../src/clients/advanced/TokenLifespan.tsx | 1 + 4 files changed, 54 insertions(+) diff --git a/js/apps/admin-ui/cypress/e2e/clients_test.spec.ts b/js/apps/admin-ui/cypress/e2e/clients_test.spec.ts index 32bbabd0733..7ad6808e6f9 100644 --- a/js/apps/admin-ui/cypress/e2e/clients_test.spec.ts +++ b/js/apps/admin-ui/cypress/e2e/clients_test.spec.ts @@ -20,6 +20,7 @@ import CommonPage from "../support/pages/CommonPage"; import AttributesTab from "../support/pages/admin-ui/manage/AttributesTab"; import DedicatedScopesMappersTab from "../support/pages/admin-ui/manage/clients/client_details/DedicatedScopesMappersTab"; import { ClientRegistrationPage } from "../support/pages/admin-ui/manage/clients/ClientRegistrationPage"; +import RealmSettingsPage from "../support/pages/admin-ui/manage/realm_settings/RealmSettingsPage"; let itemId = "client_crud"; const loginPage = new LoginPage(); @@ -30,6 +31,7 @@ const commonPage = new CommonPage(); const listingPage = new ListingPage(); const attributesTab = new AttributesTab(); const dedicatedScopesMappersTab = new DedicatedScopesMappersTab(); +const realmSettings = new RealmSettingsPage(); describe("Clients test", () => { const realmName = `clients-realm-${uuid()}`; @@ -880,6 +882,30 @@ describe("Clients test", () => { advancedTab.revertCompatibility(); }); + it("Client Offline Session Max", () => { + configureOfflineSessionMaxInRealmSettings(true); + + cy.findByTestId("token-lifespan-clientOfflineSessionMax").should("exist"); + + configureOfflineSessionMaxInRealmSettings(false); + + cy.findByTestId("token-lifespan-clientOfflineSessionMax").should( + "not.exist", + ); + + function configureOfflineSessionMaxInRealmSettings(enabled: boolean) { + commonPage.sidebar().goToRealmSettings(); + realmSettings.goToSessionsTab(); + realmSettings.setOfflineSessionMaxSwitch(enabled); + realmSettings.saveSessions(); + + commonPage.sidebar().goToClients(); + commonPage.tableToolbarUtils().searchItem(client); + commonPage.tableUtils().clickRowItemLink(client); + clientDetailsPage.goToAdvancedTab(); + } + }); + it("Advanced settings", () => { advancedTab.jumpToAdvanced(); diff --git a/js/apps/admin-ui/cypress/support/pages/admin-ui/manage/realm_settings/RealmSettingsPage.ts b/js/apps/admin-ui/cypress/support/pages/admin-ui/manage/realm_settings/RealmSettingsPage.ts index 5de3fe8bc81..1f7cac1f1a3 100644 --- a/js/apps/admin-ui/cypress/support/pages/admin-ui/manage/realm_settings/RealmSettingsPage.ts +++ b/js/apps/admin-ui/cypress/support/pages/admin-ui/manage/realm_settings/RealmSettingsPage.ts @@ -14,6 +14,7 @@ export default class RealmSettingsPage extends CommonPage { generalSaveBtn = "general-tab-save"; generalRevertBtn = "general-tab-revert"; themesSaveBtn = "themes-tab-save"; + sessionsSaveBtn = "sessions-tab-save"; loginTab = "rs-login-tab"; emailTab = "rs-email-tab"; themesTab = "rs-themes-tab"; @@ -402,6 +403,12 @@ export default class RealmSettingsPage extends CommonPage { return this; } + saveSessions() { + cy.findByTestId(this.sessionsSaveBtn).click(); + + return this; + } + addSenderEmail(senderEmail: string) { this.getFromInput().clear(); @@ -710,6 +717,11 @@ export default class RealmSettingsPage extends CommonPage { return this; } + setOfflineSessionMaxSwitch(value: boolean) { + this.setSwitch(this.offlineSessionMaxSwitch, value); + return this; + } + clickAdd() { cy.findByTestId("addEventTypeConfirm").click(); return this; diff --git a/js/apps/admin-ui/src/clients/advanced/AdvancedSettings.tsx b/js/apps/admin-ui/src/clients/advanced/AdvancedSettings.tsx index 92682aa2d6b..aacf2433943 100644 --- a/js/apps/admin-ui/src/clients/advanced/AdvancedSettings.tsx +++ b/js/apps/admin-ui/src/clients/advanced/AdvancedSettings.tsx @@ -111,6 +111,21 @@ export const AdvancedSettings = ({ defaultValue={realm?.offlineSessionIdleTimeout} units={["minute", "day", "hour"]} /> + + {realm?.offlineSessionMaxLifespanEnabled && ( + + )} ( "attributes.tls.client.certificate.bound.access.tokens", diff --git a/js/apps/admin-ui/src/clients/advanced/TokenLifespan.tsx b/js/apps/admin-ui/src/clients/advanced/TokenLifespan.tsx index 5ca11114e23..1434737388b 100644 --- a/js/apps/admin-ui/src/clients/advanced/TokenLifespan.tsx +++ b/js/apps/admin-ui/src/clients/advanced/TokenLifespan.tsx @@ -51,6 +51,7 @@ export const TokenLifespan = ({ label={t(id)} fieldId={id} labelIcon={} + data-testid={`token-lifespan-${id}`} > Date: Thu, 27 Jun 2024 12:30:02 +0100 Subject: [PATCH 036/103] Backport to use clientId instead of id to save client (#30865) Signed-off-by: Agnieszka Gancarczyk Co-authored-by: Agnieszka Gancarczyk --- js/apps/admin-ui/src/components/client/ClientSelect.tsx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/js/apps/admin-ui/src/components/client/ClientSelect.tsx b/js/apps/admin-ui/src/components/client/ClientSelect.tsx index b3320a59240..13514009391 100644 --- a/js/apps/admin-ui/src/components/client/ClientSelect.tsx +++ b/js/apps/admin-ui/src/components/client/ClientSelect.tsx @@ -57,10 +57,7 @@ export const ClientSelect = ({ onFilter={(value) => setSearch(value)} variant={variant} isDisabled={isDisabled} - options={clients.map(({ id, clientId }) => ({ - key: id!, - value: clientId!, - }))} + options={clients.map(({ clientId }) => clientId!)} /> ); }; From ddccf58327657b8dd1ecd2edd86bb346fa706bec Mon Sep 17 00:00:00 2001 From: Jon Koops Date: Thu, 27 Jun 2024 16:15:19 +0200 Subject: [PATCH 037/103] added label to option (#30649) (#30886) fixes: #30552 Signed-off-by: Erik Jan de Wit (cherry picked from commit b07ba763bdbf56e4e729935185748db153563dd8) Co-authored-by: Erik Jan de Wit --- js/apps/admin-ui/src/realm-settings/TokensTab.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/js/apps/admin-ui/src/realm-settings/TokensTab.tsx b/js/apps/admin-ui/src/realm-settings/TokensTab.tsx index 0abbf96e265..dad8fdae0f5 100644 --- a/js/apps/admin-ui/src/realm-settings/TokensTab.tsx +++ b/js/apps/admin-ui/src/realm-settings/TokensTab.tsx @@ -126,7 +126,9 @@ export const RealmSettingsTokensTab = ({ selected={p === field.value} key={`default-sig-alg-${idx}`} value={p} - >
+ > + {p} +
))} )} From 041c7d6b5c876739e96a8b560d845b45c67d3594 Mon Sep 17 00:00:00 2001 From: Jon Koops Date: Thu, 27 Jun 2024 19:15:36 +0200 Subject: [PATCH 038/103] Fix rotated secret (#30331) (#30887) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andreas Blaettlinger (cherry picked from commit d83537005f72256efafa96f87feee0bfa2c56b91) Co-authored-by: Andreas Blättlinger <69153350+andreas-blaettlinger@users.noreply.github.com> --- js/apps/admin-ui/src/clients/credentials/ClientSecret.tsx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/js/apps/admin-ui/src/clients/credentials/ClientSecret.tsx b/js/apps/admin-ui/src/clients/credentials/ClientSecret.tsx index 70dd1f25c43..d25142ff0d3 100644 --- a/js/apps/admin-ui/src/clients/credentials/ClientSecret.tsx +++ b/js/apps/admin-ui/src/clients/credentials/ClientSecret.tsx @@ -8,7 +8,7 @@ import { Split, SplitItem, } from "@patternfly/react-core"; -import { useState } from "react"; +import { useEffect, useState } from "react"; import { useFormContext } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { PasswordInput } from "@keycloak/keycloak-ui-shared"; @@ -121,6 +121,12 @@ export const ClientSecret = ({ client, secret, toggle }: ClientSecretProps) => { }, }); + useEffect(() => { + if (secretRotated !== client.attributes?.["client.secret.rotated"]) { + setSecretRotated(client.attributes?.["client.secret.rotated"]); + } + }, [client, secretRotated]); + return ( <> From 84c9dd59accaea595d16fb1cf82fd756a522ecda Mon Sep 17 00:00:00 2001 From: Romain LABAT Date: Fri, 28 Jun 2024 09:30:02 +0200 Subject: [PATCH 039/103] Support for service accounts when fetch roles is enabled Closes: #30444 Signed-off-by: Romain LABAT Signed-off-by: Pedro Igor Co-authored-by: Pedro Igor --- .../provider/role/RolePolicyProvider.java | 28 ++++++++++++++++--- .../testsuite/authz/RolePolicyTest.java | 23 +++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/authz/policy/common/src/main/java/org/keycloak/authorization/policy/provider/role/RolePolicyProvider.java b/authz/policy/common/src/main/java/org/keycloak/authorization/policy/provider/role/RolePolicyProvider.java index 499acba9a83..43f0eaf91cd 100644 --- a/authz/policy/common/src/main/java/org/keycloak/authorization/policy/provider/role/RolePolicyProvider.java +++ b/authz/policy/common/src/main/java/org/keycloak/authorization/policy/provider/role/RolePolicyProvider.java @@ -22,6 +22,7 @@ import org.jboss.logging.Logger; import org.keycloak.authorization.AuthorizationProvider; +import org.keycloak.authorization.attribute.Attributes.Entry; import org.keycloak.authorization.identity.Identity; import org.keycloak.authorization.model.Policy; import org.keycloak.authorization.policy.evaluation.Evaluation; @@ -31,6 +32,8 @@ import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserModel; +import org.keycloak.models.UserProvider; +import org.keycloak.representations.JsonWebToken; import org.keycloak.representations.idm.authorization.RolePolicyRepresentation; /** @@ -74,9 +77,8 @@ public void evaluate(Evaluation evaluation) { private boolean hasRole(Identity identity, RoleModel role, RealmModel realm, AuthorizationProvider authorizationProvider, boolean fetchRoles) { if (fetchRoles) { - KeycloakSession session = authorizationProvider.getKeycloakSession(); - UserModel user = session.users().getUserById(realm, identity.getId()); - return user.hasRole(role); + UserModel subject = getSubject(identity, realm, authorizationProvider); + return subject != null && subject.hasRole(role); } String roleName = role.getName(); if (role.isClientRole()) { @@ -86,8 +88,26 @@ private boolean hasRole(Identity identity, RoleModel role, RealmModel realm, Aut return identity.hasRealmRole(roleName); } + private UserModel getSubject(Identity identity, RealmModel realm, AuthorizationProvider authorizationProvider) { + KeycloakSession session = authorizationProvider.getKeycloakSession(); + UserProvider users = session.users(); + UserModel user = users.getUserById(realm, identity.getId()); + + if (user == null) { + Entry sub = identity.getAttributes().getValue(JsonWebToken.SUBJECT); + + if (sub == null || sub.isEmpty()) { + return null; + } + + return users.getUserById(realm, sub.asString(0)); + } + + return user; + } + @Override public void close() { } -} \ No newline at end of file +} diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/RolePolicyTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/RolePolicyTest.java index 6057c49888f..0c4c2036b16 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/RolePolicyTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/authz/RolePolicyTest.java @@ -192,6 +192,29 @@ public void testFetchRoles() { assertNotNull(authzClient.authorization("kolo", "password").authorize(new AuthorizationRequest(ticket))); } + @Test + public void testFetchRolesUsingServiceAccount() { + AuthzClient authzClient = getAuthzClient(); + RealmResource realm = getRealm(); + ClientsResource clients = realm.clients(); + ClientRepresentation client = clients.findByClientId(authzClient.getConfiguration().getResource()).get(0); + ClientScopeRepresentation rolesScope = ApiUtil.findClientScopeByName(realm, OIDCLoginProtocolFactory.ROLES_SCOPE).toRepresentation(); + ClientResource clientResource = clients.get(client.getId()); + clientResource.removeDefaultClientScope(rolesScope.getId()); + UserRepresentation serviceAccountUser = clientResource.getServiceAccountUser(); + RoleRepresentation roleB = realm.roles().get("Role B").toRepresentation(); + realm.users().get(serviceAccountUser.getId()).roles().realmLevel().add(List.of(roleB)); + RolePolicyRepresentation roleRep = clientResource.authorization().policies().role().findByName("Role B Policy"); + roleRep.setFetchRoles(true); + clientResource.authorization().policies().role().findById(roleRep.getId()).update(roleRep); + getCleanup().addCleanup(() -> { + clientResource.addDefaultClientScope(rolesScope.getId()); + roleRep.setFetchRoles(false); + clientResource.authorization().policies().role().findById(roleRep.getId()).update(roleRep); + }); + assertNotNull(authzClient.authorization().authorize(new AuthorizationRequest())); + } + private void createRealmRolePolicy(String name, String... roles) { RolePolicyRepresentation policy = new RolePolicyRepresentation(); From 55d611a394b022bec03a47057d59840fdb892032 Mon Sep 17 00:00:00 2001 From: andymunro <48995441+andymunro@users.noreply.github.com> Date: Fri, 28 Jun 2024 09:14:36 -0400 Subject: [PATCH 040/103] Backport 25 Remove inclusive foreword Closes #30856 Signed-off-by: AndyMunro Co-authored-by: Alexander Schwartz --- docs/documentation/api_documentation/topics/overview.adoc | 2 -- .../templates/making-open-source-more-inclusive.adoc | 7 ------- 2 files changed, 9 deletions(-) delete mode 100644 docs/documentation/topics/templates/making-open-source-more-inclusive.adoc diff --git a/docs/documentation/api_documentation/topics/overview.adoc b/docs/documentation/api_documentation/topics/overview.adoc index a06996fbf7b..76616bdfc9f 100644 --- a/docs/documentation/api_documentation/topics/overview.adoc +++ b/docs/documentation/api_documentation/topics/overview.adoc @@ -1,6 +1,4 @@ -include::templates/making-open-source-more-inclusive.adoc[] - == {project_name} API Documentation === JavaDocs Documentation diff --git a/docs/documentation/topics/templates/making-open-source-more-inclusive.adoc b/docs/documentation/topics/templates/making-open-source-more-inclusive.adoc deleted file mode 100644 index 2b88037619f..00000000000 --- a/docs/documentation/topics/templates/making-open-source-more-inclusive.adoc +++ /dev/null @@ -1,7 +0,0 @@ -ifeval::[{project_product}==true] -[preface] -[id="making-open-source-more-inclusive"] -== Making open source more inclusive - -Red Hat is committed to replacing problematic language in our code, documentation, and web properties. We are beginning with these four terms: master, slave, blacklist, and whitelist. Because of the enormity of this endeavor, these changes will be implemented gradually over several upcoming releases. For more details, see link:https://www.redhat.com/en/blog/making-open-source-more-inclusive-eradicating-problematic-language[our CTO Chris Wright's message]. -endif::[] From 9962a70b9442e51c15c967a843e2bc14ab2a9313 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=A1clav=20Muzik=C3=A1=C5=99?= Date: Fri, 28 Jun 2024 15:17:57 +0200 Subject: [PATCH 041/103] Document how Admin REST API endpoints work with Hostname config (#30916) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #30537 Signed-off-by: Václav Muzikář Co-authored-by: Martin Bartoš (cherry picked from commit bce7a29035ecaa8869d2bf9b84dd86e371333f52) --- .../server/configuration-production.adoc | 10 +++++- docs/guides/server/hostname.adoc | 4 ++- docs/guides/server/reverseproxy.adoc | 32 ++++--------------- 3 files changed, 19 insertions(+), 27 deletions(-) diff --git a/docs/guides/server/configuration-production.adoc b/docs/guides/server/configuration-production.adoc index 85a67da200f..a6e2fc0be7a 100644 --- a/docs/guides/server/configuration-production.adoc +++ b/docs/guides/server/configuration-production.adoc @@ -23,6 +23,14 @@ In a production environment, {project_name} instances usually run in a private n For details on the endpoint categories and instructions on how to configure the public hostname for them, see <@links.server id="hostname"/>. +=== Exposing the {project_name} Administration APIs and UI on a different hostname + +It is considered a best practice to expose the {project_name} Administration REST API and Console on a different hostname or context-path than the one used for the public frontend URLs that are used e.g. by login flows. This separation ensures that the Administration interfaces are not exposed to the public internet, which reduces the attack surface. + +WARNING: Access to REST APIs needs to be blocked on the reverse proxy level, if they are not intended to be publicly exposed. + +For details, see <@links.server id="hostname"/>. + == Reverse proxy in a distributed environment Apart from <@links.server id="hostname"/>, production environments usually include a reverse proxy / load balancer component. It separates and unifies access to the network used by your company or organization. For a {project_name} production environment, this component is recommended. @@ -64,4 +72,4 @@ For example, to change the IP stack preference to IPv4, set an environment varia export JAVA_OPTS_APPEND="-Djava.net.preferIPv4Stack=true" ---- - \ No newline at end of file + diff --git a/docs/guides/server/hostname.adoc b/docs/guides/server/hostname.adoc index b9d77409d3f..adcbda951d8 100644 --- a/docs/guides/server/hostname.adoc +++ b/docs/guides/server/hostname.adoc @@ -73,6 +73,8 @@ This allows you to access {project_name} at `https://my.keycloak.org` and the Ad NOTE: Keep in mind that hostname and proxy options do not change the ports on which the server listens. Instead it changes only the ports of static resources like JavaScript and CSS links, OIDC well-known endpoints, redirect URIs, etc. that will be used in front of the proxy. You need to use HTTP configuration options to change the actual ports the server is listening on. Refer to the <@links.server id="all-config"/> for details. +WARNING: Using the `hostname-admin` option does not prevent accessing the Administration REST API endpoints via the frontend URL specified by the `hostname` option. If you want to restrict access to the Administration REST API, you need to do it on the reverse proxy level. Administration Console implicitly accesses the API using the URL as specified by the `hostname-admin` option. + == Background - server endpoints {project_name} exposes several endpoints, each with a different purpose. They are typically used for communication among applications or for managing the server. We recognize 3 main endpoint groups: @@ -110,7 +112,7 @@ Note that `hostname` option must be set to a URL. For more information, refer to === Administration -Similarly to the base frontend URL, you can also set the base URL for resources and endpoints of the administration console. The server exposes the administration console and static resources using a specific URL. This URL is used for redirect URLs, loading resources (CSS, JS), etc. It can be done by setting the `hostname-admin` option: +Similarly to the base frontend URL, you can also set the base URL for resources and endpoints of the administration console. The server exposes the administration console and static resources using a specific URL. This URL is used for redirect URLs, loading resources (CSS, JS), Administration REST API etc. It can be done by setting the `hostname-admin` option: <@kc.start parameters="--hostname https://my.keycloak.org --hostname-admin https://admin.my.keycloak.org:8443"/> diff --git a/docs/guides/server/reverseproxy.adoc b/docs/guides/server/reverseproxy.adoc index 6d7d740d502..9e75a37a4c9 100644 --- a/docs/guides/server/reverseproxy.adoc +++ b/docs/guides/server/reverseproxy.adoc @@ -29,7 +29,7 @@ If this header is incorrectly configured, rogue clients can set this header and NOTE: When using the `xforwarded` setting, the `X-Forwarded-Port` takes precedence over any port included in the `X-Forwarded-Host`. -== Proxy modes +== Proxy modes (deprecated) NOTE: The support for setting proxy modes is deprecated and will be removed in a future {project_name} release. Consider configuring accepted reverse proxy headers instead as described in the chapter above. For migration instructions consult the https://www.keycloak.org/docs/latest/upgrading/index.html#deprecated-proxy-option[Upgrading Guide]. For {project_name}, your choice of proxy modes depends on the TLS termination in your environment. The following proxy modes are available: @@ -57,15 +57,11 @@ To select the proxy mode, enter this command: == Different context-path on reverse proxy {project_name} assumes it is exposed through the reverse proxy under the same context path as {project_name} is configured for. By default {project_name} is exposed through the root (`/`), which means it expects to be exposed through the reverse proxy on `/` as well. -You can use `hostname-path` or `hostname-url` in these cases, for example using `--hostname-path=/auth` if {project_name} is exposed through the reverse proxy on `/auth`. +You can use a full URL for the `hostname` option in these cases, for example using `--hostname=https://my.keycloak.org/auth` if {project_name} is exposed through the reverse proxy on `/auth`. -Alternatively you can also change the context path of {project_name} itself to match the context path for the reverse proxy using the `http-relative-path` option, which will change the context-path of {project_name} itself to match the context path used by the reverse proxy. - -== Trust the proxy to set hostname - -By default, {project_name} needs to know under which hostname it will be called. If your reverse proxy is configured to check for the correct hostname, you can set {project_name} to accept any hostname. +For more details on exposing {project_name} on different hostname or context-path incl. Administration REST API and Console, see <@links.server id="hostname"/>. -<@kc.start parameters="--proxy-headers=forwarded|xforwarded --hostname-strict=false"/> +Alternatively you can also change the context path of {project_name} itself to match the context path for the reverse proxy using the `http-relative-path` option, which will change the context-path of {project_name} itself to match the context path used by the reverse proxy. == Enable sticky sessions @@ -103,16 +99,7 @@ to `false` in order to avoid attaching the node to cookies and just rely on the By default, the `spi-sticky-session-encoder-infinispan-should-attach-route` option value is `true` so that the node name is attached to cookies to indicate to the reverse proxy the node that subsequent requests should be sent to. -=== Exposing the administration console - -By default, the administration console URLs are created solely based on the requests to resolve the proper scheme, host name, and port. For instance, -if you are using the `edge` proxy mode and your proxy is misconfigured, backend requests from your TLS termination proxy are going to use plain HTTP and potentially cause the administration -console from being accessible because URLs are going to be created using the `http` scheme and the proxy does not support plain HTTP. - -In order to proper expose the administration console, you should make sure that your proxy is setting the `X-Forwarded-*` headers herein mentioned in order -to create URLs using the scheme, host name, and port, being exposed by your proxy. - -=== Exposed path recommendations +== Exposed path recommendations When using a reverse proxy, {project_name} only requires certain paths need to be exposed. The following table shows the recommended paths to expose. @@ -135,11 +122,6 @@ The following table shows the recommended paths to expose. |Yes (see note below) |Access to keycloak.js needed for "internal" clients, e.g. the account console -|/welcome/ -| - -|No -|No need exists to expose the welcome page after initial installation. - |/realms/ |/realms/ |Yes @@ -173,7 +155,7 @@ As it's true that the `js` path is needed for internal clients like the account We assume you run {project_name} on the root path `/` on your reverse proxy/gateway's public API. If not, prefix the path with your desired one. -=== Enabling client certificate lookup +== Enabling client certificate lookup When the proxy is configured as a TLS termination proxy the client certificate information can be forwarded to the server through specific HTTP request headers and then used to authenticate clients. You are able to configure how the server is going to retrieve client certificate information depending on the proxy you are using. @@ -226,7 +208,7 @@ to load additional certificates from headers `CERT_CHAIN_0` to `CERT_CHAIN_9` if | Enable trusting NGINX proxy certificate verification, instead of forwarding the certificate to {project_name} and verifying it in {project_name}. |=== -==== Configuring the NGINX provider +=== Configuring the NGINX provider The NGINX SSL/TLS module does not expose the client certificate chain. {project_name}'s NGINX certificate lookup provider rebuilds it by using the {project_name} truststore. From 0b6447518e446e50ccf95847200a4a63a5585cb2 Mon Sep 17 00:00:00 2001 From: Erik Jan de Wit Date: Mon, 1 Jul 2024 10:47:28 +0200 Subject: [PATCH 042/103] small fix to npm package (#30365) (#30646) Signed-off-by: Erik Jan de Wit (cherry picked from commit 99d3611afebd23d74608f3c8056cfcdb06e4a394) --- js/apps/account-ui/src/index.ts | 7 +++++++ js/apps/account-ui/vite.config.ts | 1 + 2 files changed, 8 insertions(+) diff --git a/js/apps/account-ui/src/index.ts b/js/apps/account-ui/src/index.ts index bc29e4b8d7c..5bfe06a547a 100644 --- a/js/apps/account-ui/src/index.ts +++ b/js/apps/account-ui/src/index.ts @@ -55,3 +55,10 @@ export { savePersonalInfo, unLinkAccount, } from "./api/methods"; +export type { Environment as AccountEnvironment } from "./environment"; +export { + KeycloakProvider, + useEnvironment, + useAlerts, +} from "@keycloak/keycloak-ui-shared"; +export { usePromise } from "./utils/usePromise"; diff --git a/js/apps/account-ui/vite.config.ts b/js/apps/account-ui/vite.config.ts index 51ea7015997..d3d666f7dff 100644 --- a/js/apps/account-ui/vite.config.ts +++ b/js/apps/account-ui/vite.config.ts @@ -16,6 +16,7 @@ export default defineConfig(({ mode }) => { } const lib = env.LIB ? { + copyPublicDir: false, outDir: "lib", lib: { entry: path.resolve(__dirname, "src/index.ts"), From efc86034383b1735bfc5b0580afa69fb397d9dea Mon Sep 17 00:00:00 2001 From: Steven Hawkins Date: Tue, 2 Jul 2024 05:04:20 -0400 Subject: [PATCH 043/103] fix: addresses cli erroneously wants a secret when env password is set (#30892) (#30978) closes: #30866 Signed-off-by: Steve Hawkins (cherry picked from commit aae1fa1417bf87cb0bd7ae9699a5a94eccf55814) --- .../client/cli/common/BaseAuthOptionsCmd.java | 15 +++++++++------ .../cli/common/BaseConfigCredentialsCmd.java | 19 +++++++++++++++++-- .../testsuite/cli/admin/KcAdmTest.java | 11 +++++++++++ 3 files changed, 37 insertions(+), 8 deletions(-) diff --git a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/cli/common/BaseAuthOptionsCmd.java b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/cli/common/BaseAuthOptionsCmd.java index e2fd26374be..3b7a8bfdde7 100644 --- a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/cli/common/BaseAuthOptionsCmd.java +++ b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/cli/common/BaseAuthOptionsCmd.java @@ -63,19 +63,19 @@ public abstract class BaseAuthOptionsCmd extends BaseGlobalOptionsCmd { @Option(names = "--user", description = "Username to login with") protected String user; - @Option(names = "--password", description = "Password to login with (prompted for if not specified, --user is used, and the env variable KC_CLI_PASSWORD is not defined)", defaultValue = "${env:KC_CLI_PASSWORD}") + @Option(names = "--password", description = "Password to login with (prompted for if not specified, --user is used, and the env variable KC_CLI_PASSWORD is not defined)") protected String password; - @Option(names = "--secret", description = "Secret to authenticate the client (prompted for if no --user nor --keystore is specified, and the env variable KC_CLI_CLIENT_SECRET is not defined)", defaultValue = "${env:KC_CLI_CLIENT_SECRET}") + @Option(names = "--secret", description = "Secret to authenticate the client (prompted for if no --user nor --keystore is specified, and the env variable KC_CLI_CLIENT_SECRET is not defined)") protected String secret; @Option(names = "--keystore", description = "Path to a keystore containing private key") protected String keystore; - @Option(names = "--storepass", description = "Keystore password (prompted for if not specified, --keystore is used, and the env variable KC_CLI_STORE_PASSWORD is undefined)", defaultValue = "${env:KC_CLI_STORE_PASSWORD}") + @Option(names = "--storepass", description = "Keystore password (prompted for if not specified, --keystore is used, and the env variable KC_CLI_STORE_PASSWORD is undefined)") protected String storePass; - @Option(names = "--keypass", description = "Key password (prompted for if not specified and --keystore is used without --storepass, \n otherwise defaults to keystore password)", defaultValue = "${env:KC_CLI_KEY_PASSWORD}") + @Option(names = "--keypass", description = "Key password (prompted for if not specified, --keystore is used without --storepass, and the env variable KC_CLI_KEY_PASSWORD is undefined, otherwise defaults to keystore password)") protected String keyPass; @Option(names = "--alias", description = "Alias of the key inside a keystore (defaults to the value of ClientId)") @@ -84,7 +84,7 @@ public abstract class BaseAuthOptionsCmd extends BaseGlobalOptionsCmd { @Option(names = "--truststore", description = "Path to a truststore") protected String trustStore; - @Option(names = "--trustpass", description = "Truststore password (prompted for if not specified, --user is used, and the env variable KC_CLI_TRUSTSTORE_PASSWORD is not defined)", defaultValue = "${env:KC_CLI_TRUSTSTORE_PASSWORD}") + @Option(names = "--trustpass", description = "Truststore password (prompted for if not specified, --user is used, and the env variable KC_CLI_TRUSTSTORE_PASSWORD is not defined)") protected String trustPass; @Option(names = "--insecure", description = "Turns off TLS validation") @@ -174,7 +174,10 @@ protected void setupTruststore(ConfigData configData) { pass = configData.getTrustpass(); } if (pass == null) { - pass = IoUtil.readSecret("Enter truststore password: "); + pass = System.getenv("KC_CLI_TRUSTSTORE_PASSWORD"); + } + if (pass == null) { + pass = IoUtil.readSecret("Enter truststore password: "); } try { diff --git a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/cli/common/BaseConfigCredentialsCmd.java b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/cli/common/BaseConfigCredentialsCmd.java index 0fcd28e3902..dcf6f839372 100644 --- a/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/cli/common/BaseConfigCredentialsCmd.java +++ b/integration/client-cli/admin-cli/src/main/java/org/keycloak/client/cli/common/BaseConfigCredentialsCmd.java @@ -103,6 +103,9 @@ public void process() { printErr("Logging into " + server + " as user " + user + " of realm " + realm); // if user was set there needs to be a password so we can authenticate + if (password == null) { + password = System.getenv("KC_CLI_PASSWORD"); + } if (password == null) { password = readSecret("Enter password: "); } @@ -114,7 +117,10 @@ public void process() { grantTypeForAuthentication = OAuth2Constants.CLIENT_CREDENTIALS; printErr("Logging into " + server + " as " + "service-account-" + clientId + " of realm " + realm); if (keystore == null && secret == null) { - secret = readSecret("Enter client secret: "); + secret = System.getenv("KC_CLI_CLIENT_SECRET"); + if (secret == null) { + secret = readSecret("Enter client secret: "); + } } } @@ -127,9 +133,18 @@ public void process() { throw new RuntimeException("No such keystore file: " + keystore); } + if (storePass == null) { + storePass = System.getenv("KC_CLI_STORE_PASSWORD"); + } + if (keyPass == null) { + keyPass = System.getenv("KC_CLI_KEY_PASSWORD"); + } + if (storePass == null) { storePass = readSecret("Enter keystore password: "); - keyPass = readSecret("Enter key password: "); + if (keyPass == null) { + keyPass = readSecret("Enter key password: "); + } } if (keyPass == null) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmTest.java index 17a8d3e58c3..353c326850c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/cli/admin/KcAdmTest.java @@ -672,5 +672,16 @@ public void testCompressedCsv() { // should contain an error message assertExitCodeAndStreamSizes(exec, 0, 0, 1); } + + @Test + public void testEnvPasswordWithRegularCommand() { + execute("config credentials --server " + serverUrl + " --realm master --user admin --password admin"); + KcAdmExec exec = KcAdmExec.newBuilder() + .argsLine("get users --format csv") + .env("KC_CLI_PASSWORD=ignoreme") + .execute(); + // should not contain an error message + assertExitCodeAndStreamSizes(exec, 0, 1, 0); + } } From c81913ba2d47f52d2b678cca3a48e066b86ceb4d Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Tue, 2 Jul 2024 10:14:42 +0100 Subject: [PATCH 044/103] Backport to Fix sub-flow name/ description editing (#30990) Signed-off-by: Agnieszka Gancarczyk Co-authored-by: Agnieszka Gancarczyk --- js/apps/admin-ui/src/authentication/components/EditFlow.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/apps/admin-ui/src/authentication/components/EditFlow.tsx b/js/apps/admin-ui/src/authentication/components/EditFlow.tsx index b13412073d2..cb976a5f827 100644 --- a/js/apps/admin-ui/src/authentication/components/EditFlow.tsx +++ b/js/apps/admin-ui/src/authentication/components/EditFlow.tsx @@ -82,7 +82,7 @@ export const EditFlow = ({ execution, onRowChange }: EditFlowProps) => { From d9f64d829469c3b892b78afab2212f555fe5dbe7 Mon Sep 17 00:00:00 2001 From: Erik Jan de Wit Date: Tue, 2 Jul 2024 16:02:16 +0200 Subject: [PATCH 045/103] changed to use adminUrl instead (#30441) (#30997) * changed to use adminUrl instead fixes: #19070 Signed-off-by: Erik Jan de Wit * changed to make use of "frondend url" and "adminUrl" Signed-off-by: Erik Jan de Wit --------- Signed-off-by: Erik Jan de Wit (cherry picked from commit e3649eb86a4487771f06a02b0cd486272732e937) --- .../admin-ui/src/clients/ClientsSection.tsx | 6 ++- js/apps/admin-ui/src/utils/client-url.test.ts | 50 +++++++++++-------- js/apps/admin-ui/src/utils/client-url.ts | 17 +++---- 3 files changed, 42 insertions(+), 31 deletions(-) diff --git a/js/apps/admin-ui/src/clients/ClientsSection.tsx b/js/apps/admin-ui/src/clients/ClientsSection.tsx index 870963e7f51..66cb41d9b4e 100644 --- a/js/apps/admin-ui/src/clients/ClientsSection.tsx +++ b/js/apps/admin-ui/src/clients/ClientsSection.tsx @@ -1,5 +1,6 @@ import type ClientRepresentation from "@keycloak/keycloak-admin-client/lib/defs/clientRepresentation"; import type { ClientQuery } from "@keycloak/keycloak-admin-client/lib/resources/clients"; +import { useEnvironment } from "@keycloak/keycloak-ui-shared"; import { AlertVariant, Badge, @@ -29,6 +30,7 @@ import { import { ViewHeader } from "../components/view-header/ViewHeader"; import { useAccess } from "../context/access/Access"; import { useRealm } from "../context/realm-context/RealmContext"; +import { Environment } from "../environment"; import helpUrls from "../help-urls"; import { emptyFormatter, exportClient } from "../util"; import { convertClientToUrl } from "../utils/client-url"; @@ -73,8 +75,8 @@ const ClientDescription = (client: ClientRepresentation) => ( ); const ClientHomeLink = (client: ClientRepresentation) => { - const { adminClient } = useAdminClient(); - const href = convertClientToUrl(client, adminClient.baseUrl); + const { environment } = useEnvironment(); + const href = convertClientToUrl(client, environment); if (!href) { return "—"; diff --git a/js/apps/admin-ui/src/utils/client-url.test.ts b/js/apps/admin-ui/src/utils/client-url.test.ts index 3ebad7aa50c..e5268047b0d 100644 --- a/js/apps/admin-ui/src/utils/client-url.test.ts +++ b/js/apps/admin-ui/src/utils/client-url.test.ts @@ -7,7 +7,8 @@ describe("convertClientToUrl", () => { const baseUrl = "http://something"; //when - const result = convertClientToUrl({ baseUrl }, ""); + //@ts-ignore + const result = convertClientToUrl({ baseUrl }, { serverBaseUrl: "" }); //then expect(result).toBe(baseUrl); @@ -16,13 +17,17 @@ describe("convertClientToUrl", () => { it("when root url constrains ${authAdminUrl}", () => { //given const rootUrl = "${authAdminUrl}"; - const baseUrl = "/else"; + const adminUrl = "/else"; //when - const result = convertClientToUrl({ rootUrl, baseUrl }, "/admin"); + const result = convertClientToUrl( + { rootUrl, adminUrl }, + //@ts-ignore + { adminBaseUrl: "/admin" }, + ); //then - expect(result).toBe("/admin/else"); + expect(result).toBe("/admin"); }); it("when root url constrains ${authBaseUrl}", () => { @@ -31,10 +36,14 @@ describe("convertClientToUrl", () => { const baseUrl = "/something"; //when - const result = convertClientToUrl({ rootUrl, baseUrl }, "/admin"); + const result = convertClientToUrl( + { rootUrl, baseUrl }, + //@ts-ignore + { serverBaseUrl: "/admin" }, + ); //then - expect(result).toBe("/admin/something"); + expect(result).toBe("/admin"); }); it("when baseUrl when rootUrl is not set", () => { @@ -42,7 +51,11 @@ describe("convertClientToUrl", () => { const baseUrl = "/another"; //when - const result = convertClientToUrl({ rootUrl: undefined, baseUrl }, ""); + const result = convertClientToUrl( + { rootUrl: undefined, baseUrl }, + //@ts-ignore + { serverBaseUrl: "" }, + ); //then expect(result).toBe("/another"); @@ -54,7 +67,11 @@ describe("convertClientToUrl", () => { const rootUrl = "http://test.nl"; //when - const result = convertClientToUrl({ rootUrl, baseUrl }, ""); + const result = convertClientToUrl( + { rootUrl, baseUrl }, + //@ts-ignore + { serverBaseUrl: "" }, + ); //then expect(result).toBe("http://test.nl/another"); @@ -65,20 +82,13 @@ describe("convertClientToUrl", () => { const rootUrl = "http://test.nl"; //when - const result = convertClientToUrl({ rootUrl, baseUrl: undefined }, ""); + const result = convertClientToUrl( + { rootUrl, baseUrl: undefined }, + //@ts-ignore + { serverBaseUrl: "" }, + ); //then expect(result).toBe("http://test.nl"); }); - - it("should it return ${authBaseUrl} when baseUrl is not set?", () => { - //given - const rootUrl = "${authBaseUrl}"; - - //when - const result = convertClientToUrl({ rootUrl, baseUrl: undefined }, ""); - - //then - expect(result).toBeUndefined(); - }); }); diff --git a/js/apps/admin-ui/src/utils/client-url.ts b/js/apps/admin-ui/src/utils/client-url.ts index 331b32f4b8a..ce5d23a7f20 100644 --- a/js/apps/admin-ui/src/utils/client-url.ts +++ b/js/apps/admin-ui/src/utils/client-url.ts @@ -1,23 +1,22 @@ import ClientRepresentation from "@keycloak/keycloak-admin-client/lib/defs/clientRepresentation"; +import type { Environment } from "../environment"; import { joinPath } from "./joinPath"; export const convertClientToUrl = ( { rootUrl, baseUrl }: ClientRepresentation, - adminClientBaseUrl: string, + environment: Environment, ) => { // absolute base url configured, use base url is if (baseUrl?.startsWith("http")) { return baseUrl; } - if ( - (rootUrl === "${authBaseUrl}" || rootUrl === "${authAdminUrl}") && - baseUrl - ) { - return rootUrl.replace( - /\$\{(authAdminUrl|authBaseUrl)\}/, - joinPath(adminClientBaseUrl, baseUrl), - ); + if (rootUrl === "${authAdminUrl}") { + return rootUrl.replace(/\$\{(authAdminUrl)\}/, environment.adminBaseUrl); + } + + if (rootUrl === "${authBaseUrl}") { + return rootUrl.replace(/\$\{(authBaseUrl)\}/, environment.serverBaseUrl); } if (rootUrl?.startsWith("http")) { From 7c22802a1bc530557bd2d2f8999e28c61610b3bb Mon Sep 17 00:00:00 2001 From: Diego Garcia Lozano Date: Thu, 4 Jul 2024 11:54:32 +0200 Subject: [PATCH 046/103] Update caching docs to match breaking changes in v25 In the latest Keycloak version (v25.0.1) the cache options are not build options anymore. They now have to be provided during runtime. Closes #31050 Signed-off-by: Diego Garcia Lozano --- docs/guides/server/caching.adoc | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/guides/server/caching.adoc b/docs/guides/server/caching.adoc index 442f6f1235e..297fb032c46 100644 --- a/docs/guides/server/caching.adoc +++ b/docs/guides/server/caching.adoc @@ -18,7 +18,7 @@ By default, caches are using a UDP transport stack so that nodes are discovered To explicitly enable distributed infinispan caching, enter this command: -<@kc.build parameters="--cache=ispn"/> +<@kc.start parameters="--cache=ispn"/> When you start {project_name} in development mode, by using the `start-dev` command, {project_name} uses only local caches and distributed caches are completely disabled by implicitly setting the `--cache=local` option. The `local` cache mode is intended only for development and testing purposes. @@ -176,7 +176,7 @@ to change the number of owners accordingly to better fit into your availability To specify your own cache configuration file, enter this command: -<@kc.build parameters="--cache-config-file=my-cache-file.xml"/> +<@kc.start parameters="--cache-config-file=my-cache-file.xml"/> The configuration file is relative to the `conf/` directory. @@ -204,7 +204,7 @@ Transport stacks ensure that distributed cache nodes in a cluster communicate in To apply a specific cache stack, enter this command: -<@kc.build parameters="--cache-stack="/> +<@kc.start parameters="--cache-stack="/> The default stack is set to `udp` when distributed caches are enabled. @@ -220,7 +220,7 @@ The following table shows transport stacks that are available without any furthe |udp|UDP|UDP multicast |=== -The following table shows transport stacks that are available using the `--cache-stack` build option and a minimum configuration: +The following table shows transport stacks that are available using the `--cache-stack` runtime option and a minimum configuration: [%autowidth] |=== @@ -249,7 +249,7 @@ For more information and links to repositories with these dependencies, see the To provide the dependencies to {project_name}, put the respective JAR in the `providers` directory and build {project_name} by entering this command: -<@kc.build parameters="--cache-stack="/> +<@kc.start parameters="--cache-stack="/> === Custom transport stacks If none of the available transport stacks are enough for your deployment, you are able to change your cache configuration file From e41db1cb1f2d26811e92d52e264134c6ab7efccf Mon Sep 17 00:00:00 2001 From: Lucy Linder Date: Sun, 7 Jul 2024 12:03:23 +0200 Subject: [PATCH 047/103] Fix ReCAPTCHA Enterprise failing due to new properties in response The assessment response added a new field called accountDefenderAssessment. This commit adds the new property, and also ensures new properties won't be problematic next time by ignoring unknown properties on the top level object. Closes: #30917 Signed-off-by: Lucy Linder --- .../forms/RecaptchaAssessmentResponse.java | 37 ++++++++++++++++++- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/services/src/main/java/org/keycloak/authentication/forms/RecaptchaAssessmentResponse.java b/services/src/main/java/org/keycloak/authentication/forms/RecaptchaAssessmentResponse.java index e50dd24376d..9f801d64e7f 100644 --- a/services/src/main/java/org/keycloak/authentication/forms/RecaptchaAssessmentResponse.java +++ b/services/src/main/java/org/keycloak/authentication/forms/RecaptchaAssessmentResponse.java @@ -24,6 +24,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +@JsonIgnoreProperties(ignoreUnknown = true) public class RecaptchaAssessmentResponse { @JsonProperty("name") @@ -38,9 +39,14 @@ public class RecaptchaAssessmentResponse { @JsonProperty("event") private Event event; + @JsonProperty("accountDefenderAssessment") + private AccountDefenderAssessment accountDefenderAssessment; + public String toString() { - return format("RecaptchaAssessmentResponse(name=%s, riskAnalysis=%s, tokenProperties=%s, event=%s)", - this.getName(), this.getRiskAnalysis(), this.getTokenProperties(), this.getEvent()); + return format( + "RecaptchaAssessmentResponse(name=%s, riskAnalysis=%s, tokenProperties=%s, event=%s, accountDefenderAssessment=%s)", + this.getName(), this.getRiskAnalysis(), this.getTokenProperties(), this.getEvent(), + this.getAccountDefenderAssessment()); } public String getName() { @@ -75,6 +81,14 @@ public void setEvent(Event event) { this.event = event; } + public AccountDefenderAssessment getAccountDefenderAssessment() { + return accountDefenderAssessment; + } + + public void setAccountDefenderAssessment(AccountDefenderAssessment accountDefenderAssessment) { + this.accountDefenderAssessment = accountDefenderAssessment; + } + @JsonIgnoreProperties(ignoreUnknown = true) public static class RiskAnalysis { @JsonProperty("score") @@ -241,7 +255,26 @@ public String getUserIpAddress() { public void setUserIpAddress(String userIpAddress) { this.userIpAddress = userIpAddress; } + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static class AccountDefenderAssessment { + @JsonProperty("labels") + private String[] labels; + + public String toString() { + return format("AccountDefenderAssessment(labels=%s)", + this.getLabels() != null ? Arrays.toString(this.getLabels()) : "[]"); + } + + public String[] getLabels() { + return labels; + } + + public void setLabels(String[] labels) { + this.labels = labels; + } } } From b2b845d9f8742bdc15facf4539b15523b0b7f6d2 Mon Sep 17 00:00:00 2001 From: Sascha Marcel Schmidt Date: Fri, 21 Jun 2024 15:44:54 +0200 Subject: [PATCH 048/103] fix(operator): Scale statefulset to 0 to prepare for update (#30450) When performing a keycloak update, the operator is supposed to make sure that potential database migrations are run with only one pod active. This change makes the operator scale down the stateful set to zero pods in preparation for the update. The next reconciliation loop will scale the stateful set back up and change the image, making sure migrations are being run on the first pod that is brought up. This also makes sure that the rollover works even if the infinispan versions are incompatible. (ref: #30449) Signed-off-by: Schmidt, Sascha (sasschmidt) (cherry picked from commit 13ef6fb1c8564aa22003cf4d1507d982f63e2f5f) --- .../controllers/KeycloakDeploymentDependentResource.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/operator/src/main/java/org/keycloak/operator/controllers/KeycloakDeploymentDependentResource.java b/operator/src/main/java/org/keycloak/operator/controllers/KeycloakDeploymentDependentResource.java index 0afaadb7545..1987ee14125 100644 --- a/operator/src/main/java/org/keycloak/operator/controllers/KeycloakDeploymentDependentResource.java +++ b/operator/src/main/java/org/keycloak/operator/controllers/KeycloakDeploymentDependentResource.java @@ -461,13 +461,13 @@ public void migrateDeployment(StatefulSet previousDeployment, StatefulSet reconc var reconciledContainer = reconciledDeployment.getSpec().getTemplate().getSpec().getContainers().get(0); if (!previousContainer.getImage().equals(reconciledContainer.getImage()) - && previousDeployment.getStatus().getReplicas() > 1) { + && previousDeployment.getStatus().getReplicas() > 0) { // TODO Check if migration is really needed (e.g. based on actual KC version); https://github.com/keycloak/keycloak/issues/10441 Log.info("Detected changed Keycloak image, assuming Keycloak upgrade. Scaling down the deployment to one instance to perform a safe database migration"); Log.infof("original image: %s; new image: %s", previousContainer.getImage(), reconciledContainer.getImage()); reconciledContainer.setImage(previousContainer.getImage()); - reconciledDeployment.getSpec().setReplicas(1); + reconciledDeployment.getSpec().setReplicas(0); reconciledDeployment.getMetadata().getAnnotations().put(Constants.KEYCLOAK_MIGRATING_ANNOTATION, Boolean.TRUE.toString()); } From f161b4e021e3dc83e3f2040fa37a9aa2e12780f1 Mon Sep 17 00:00:00 2001 From: Johannes Knutsen Date: Tue, 9 Jul 2024 20:31:16 +0200 Subject: [PATCH 049/103] Add @JsonIgnore to SingleUseObjectKeyModel's getExpiration() Closes #31171 Signed-off-by: Johannes Knutsen --- .../main/java/org/keycloak/models/SingleUseObjectKeyModel.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server-spi/src/main/java/org/keycloak/models/SingleUseObjectKeyModel.java b/server-spi/src/main/java/org/keycloak/models/SingleUseObjectKeyModel.java index 1e7d3532b17..ef5e5b48d88 100644 --- a/server-spi/src/main/java/org/keycloak/models/SingleUseObjectKeyModel.java +++ b/server-spi/src/main/java/org/keycloak/models/SingleUseObjectKeyModel.java @@ -16,6 +16,7 @@ */ package org.keycloak.models; +import com.fasterxml.jackson.annotation.JsonIgnore; import org.keycloak.common.util.Base64; import java.nio.charset.StandardCharsets; import java.util.UUID; @@ -45,6 +46,7 @@ public interface SingleUseObjectKeyModel { * @deprecated int will overflow with values after 2038. Use {@link #getExp()} instead. */ @Deprecated + @JsonIgnore default int getExpiration() { return getExp().intValue(); } From 3a05abcfaabe787231e4fb6c5f96ee8d1975411d Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Wed, 10 Jul 2024 14:24:51 +0100 Subject: [PATCH 050/103] Backport to fix input type and help text for IDP SAML Certificate (#31194) Signed-off-by: Agnieszka Gancarczyk Co-authored-by: Agnieszka Gancarczyk --- .../theme/keycloak.v2/admin/messages/messages_en.properties | 3 ++- .../src/identity-providers/add/DescriptorSettings.tsx | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties index 21c1f40bb11..bb0a6c7f30a 100644 --- a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties +++ b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties @@ -3201,4 +3201,5 @@ redirectWhenEmailMatchesHelp=Automatically redirect the user to this identity pr emailVerificationHelp=Specifies independent timeout for email verification. idpAccountEmailVerificationHelp=Specifies independent timeout for IdP account email verification. forgotPasswordHelp=Specifies independent timeout for forgot password. -executeActionsHelp=Specifies independent timeout for execute actions. \ No newline at end of file +executeActionsHelp=Specifies independent timeout for execute actions. +validatingX509CertsHelp=The public certificates Keycloak uses to validate the signatures of SAML requests and responses from the external IDP when Use metadata descriptor URL is OFF. Multiple certificates can be entered separated by comma (,). The certificates can be re-imported from the Metadata descriptor URL clicking the Import Keys action in the identity provider page. The action downloads the current certificates in the metadata endpoint and assigns them to the config in this same option. You need to click Save to definitely store the re-imported certificates. \ No newline at end of file diff --git a/js/apps/admin-ui/src/identity-providers/add/DescriptorSettings.tsx b/js/apps/admin-ui/src/identity-providers/add/DescriptorSettings.tsx index e4ab8951ecd..d8d3a6f7cac 100644 --- a/js/apps/admin-ui/src/identity-providers/add/DescriptorSettings.tsx +++ b/js/apps/admin-ui/src/identity-providers/add/DescriptorSettings.tsx @@ -6,6 +6,7 @@ import { useTranslation } from "react-i18next"; import { NumberControl, SelectControl, + TextAreaControl, TextControl, } from "@keycloak/keycloak-ui-shared"; import { DefaultSwitchControl } from "../../components/SwitchControl"; @@ -284,9 +285,10 @@ const Fields = ({ readOnly }: DescriptorSettingsProps) => { isDisabled={readOnly} /> {useMetadataDescriptorUrl !== "true" && ( - )} From 31f475d7a7b9f221acf6ce4bc1af078b9d80c4d2 Mon Sep 17 00:00:00 2001 From: rmartinc Date: Wed, 3 Jul 2024 18:20:17 +0200 Subject: [PATCH 051/103] Improve consent deletion when a realm is removed Closes #30992 Signed-off-by: rmartinc (cherry picked from commit ce195b81f82e21c97616431cd6fb0e3b05b4e729) --- .../topics/changes/changes-25_0_2.adoc | 5 +++ .../upgrading/topics/changes/changes.adoc | 4 +++ .../connections/jpa/util/JpaUtils.java | 13 +++----- .../PersistentClientSessionEntity.java | 13 +++----- .../META-INF/jpa-changelog-18.0.15.xml | 31 +++++++++++++++++++ .../META-INF/jpa-changelog-master.xml | 1 + .../META-INF/queries-default.properties | 22 ------------- .../META-INF/queries-mariadb.properties | 8 +++++ .../META-INF/queries-mysql.properties | 8 +++++ 9 files changed, 66 insertions(+), 39 deletions(-) create mode 100644 docs/documentation/upgrading/topics/changes/changes-25_0_2.adoc create mode 100644 model/jpa/src/main/resources/META-INF/jpa-changelog-18.0.15.xml delete mode 100644 model/jpa/src/main/resources/META-INF/queries-default.properties diff --git a/docs/documentation/upgrading/topics/changes/changes-25_0_2.adoc b/docs/documentation/upgrading/topics/changes/changes-25_0_2.adoc new file mode 100644 index 00000000000..83a1fe03c27 --- /dev/null +++ b/docs/documentation/upgrading/topics/changes/changes-25_0_2.adoc @@ -0,0 +1,5 @@ += Improving performance for deletion of user consents + +When a client scope or the full realm are deleted the associated user consents should also be removed. A new index over the table `USER_CONSENT_CLIENT_SCOPE` has been added to increase the performance. + +Note that, if the table contains more than 300.000 entries, by default {project_name} skips the creation of the indexes during the automatic schema migration and logs the SQL statements to the console instead. The statements must be run manually in the DB after {project_name}'s startup. Check the link:{upgradingguide_link}[{upgradingguide_name}] for details on how to configure a different limit. diff --git a/docs/documentation/upgrading/topics/changes/changes.adoc b/docs/documentation/upgrading/topics/changes/changes.adoc index e4ac65ff958..ce165190e1f 100644 --- a/docs/documentation/upgrading/topics/changes/changes.adoc +++ b/docs/documentation/upgrading/topics/changes/changes.adoc @@ -1,6 +1,10 @@ [[migration-changes]] == Migration Changes +=== Migrating to 25.0.2 + +include::changes-25_0_2.adoc[leveloffset=3] + === Migrating to 25.0.0 include::changes-25_0_0.adoc[leveloffset=3] diff --git a/model/jpa/src/main/java/org/keycloak/connections/jpa/util/JpaUtils.java b/model/jpa/src/main/java/org/keycloak/connections/jpa/util/JpaUtils.java index 48b81eb9ae6..06246414b82 100644 --- a/model/jpa/src/main/java/org/keycloak/connections/jpa/util/JpaUtils.java +++ b/model/jpa/src/main/java/org/keycloak/connections/jpa/util/JpaUtils.java @@ -182,18 +182,15 @@ private static String getQueryShortName(String name) { */ public static Properties loadSpecificNamedQueries(String databaseType) { URL specificUrl = JpaUtils.class.getClassLoader().getResource("META-INF/queries-" + databaseType + ".properties"); - URL defaultUrl = JpaUtils.class.getClassLoader().getResource("META-INF/queries-default.properties"); - - if (defaultUrl == null) { - throw new IllegalStateException("META-INF/queries-default.properties was not found in the classpath"); - } Properties specificQueries = loadSqlProperties(specificUrl); - Properties defaultQueries = loadSqlProperties(defaultUrl); Properties queries = new Properties(); + if (specificQueries == null) { + return queries; + } - for (String queryNameFull : defaultQueries.stringPropertyNames()) { - String querySql = defaultQueries.getProperty(queryNameFull); + for (String queryNameFull : specificQueries.stringPropertyNames()) { + String querySql = specificQueries.getProperty(queryNameFull); String queryName = getQueryShortName(queryNameFull); String specificQueryNameFull = getQueryFromProperties(queryName, specificQueries); diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentClientSessionEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentClientSessionEntity.java index 9bb1ee75f0a..265aa0391c6 100644 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentClientSessionEntity.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentClientSessionEntity.java @@ -32,19 +32,14 @@ * @author Marek Posolda */ @NamedQueries({ - // sub-query with deletion performs very slow in MySQL/MariaDB databases - // It is removed from here and added manually in JpaUtils to give a native implementation if needed - // @NamedQuery(name="deleteClientSessionsByRealm", query="delete from PersistentClientSessionEntity sess where sess.userSessionId IN (select u.userSessionId from PersistentUserSessionEntity u where u.realmId = :realmId)"), + @NamedQuery(name="deleteClientSessionsByRealm", query="delete from PersistentClientSessionEntity sess where sess.userSessionId IN (select u.userSessionId from PersistentUserSessionEntity u where u.realmId = :realmId)"), @NamedQuery(name="deleteClientSessionsByClient", query="delete from PersistentClientSessionEntity sess where sess.clientId = :clientId"), @NamedQuery(name="deleteClientSessionsByExternalClient", query="delete from PersistentClientSessionEntity sess where sess.clientStorageProvider = :clientStorageProvider and sess.externalClientId = :externalClientId"), @NamedQuery(name="deleteClientSessionsByClientStorageProvider", query="delete from PersistentClientSessionEntity sess where sess.clientStorageProvider = :clientStorageProvider"), - // sub-query with deletion performs very slow in MySQL/MariaDB databases - // It is removed from here and added manually in JpaUtils to give a native implementation if needed - // @NamedQuery(name="deleteClientSessionsByUser", query="delete from PersistentClientSessionEntity sess where sess.userSessionId IN (select u.userSessionId from PersistentUserSessionEntity u where u.userId = :userId)"), + @NamedQuery(name="deleteClientSessionsByUser", query="delete from PersistentClientSessionEntity sess where sess.userSessionId IN (select u.userSessionId from PersistentUserSessionEntity u where u.userId = :userId)"), @NamedQuery(name="deleteClientSessionsByUserSession", query="delete from PersistentClientSessionEntity sess where sess.userSessionId = :userSessionId and sess.offline = :offline"), - // KEYCLOAK-18842: The deleteExpiredClientSessions performs very slow in MySQL/MariaDB databases - // It is removed from here and added manually in JpaUtils to give a native implementation if needed - //@NamedQuery(name="deleteExpiredClientSessions", query="delete from PersistentClientSessionEntity sess where sess.userSessionId IN (select u.userSessionId from PersistentUserSessionEntity u where u.realmId = :realmId AND u.offline = :offline AND u.lastSessionRefresh < :lastSessionRefresh)"), + @NamedQuery(name="deleteExpiredClientSessions", query="delete from PersistentClientSessionEntity sess where sess.offline = :offline AND sess.userSessionId IN (select u.userSessionId from PersistentUserSessionEntity u where u.realmId = :realmId AND u.offline = :offline AND u.lastSessionRefresh < :lastSessionRefresh)"), + @NamedQuery(name="deleteClientSessionsByRealmSessionType", query="delete from PersistentClientSessionEntity sess where sess.offline = :offline AND sess.userSessionId IN (select u.userSessionId from PersistentUserSessionEntity u where u.realmId = :realmId and u.offline = :offline)"), @NamedQuery(name="findClientSessionsByUserSession", query="select sess from PersistentClientSessionEntity sess where sess.userSessionId=:userSessionId and sess.offline = :offline"), @NamedQuery(name="findClientSessionsOrderedByIdInterval", query="select sess from PersistentClientSessionEntity sess where sess.offline = :offline and sess.userSessionId >= :fromSessionId and sess.userSessionId <= :toSessionId order by sess.userSessionId"), @NamedQuery(name="findClientSessionsOrderedByIdExact", query="select sess from PersistentClientSessionEntity sess where sess.offline = :offline and sess.userSessionId IN (:userSessionIds)"), diff --git a/model/jpa/src/main/resources/META-INF/jpa-changelog-18.0.15.xml b/model/jpa/src/main/resources/META-INF/jpa-changelog-18.0.15.xml new file mode 100644 index 00000000000..aabf2554af8 --- /dev/null +++ b/model/jpa/src/main/resources/META-INF/jpa-changelog-18.0.15.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + diff --git a/model/jpa/src/main/resources/META-INF/jpa-changelog-master.xml b/model/jpa/src/main/resources/META-INF/jpa-changelog-master.xml index b4998f0bbd7..fd2eafdc3f6 100755 --- a/model/jpa/src/main/resources/META-INF/jpa-changelog-master.xml +++ b/model/jpa/src/main/resources/META-INF/jpa-changelog-master.xml @@ -73,6 +73,7 @@ + diff --git a/model/jpa/src/main/resources/META-INF/queries-default.properties b/model/jpa/src/main/resources/META-INF/queries-default.properties deleted file mode 100644 index 749eb034cbd..00000000000 --- a/model/jpa/src/main/resources/META-INF/queries-default.properties +++ /dev/null @@ -1,22 +0,0 @@ -# properties file to define all default queries that are loaded separately -# in a properties file. These queries can be overloaded with a -# specific file for each database type. Queries are defined in the form: -# name[type]=sql -# type can be native (for native queries) or jpql (jpql syntax) -# if no type is defined jpql is the default - -deleteExpiredClientSessions=delete from PersistentClientSessionEntity sess where sess.offline = :offline AND sess.userSessionId IN (\ - select u.userSessionId from PersistentUserSessionEntity u \ - where u.realmId = :realmId AND u.offline = :offline AND u.lastSessionRefresh < :lastSessionRefresh) - -deleteClientSessionsByRealm=delete from PersistentClientSessionEntity sess where sess.userSessionId IN (\ - select u.userSessionId from PersistentUserSessionEntity u \ - where u.realmId = :realmId) - -deleteClientSessionsByRealmSessionType=delete from PersistentClientSessionEntity sess where sess.offline = :offline AND sess.userSessionId IN (\ - select u.userSessionId from PersistentUserSessionEntity u \ - where u.realmId = :realmId and u.offline = :offline) - -deleteClientSessionsByUser=delete from PersistentClientSessionEntity sess where sess.userSessionId IN (\ - select u.userSessionId from PersistentUserSessionEntity u \ - where u.userId = :userId) diff --git a/model/jpa/src/main/resources/META-INF/queries-mariadb.properties b/model/jpa/src/main/resources/META-INF/queries-mariadb.properties index b2422319da9..cf8e05c460f 100644 --- a/model/jpa/src/main/resources/META-INF/queries-mariadb.properties +++ b/model/jpa/src/main/resources/META-INF/queries-mariadb.properties @@ -16,3 +16,11 @@ deleteClientSessionsByRealmSessionType[native]=delete c from OFFLINE_CLIENT_SESS deleteClientSessionsByUser[native]=delete c from OFFLINE_CLIENT_SESSION c join OFFLINE_USER_SESSION u \ where c.USER_SESSION_ID = u.USER_SESSION_ID and u.USER_ID = :userId + +deleteUserConsentClientScopesByRealm[native]=delete cc from USER_CONSENT_CLIENT_SCOPE cc join USER_CONSENT uc join USER_ENTITY u \ + where cc.USER_CONSENT_ID = uc.ID and uc.USER_ID = u.ID and u.REALM_ID=:realmId + +deleteUserConsentsByRealm[native]=delete uc from USER_CONSENT uc join USER_ENTITY u where uc.USER_ID = u.ID and u.REALM_ID = :realmId + +deleteUserConsentClientScopesByClient[native]=delete cc from USER_CONSENT_CLIENT_SCOPE cc join USER_CONSENT uc \ + where cc.USER_CONSENT_ID = uc.ID and uc.CLIENT_ID = :clientId diff --git a/model/jpa/src/main/resources/META-INF/queries-mysql.properties b/model/jpa/src/main/resources/META-INF/queries-mysql.properties index b2422319da9..cf8e05c460f 100644 --- a/model/jpa/src/main/resources/META-INF/queries-mysql.properties +++ b/model/jpa/src/main/resources/META-INF/queries-mysql.properties @@ -16,3 +16,11 @@ deleteClientSessionsByRealmSessionType[native]=delete c from OFFLINE_CLIENT_SESS deleteClientSessionsByUser[native]=delete c from OFFLINE_CLIENT_SESSION c join OFFLINE_USER_SESSION u \ where c.USER_SESSION_ID = u.USER_SESSION_ID and u.USER_ID = :userId + +deleteUserConsentClientScopesByRealm[native]=delete cc from USER_CONSENT_CLIENT_SCOPE cc join USER_CONSENT uc join USER_ENTITY u \ + where cc.USER_CONSENT_ID = uc.ID and uc.USER_ID = u.ID and u.REALM_ID=:realmId + +deleteUserConsentsByRealm[native]=delete uc from USER_CONSENT uc join USER_ENTITY u where uc.USER_ID = u.ID and u.REALM_ID = :realmId + +deleteUserConsentClientScopesByClient[native]=delete cc from USER_CONSENT_CLIENT_SCOPE cc join USER_CONSENT uc \ + where cc.USER_CONSENT_ID = uc.ID and uc.CLIENT_ID = :clientId From 7c9ffe0c41d97a6165ca2d983f05f4172111a71c Mon Sep 17 00:00:00 2001 From: Pedro Igor Date: Mon, 8 Jul 2024 08:58:02 -0300 Subject: [PATCH 052/103] Testing ldap connection should not process or bind the credentials (#31081) Closes #30821 Signed-off-by: Pedro Igor --- .../managers/LDAPServerCapabilitiesManager.java | 2 +- .../admin/UserFederationLdapConnectionTest.java | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java b/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java index e43da438764..66a3777828d 100755 --- a/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java +++ b/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java @@ -67,7 +67,7 @@ private static int parseConnectionTimeout(String connectionTimeout) { public static LDAPConfig buildLDAPConfig(TestLdapConnectionRepresentation config, RealmModel realm) { String bindCredential = config.getBindCredential(); - if (config.getComponentId() != null && !LDAPConstants.AUTH_TYPE.equals(LDAPConstants.AUTH_TYPE_NONE) + if (config.getComponentId() != null && !LDAPConstants.AUTH_TYPE_NONE.equals(config.getAuthType()) && ComponentRepresentation.SECRET_VALUE.equals(bindCredential)) { // check the connection URL and the bind DN are the same to allow using the same configured password ComponentModel component = realm.getComponent(config.getComponentId()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserFederationLdapConnectionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserFederationLdapConnectionTest.java index 37f9462523a..ecc4382fd33 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserFederationLdapConnectionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserFederationLdapConnectionTest.java @@ -48,7 +48,7 @@ public class UserFederationLdapConnectionTest extends AbstractAdminTest { public static LDAPRule ldapRule = new LDAPRule(); @Test - public void testLdapConnections1() { + public void testLdapConnections() { // Unknown action Response response = realm.testLDAPConnection(new TestLdapConnectionRepresentation("unknown", "ldap://localhost:10389", "foo", "bar", "false", null)); assertStatus(response, 400); @@ -61,6 +61,14 @@ public void testLdapConnections1() { response = realm.testLDAPConnection(new TestLdapConnectionRepresentation(LDAPServerCapabilitiesManager.TEST_CONNECTION, "ldap://localhost:10389", null, null, "false", null, "false", LDAPConstants.AUTH_TYPE_NONE)); assertStatus(response, 204); + // Connection success with invalid credentials + String ldapModelId = testingClient.testing().ldap(REALM_NAME).createLDAPProvider(ldapRule.getConfig(), false); + getCleanup().addCleanup(() -> { + adminClient.realm(REALM_NAME).components().removeComponent(ldapModelId);; + }); + response = realm.testLDAPConnection(new TestLdapConnectionRepresentation(LDAPServerCapabilitiesManager.TEST_CONNECTION, "ldap://localhost:10389", "invalid-db", ComponentRepresentation.SECRET_VALUE, "false", null, "false", LDAPConstants.AUTH_TYPE_SIMPLE, ldapModelId)); + assertStatus(response, 204); + // Bad authentication response = realm.testLDAPConnection(new TestLdapConnectionRepresentation(LDAPServerCapabilitiesManager.TEST_AUTHENTICATION, "ldap://localhost:10389", "foo", "bar", "false", "10000")); assertStatus(response, 400); From 6783b97c93dc9cc1ac0f442f9830c694fab26d63 Mon Sep 17 00:00:00 2001 From: Lucy Linder Date: Wed, 10 Jul 2024 20:23:02 +0200 Subject: [PATCH 053/103] Update links in ReCAPTCHA doc Google links changed and are now causing redirect issues reports. Closes: #31187 Signed-off-by: Lucy Linder --- .../server_admin/topics/users/proc-enabling-recaptcha.adoc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/documentation/server_admin/topics/users/proc-enabling-recaptcha.adoc b/docs/documentation/server_admin/topics/users/proc-enabling-recaptcha.adoc index 3334f3582de..fd0fac0a338 100644 --- a/docs/documentation/server_admin/topics/users/proc-enabling-recaptcha.adoc +++ b/docs/documentation/server_admin/topics/users/proc-enabling-recaptcha.adoc @@ -7,7 +7,7 @@ [role="_abstract"] To safeguard registration against bots, {project_name} has integration with Google reCAPTCHA (see <>) and reCAPTCHA Enterprise (see <>). -The default theme (`register.ftl`) supports both v2 (visible, checkbox-based) and v3 (score-based, invisible) reCAPTCHA (see https://cloud.google.com/recaptcha-enterprise/docs/choose-key-type[Choose the appropriate reCAPTCHA key type]). +The default theme (`register.ftl`) supports both v2 (visible, checkbox-based) and v3 (score-based, invisible) reCAPTCHA (see https://cloud.google.com/recaptcha/docs/choose-key-type[Choose the appropriate reCAPTCHA key type]). [[procedure_recaptcha]] == Setting up Google reCAPTCHA @@ -85,7 +85,7 @@ image:images/recaptcha-enterprise-config.png[] .. Enter the *Recaptcha Site Key* generated at the beginning of the procedure. .. Enter the *Recaptcha API Key* generated at the beginning of the procedure. .. Toggle **reCAPTCHA v3** according to your Site Key type: on for score-based reCAPTCHA (v3), off for challenge reCAPTCHA (v2). -.. (Optional) Customize the *Min. Score Threshold* as you see fit. Set it to the minimum score, between 0.0 and 1.0, that a user should achieve on reCAPTCHA to be allowed to register. See https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment-website#interpret_scores[interpret scores]. +.. (Optional) Customize the *Min. Score Threshold* as you see fit. Set it to the minimum score, between 0.0 and 1.0, that a user should achieve on reCAPTCHA to be allowed to register. See https://cloud.google.com/recaptcha/docs/interpret-assessment-website#interpret_scores[interpret scores]. .. (Optional) Toggle *Use recaptcha.net* to use `www.recatcha.net` instead of `www.google.com` domain for cookies. See https://developers.google.com/recaptcha/docs/faq[reCAPTCHA faq] for more information. . Authorize Google to use the registration page as an iframe. See the last steps of <> for a detailed procedure. From 9efe7e8e24397de03e435710cbb785c6994535a8 Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Thu, 11 Jul 2024 12:13:30 +0100 Subject: [PATCH 054/103] Backport to update realm when changing bind (#31212) Signed-off-by: Agnieszka Gancarczyk Co-authored-by: Agnieszka Gancarczyk --- .../admin-ui/src/authentication/AuthenticationSection.tsx | 4 +--- js/apps/admin-ui/src/authentication/BindFlowDialog.tsx | 5 ++--- js/apps/admin-ui/src/authentication/components/UsedBy.tsx | 8 ++++---- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/js/apps/admin-ui/src/authentication/AuthenticationSection.tsx b/js/apps/admin-ui/src/authentication/AuthenticationSection.tsx index 457027aad99..65e18c4b567 100644 --- a/js/apps/admin-ui/src/authentication/AuthenticationSection.tsx +++ b/js/apps/admin-ui/src/authentication/AuthenticationSection.tsx @@ -244,9 +244,7 @@ export default function AuthenticationSection() { { name: "usedBy", displayKey: "usedBy", - cellRenderer: (row) => ( - - ), + cellRenderer: (row) => , }, { name: "description", diff --git a/js/apps/admin-ui/src/authentication/BindFlowDialog.tsx b/js/apps/admin-ui/src/authentication/BindFlowDialog.tsx index 53e26d78fa2..6fdd00950bb 100644 --- a/js/apps/admin-ui/src/authentication/BindFlowDialog.tsx +++ b/js/apps/admin-ui/src/authentication/BindFlowDialog.tsx @@ -29,16 +29,15 @@ export const BindFlowDialog = ({ flowAlias, onClose }: BindFlowDialogProps) => { const { t } = useTranslation(); const form = useForm(); const { addAlert, addError } = useAlerts(); - const { realm } = useRealm(); + const { realm, realmRepresentation: realmRep, refresh } = useRealm(); const onSubmit = async ({ bindingType }: BindingForm) => { - const realmRep = await adminClient.realms.findOne({ realm }); - try { await adminClient.realms.update( { realm }, { ...realmRep, [bindingType]: flowAlias }, ); + refresh(); addAlert(t("updateFlowSuccess"), AlertVariant.success); } catch (error) { addError("updateFlowError", error); diff --git a/js/apps/admin-ui/src/authentication/components/UsedBy.tsx b/js/apps/admin-ui/src/authentication/components/UsedBy.tsx index 7e2d7b63861..2ed4c5e4258 100644 --- a/js/apps/admin-ui/src/authentication/components/UsedBy.tsx +++ b/js/apps/admin-ui/src/authentication/components/UsedBy.tsx @@ -1,4 +1,3 @@ -import RealmRepresentation from "@keycloak/keycloak-admin-client/lib/defs/realmRepresentation"; import { Button, Modal, @@ -17,10 +16,10 @@ import useToggle from "../../utils/useToggle"; import { AuthenticationType, REALM_FLOWS } from "../AuthenticationSection"; import style from "./used-by.module.css"; +import { useRealm } from "../../context/realm-context/RealmContext"; type UsedByProps = { authType: AuthenticationType; - realm: RealmRepresentation; }; const Label = ({ label }: { label: string }) => ( @@ -96,11 +95,12 @@ const UsedByModal = ({ id, isSpecificClient, onClose }: UsedByModalProps) => { ); }; -export const UsedBy = ({ authType: { id, usedBy }, realm }: UsedByProps) => { +export const UsedBy = ({ authType: { id, usedBy } }: UsedByProps) => { const { t } = useTranslation(); + const { realmRepresentation: realm } = useRealm(); const [open, toggle] = useToggle(); - const key = Object.entries(realm).find( + const key = Object.entries(realm!).find( (e) => e[1] === usedBy?.values[0], )?.[0]; From 1e3aa37bf011675e83f5dcbf08ff6e957e075079 Mon Sep 17 00:00:00 2001 From: rmartinc Date: Wed, 10 Jul 2024 17:41:54 +0200 Subject: [PATCH 055/103] Do not compare user DN using DN comparison as Ad can login via username@domain Closes #31196 Signed-off-by: rmartinc (cherry picked from commit bd90ead892b6a8ba00da747e8e870babc820a14e) --- .../services/managers/LDAPServerCapabilitiesManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java b/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java index 66a3777828d..18eb96b4b86 100755 --- a/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java +++ b/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java @@ -74,7 +74,7 @@ public static LDAPConfig buildLDAPConfig(TestLdapConnectionRepresentation config if (component != null) { LDAPConfig ldapConfig = new LDAPConfig(component.getConfig()); if (Objects.equals(URI.create(config.getConnectionUrl()), URI.create(ldapConfig.getConnectionUrl())) - && Objects.equals(LDAPDn.fromString(config.getBindDn()), LDAPDn.fromString(ldapConfig.getBindDN()))) { + && config.getBindDn() != null && config.getBindDn().equalsIgnoreCase(ldapConfig.getBindDN())) { bindCredential = ldapConfig.getBindCredential(); } } From cd50c8af04afea3b83805e7e62d9f025dc3366b0 Mon Sep 17 00:00:00 2001 From: rmartinc Date: Thu, 11 Jul 2024 15:40:22 +0200 Subject: [PATCH 056/103] Change link to https://github.com/eclipse/microprofile/wiki/JWT_Auth Closes #31219 Signed-off-by: rmartinc (cherry picked from commit e80c3fee9bd762a6ddc7b82867b6d19175a8694d) --- .../server_admin/topics/clients/con-client-scopes.adoc | 2 +- docs/documentation/upgrading/topics/changes/changes.adoc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/documentation/server_admin/topics/clients/con-client-scopes.adoc b/docs/documentation/server_admin/topics/clients/con-client-scopes.adoc index ca25d92445c..28ff3911eb0 100644 --- a/docs/documentation/server_admin/topics/clients/con-client-scopes.adoc +++ b/docs/documentation/server_admin/topics/clients/con-client-scopes.adoc @@ -29,7 +29,7 @@ This scope is also not defined in the OpenID Connect specification and not added + ** *microprofile-jwt* + -This scope handles claims defined in the https://wiki.eclipse.org/MicroProfile/JWT_Auth[MicroProfile/JWT Auth Specification]. This scope defines a user property mapper for the *upn* claim and a realm role mapper for the *groups* claim. These mappers can be changed so different properties can be used to create the MicroProfile/JWT specific claims. +This scope handles claims defined in the https://github.com/eclipse/microprofile/wiki/JWT_Auth[MicroProfile/JWT Auth Specification]. This scope defines a user property mapper for the *upn* claim and a realm role mapper for the *groups* claim. These mappers can be changed so different properties can be used to create the MicroProfile/JWT specific claims. + ** *offline_access* + diff --git a/docs/documentation/upgrading/topics/changes/changes.adoc b/docs/documentation/upgrading/topics/changes/changes.adoc index ce165190e1f..ee779657332 100644 --- a/docs/documentation/upgrading/topics/changes/changes.adoc +++ b/docs/documentation/upgrading/topics/changes/changes.adoc @@ -460,7 +460,7 @@ Cross-Datacenter Replication changes:: not guaranteed as we don't test it anymore. ==== New optional client scope -We have added a new `microprofile-jwt` optional client scope to handle the claims defined in the https://wiki.eclipse.org/MicroProfile/JWT_Auth[MicroProfile/JWT Auth Specification]. +We have added a new `microprofile-jwt` optional client scope to handle the claims defined in the https://github.com/eclipse/microprofile/wiki/JWT_Auth[MicroProfile/JWT Auth Specification]. This new client scope defines protocol mappers to set the username of the authenticated user to the `upn` claim and to set the realm roles to the `groups` claim. From 1007ecec26a3d7a04cd2d8d3dfefb40e730e0c9f Mon Sep 17 00:00:00 2001 From: mposolda Date: Fri, 12 Jul 2024 16:05:55 +0200 Subject: [PATCH 057/103] Offline tokens created in Keycloak 14 or earlier will not work on Keycloak 25 closes #31224 Signed-off-by: mposolda (cherry picked from commit 1864cf1827ddd613bc6abc643e66621308932038) --- .../org/keycloak/representations/IDToken.java | 4 +- .../representations/RefreshToken.java | 7 + .../oauth/OfflineTokenMigrationTest.java | 127 ++++++++++++++++++ 3 files changed, 136 insertions(+), 2 deletions(-) create mode 100644 testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OfflineTokenMigrationTest.java diff --git a/core/src/main/java/org/keycloak/representations/IDToken.java b/core/src/main/java/org/keycloak/representations/IDToken.java index 33c54b70ef3..8f7f25958fb 100755 --- a/core/src/main/java/org/keycloak/representations/IDToken.java +++ b/core/src/main/java/org/keycloak/representations/IDToken.java @@ -140,7 +140,7 @@ public class IDToken extends JsonWebToken { // Financial API - Part 2: Read and Write API Security Profile // http://openid.net/specs/openid-financial-api-part-2.html#authorization-server @JsonProperty(S_HASH) - protected String stateHash; + protected String stateHash; public String getNonce() { return nonce; @@ -172,7 +172,7 @@ public void setSessionId(String sessionId) { @Deprecated @JsonIgnore public String getSessionState() { - return sessionId; + return getSessionId(); } public String getAccessTokenHash() { diff --git a/core/src/main/java/org/keycloak/representations/RefreshToken.java b/core/src/main/java/org/keycloak/representations/RefreshToken.java index b7c0f77b135..2f6b5a1b75f 100755 --- a/core/src/main/java/org/keycloak/representations/RefreshToken.java +++ b/core/src/main/java/org/keycloak/representations/RefreshToken.java @@ -53,4 +53,11 @@ public RefreshToken(AccessToken token) { public TokenCategory getCategory() { return TokenCategory.INTERNAL; } + + @Override + public String getSessionId() { + String sessionId = super.getSessionId(); + // Fallback as offline tokens created in Keycloak 14 or earlier have only the "session_state" claim, but not "sid" + return sessionId != null ? sessionId : (String) getOtherClaims().get(IDToken.SESSION_STATE); + } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OfflineTokenMigrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OfflineTokenMigrationTest.java new file mode 100644 index 00000000000..93fa9f01504 --- /dev/null +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/OfflineTokenMigrationTest.java @@ -0,0 +1,127 @@ +/* + * Copyright 2024 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.keycloak.testsuite.oauth; + +import java.io.Serializable; +import java.util.Map; +import java.util.function.BiFunction; + +import org.jboss.arquillian.graphene.page.Page; +import org.junit.Assert; +import org.junit.Test; +import org.keycloak.OAuth2Constants; +import org.keycloak.crypto.SignatureProvider; +import org.keycloak.crypto.SignatureSignerContext; +import org.keycloak.jose.jws.JWSBuilder; +import org.keycloak.jose.jws.JWSInput; +import org.keycloak.models.KeycloakSession; +import org.keycloak.representations.AccessToken; +import org.keycloak.representations.IDToken; +import org.keycloak.representations.RefreshToken; +import org.keycloak.representations.idm.RealmRepresentation; +import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; +import org.keycloak.testsuite.pages.LoginPage; +import org.keycloak.testsuite.runonserver.FetchOnServer; +import org.keycloak.testsuite.runonserver.FetchOnServerWrapper; +import org.keycloak.testsuite.util.OAuthClient; +import org.keycloak.util.JsonSerialization; + +/** + * Test for simulating token refresh with the offline tokens created in older Keycloak versions. + * + * Keycloak supports refresh of the offline tokens, which were created in older Keycloak versions than current Keycloak version. But + * testing real migration is sometimes hard to achieve as it requires running of the old Keycloak server, which is sometimes not feasible. + * + * This test just simulates the refresh with the old offline-token by manually converting offline-token to the offline-token format, which was used by the specified old Keycloak version + * + * @author Marek Posolda + */ +public class OfflineTokenMigrationTest extends AbstractTestRealmKeycloakTest { + + @Page + protected LoginPage loginPage; + + @Override + public void configureTestRealm(RealmRepresentation testRealm) { + + } + + // Issue 31224 + // Test refresh with the offline-token created in Keycloak 14 works + @Test + public void testOfflineTokenMigrationFromKeycloak14() throws Exception { + OfflineTokenConverter convertOfflineTokenToKeycloak14Format = (session, oldOfflineToken) -> { + try { + RefreshToken refreshToken = session.tokens().decode(oldOfflineToken, RefreshToken.class); + String sessionId = refreshToken.getSessionId(); + String signatureAlgorithm = new JWSInput(oldOfflineToken).getHeader().getAlgorithm().toString(); + + Map asMap = JsonSerialization.readValue(JsonSerialization.writeValueAsString(refreshToken), Map.class); + asMap.remove(IDToken.SESSION_ID); + asMap.put(IDToken.SESSION_STATE, sessionId); + + SignatureProvider signatureProvider = session.getProvider(SignatureProvider.class, signatureAlgorithm); + SignatureSignerContext signer = signatureProvider.signer(); + + String type = "JWT"; + return new JWSBuilder().type(type).jsonContent(asMap).sign(signer); + } catch (Exception ioe) { + throw new RuntimeException(ioe); + } + }; + + testOfflineTokenMigration(convertOfflineTokenToKeycloak14Format); + } + + private void testOfflineTokenMigration(OfflineTokenConverter offlineTokenConverter) throws Exception { + // Send request to obtain offline token + oauth.scope(OAuth2Constants.OFFLINE_ACCESS); + oauth.clientId("direct-grant"); + + OAuthClient.AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password"); + Assert.assertNull(tokenResponse.getErrorDescription()); + String offlineTokenString = tokenResponse.getRefreshToken(); + + // Convert offline token to the format of some old Keycloak version + FetchOnServerWrapper fetch = new FetchOnServerWrapper<>() { + + @Override + public FetchOnServer getRunOnServer() { + return session -> offlineTokenConverter.apply(session, offlineTokenString); + } + + @Override + public Class getResultClass() { + return String.class; + } + + }; + String modifiedOfflineToken = testingClient.server("test").fetch(fetch); + getLogger().infof("Modified offline token: %s", modifiedOfflineToken); + + // Check it is possible to successfully refresh with the modified offline token + OAuthClient.AccessTokenResponse response = oauth.doRefreshTokenRequest(modifiedOfflineToken, "password"); + AccessToken refreshedToken = oauth.verifyToken(response.getAccessToken()); + Assert.assertEquals(200, response.getStatusCode()); + } + + public interface OfflineTokenConverter extends Serializable, BiFunction { + } +} From 9805443267757b7e21634ec29d3a68bdab8d0c48 Mon Sep 17 00:00:00 2001 From: Stefan Guilhen Date: Wed, 12 Jun 2024 09:34:19 -0300 Subject: [PATCH 058/103] Fix GroupLDAPStorageMapper so it doesn't attempt to update a group fetched in a different tx when synchronizing groups from LDAP Closes #29784 Signed-off-by: Stefan Guilhen (cherry picked from commit c49b5749ef9ed7be8c408ae5b4b6d29ad6a20ff6) --- .../group/GroupLDAPStorageMapper.java | 10 ++-- .../ldap/LDAPGroupMapperSyncTest.java | 60 ++++++++++++++++++- 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/federation/ldap/src/main/java/org/keycloak/storage/ldap/mappers/membership/group/GroupLDAPStorageMapper.java b/federation/ldap/src/main/java/org/keycloak/storage/ldap/mappers/membership/group/GroupLDAPStorageMapper.java index b72f6a658a0..ccda382696e 100644 --- a/federation/ldap/src/main/java/org/keycloak/storage/ldap/mappers/membership/group/GroupLDAPStorageMapper.java +++ b/federation/ldap/src/main/java/org/keycloak/storage/ldap/mappers/membership/group/GroupLDAPStorageMapper.java @@ -194,13 +194,15 @@ public String getStatus() { return syncResult; } - private void syncExistingGroup(GroupModel kcExistingGroup, Map.Entry groupEntry, + private void syncExistingGroup(RealmModel realm, GroupModel kcExistingGroup, Map.Entry groupEntry, SynchronizationResult syncResult, Set visitedGroupIds, String groupName) { try { // Update each existing group to be synced in its own inner transaction to prevent race condition when // the groups intended to be updated was already deleted via other channel in the meantime KeycloakModelUtils.runJobInTransaction(ldapProvider.getSession().getKeycloakSessionFactory(), session -> { - updateAttributesOfKCGroup(kcExistingGroup, groupEntry.getValue()); + RealmModel innerTransactionRealm = session.realms().getRealm(realm.getId()); + GroupModel innerTransactionGroup = session.groups().getGroupById(innerTransactionRealm, kcExistingGroup.getId()); + updateAttributesOfKCGroup(innerTransactionGroup, groupEntry.getValue()); syncResult.increaseUpdated(); visitedGroupIds.add(kcExistingGroup.getId()); }); @@ -278,9 +280,9 @@ private void syncFlatGroupStructure(RealmModel realm, SynchronizationResult sync GroupModel kcExistingGroup = transactionGroupPathGroups.get(groupName); if (kcExistingGroup != null) { - syncExistingGroup(kcExistingGroup, groupEntry, syncResult, visitedGroupIds, groupName); + syncExistingGroup(currentRealm, kcExistingGroup, groupEntry, syncResult, visitedGroupIds, groupName); } else { - syncNonExistingGroup(realm, groupEntry, syncResult, visitedGroupIds, groupName); + syncNonExistingGroup(currentRealm, groupEntry, syncResult, visitedGroupIds, groupName); } } }); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncTest.java index 2ae482cdcc7..6153075939b 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPGroupMapperSyncTest.java @@ -39,6 +39,7 @@ import org.keycloak.storage.ldap.LDAPUtils; import org.keycloak.storage.ldap.idm.model.LDAPDn; import org.keycloak.storage.ldap.idm.model.LDAPObject; +import org.keycloak.storage.ldap.mappers.LDAPStorageMapper; import org.keycloak.storage.ldap.mappers.membership.LDAPGroupMapperMode; import org.keycloak.storage.ldap.mappers.membership.MembershipType; import org.keycloak.storage.ldap.mappers.membership.group.GroupLDAPStorageMapper; @@ -52,6 +53,7 @@ import java.util.Date; import java.util.Set; import java.util.stream.Collectors; +import java.util.stream.Stream; import static org.keycloak.testsuite.util.LDAPTestUtils.getGroupDescriptionLDAPAttrName; @@ -114,7 +116,6 @@ private void testSyncNoPreserveGroupInheritance() throws Exception { testingClient.server().run(session -> { LDAPTestContext ctx = LDAPTestContext.init(session); RealmModel realm = ctx.getRealm(); - String descriptionAttrName = LDAPTestUtils.getGroupDescriptionLDAPAttrName(ctx.getLdapProvider()); ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(realm, ctx.getLdapModel(), "groupsMapper"); LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel()); GroupLDAPStorageMapper groupMapper = LDAPTestUtils.getGroupMapper(mapperModel, ldapProvider, realm); @@ -500,4 +501,61 @@ public void test07_ldapGroupsSyncHasLinearTimeComplexity() throws Exception { } + @Test + public void test08_flatSynchWithBatchSizeLessThanNumberOfGroups() { + // update the LDAP config to use pagination and a batch size that is less than the number of LDAP groups. + testingClient.server().run(session -> { + LDAPTestContext ctx = LDAPTestContext.init(session); + RealmModel realm = ctx.getRealm(); + ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(realm); + LDAPTestUtils.updateConfigOptions(ldapModel, LDAPConstants.PAGINATION, "true", LDAPConstants.BATCH_SIZE_FOR_SYNC, "1"); + realm.updateComponent(ldapModel); + + ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(ctx.getRealm(), ldapModel, "groupsMapper"); + LDAPTestUtils.updateConfigOptions(mapperModel, GroupMapperConfig.PRESERVE_GROUP_INHERITANCE, "false"); + realm.updateComponent(mapperModel); + }); + + testingClient.server().run(session -> { + LDAPTestContext ctx = LDAPTestContext.init(session); + RealmModel realm = ctx.getRealm(); + ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(realm, ctx.getLdapModel(), "groupsMapper"); + + // check right config is in place. + Assert.assertEquals(ctx.getLdapModel().getConfig().getFirst(LDAPConstants.PAGINATION), "true"); + Assert.assertEquals(ctx.getLdapModel().getConfig().getFirst(LDAPConstants.BATCH_SIZE_FOR_SYNC), "1"); + Assert.assertEquals(mapperModel.getConfig().getFirst(GroupMapperConfig.PRESERVE_GROUP_INHERITANCE), "false"); + + // synch groups a first time - imports all new groups into keycloak. + LDAPStorageMapper groupMapper = new GroupLDAPStorageMapperFactory().create(session, mapperModel); + SynchronizationResult syncResult = groupMapper.syncDataFromFederationProviderToKeycloak(realm); + LDAPTestAsserts.assertSyncEquals(syncResult, 3, 0, 0, 0); + + // check all groups were imported as top level groups with no subgroups. + Stream.of("/group1", "/group11", "/group12").forEach(path -> { + GroupModel kcGroup = KeycloakModelUtils.findGroupByPath(session, realm, path); + Assert.assertNotNull(kcGroup); + Assert.assertEquals(0, kcGroup.getSubGroupsStream().count()); + }); + + // re-synch groups, updating previously imported groups. + syncResult = groupMapper.syncDataFromFederationProviderToKeycloak(realm); + LDAPTestAsserts.assertSyncEquals(syncResult, 0, 3, 0, 0); + }); + + // restore pagination, batch size and preserve inheritance configs. + testingClient.server().run(session -> { + LDAPTestContext ctx = LDAPTestContext.init(session); + RealmModel realm = ctx.getRealm(); + ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(realm); + ldapModel.getConfig().putSingle(LDAPConstants.PAGINATION, "false"); + ldapModel.getConfig().remove(LDAPConstants.BATCH_SIZE_FOR_SYNC); + realm.updateComponent(ldapModel); + + ComponentModel mapperModel = LDAPTestUtils.getSubcomponentByName(ctx.getRealm(), ldapModel, "groupsMapper"); + LDAPTestUtils.updateConfigOptions(mapperModel, GroupMapperConfig.PRESERVE_GROUP_INHERITANCE, "false"); + realm.updateComponent(mapperModel); + }); + } + } From 2858bc210f0652de93bcae48958dbbde1d36da39 Mon Sep 17 00:00:00 2001 From: Ricardo Martin Date: Tue, 16 Jul 2024 15:38:38 +0200 Subject: [PATCH 059/103] Fix test LDAP connection with multiple ldap connection urls Previously, the given connection string was check with URI.create(..) which failed when multiple space separated LDAP URLs were given. Closes #31267 (cherry picked from commit 2140e573f2d53ddbc1db6ec68e17c14c26c52fa8) Signed-off-by: Thomas Darimont Co-authored-by: Thomas Darimont --- .../LDAPServerCapabilitiesManager.java | 25 ++++++++++++++++++- .../UserFederationLdapConnectionTest.java | 15 ++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java b/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java index 18eb96b4b86..49dba42a79a 100755 --- a/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java +++ b/federation/ldap/src/main/java/org/keycloak/services/managers/LDAPServerCapabilitiesManager.java @@ -27,6 +27,7 @@ import org.keycloak.component.ComponentModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.LDAPConstants; +import org.keycloak.models.ModelValidationException; import org.keycloak.models.RealmModel; import org.keycloak.representations.idm.ComponentRepresentation; import org.keycloak.representations.idm.TestLdapConnectionRepresentation; @@ -73,7 +74,7 @@ public static LDAPConfig buildLDAPConfig(TestLdapConnectionRepresentation config ComponentModel component = realm.getComponent(config.getComponentId()); if (component != null) { LDAPConfig ldapConfig = new LDAPConfig(component.getConfig()); - if (Objects.equals(URI.create(config.getConnectionUrl()), URI.create(ldapConfig.getConnectionUrl())) + if (checkLdapConnectionUrl(config, ldapConfig) && config.getBindDn() != null && config.getBindDn().equalsIgnoreCase(ldapConfig.getBindDN())) { bindCredential = ldapConfig.getBindCredential(); } @@ -94,6 +95,28 @@ public static LDAPConfig buildLDAPConfig(TestLdapConnectionRepresentation config return new LDAPConfig(configMap); } + /** + * Ensure provided connection URI matches parsed LDAP connection URI. + * + * See: https://docs.oracle.com/javase/jndi/tutorial/ldap/misc/url.html + * @param config + * @param ldapConfig + * @return + */ + private static boolean checkLdapConnectionUrl(TestLdapConnectionRepresentation config, LDAPConfig ldapConfig) { + // There could be multiple connection URIs separated via spaces. + String[] configConnectionUrls = config.getConnectionUrl().trim().split(" "); + String[] ldapConfigConnectionUrls = ldapConfig.getConnectionUrl().trim().split(" "); + if (configConnectionUrls.length != ldapConfigConnectionUrls.length) { + return false; + } + boolean urlsMatch = true; + for (int i = 0; i < configConnectionUrls.length && urlsMatch; i++) { + urlsMatch = Objects.equals(URI.create(configConnectionUrls[i]), URI.create(ldapConfigConnectionUrls[i])); + } + return urlsMatch; + } + public static Set queryServerCapabilities(TestLdapConnectionRepresentation config, KeycloakSession session, RealmModel realm) { diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserFederationLdapConnectionTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserFederationLdapConnectionTest.java index ecc4382fd33..b372fa7b92a 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserFederationLdapConnectionTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/admin/UserFederationLdapConnectionTest.java @@ -131,6 +131,7 @@ public void testLdapConnectionsSsl() { @Test public void testLdapConnectionMoreServers() { + // Both servers work Response response = realm.testLDAPConnection(new TestLdapConnectionRepresentation(LDAPServerCapabilitiesManager.TEST_AUTHENTICATION, "ldap://localhost:10389 ldaps://localhost:10636", "uid=admin,ou=system", "secret", "true", null)); assertStatus(response, 204); @@ -155,11 +156,23 @@ public void testLdapConnectionMoreServers() { response = realm.testLDAPConnection(new TestLdapConnectionRepresentation(LDAPServerCapabilitiesManager.TEST_AUTHENTICATION, "ldap://localhostt:10389 ldaps://localhostt:10636", "uid=admin,ou=system", "secret", "true", null)); assertStatus(response, 400); + // create LDAP component model using ldap + Map cfg = ldapRule.getConfig(); + cfg.put(LDAPConstants.CONNECTION_URL, "ldap://invalid:10389 ldap://localhost:10389"); + cfg.put(LDAPConstants.CONNECTION_TIMEOUT, "1000"); + String ldapModelId = testingClient.testing().ldap(REALM_NAME).createLDAPProvider(cfg, false); + + // Only 2nd server works with stored LDAP federation provider + response = realm.testLDAPConnection(new TestLdapConnectionRepresentation(LDAPServerCapabilitiesManager.TEST_AUTHENTICATION, + cfg.get(LDAPConstants.CONNECTION_URL), cfg.get(LDAPConstants.BIND_DN), ComponentRepresentation.SECRET_VALUE, + cfg.get(LDAPConstants.USE_TRUSTSTORE_SPI), cfg.get(LDAPConstants.CONNECTION_TIMEOUT),cfg.get(LDAPConstants.START_TLS), + cfg.get(LDAPConstants.AUTH_TYPE), ldapModelId)); + assertStatus(response, 204); } @Test public void testLdapConnectionComponentAlreadyCreated() { - // create ldap componnet model using ldaps + // create ldap component model using ldaps Map cfg = ldapRule.getConfig(); cfg.put(LDAPConstants.CONNECTION_URL, "ldaps://localhost:10636"); cfg.put(LDAPConstants.START_TLS, "false"); From adb3765a842f75db4dd5c48096e5c7c5dff4dd5a Mon Sep 17 00:00:00 2001 From: Pedro Ruivo Date: Tue, 16 Jul 2024 11:05:38 +0100 Subject: [PATCH 060/103] Add default stack in cache-ispn.xml A bug in Infinispan prevents the metrics to be registered if the "stack" is not specified. Change the default configuration shipped with Keycloak to use the UDP stack as default. UDP is the default in previous Keycloak versions. Fixes #31218 Signed-off-by: Pedro Ruivo Signed-off-by: Alexander Schwartz Co-authored-by: Alexander Schwartz --- docs/guides/high-availability/concepts-threads.adoc | 5 +++-- quarkus/runtime/src/main/resources/cache-ispn.xml | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/guides/high-availability/concepts-threads.adoc b/docs/guides/high-availability/concepts-threads.adoc index 16d526b3dbe..b20158e61d1 100644 --- a/docs/guides/high-availability/concepts-threads.adoc +++ b/docs/guides/high-availability/concepts-threads.adoc @@ -34,13 +34,14 @@ Low numbers ensure fast response times for all clients, even if there is an occa === JGroups connection pool The combined number of executor threads in all {project_name} nodes in the cluster should not exceed the number of threads available in JGroups thread pool to avoid the error `org.jgroups.util.ThreadPool: thread pool is full`. -To see the error the first time it happens, the system property `jgroups.thread_dumps_threshold` needs to be set to `1`, as otherwise the message appears only after 10000 threads have been rejected. +To see the error the first time it happens, the system property `jgroups.thread_dumps_threshold` needs to be set to `1`, as otherwise the message appears only after 10000 requests have been rejected. -- include::partials/threads/executor-jgroups-thread-calculation.adoc[] -- -Use the metrics `vendor_jgroups_tcp_get_thread_pool_size` to monitor the total JGroup threads in the pool and `vendor_jgroups_tcp_get_thread_pool_size_active` for the threads active in the pool. +Use metrics to monitor the total JGroup threads in the pool and for the threads active in the pool. +When using TCP as the JGroups transport protocol, the metrics `vendor_jgroups_tcp_get_thread_pool_size` and `vendor_jgroups_tcp_get_thread_pool_size_active` are available for monitoring. When using UDP, the metrics `vendor_jgroups_udp_get_thread_pool_size` and `vendor_jgroups_udp_get_thread_pool_size_active` are available. This is useful to monitor that limiting the Quarkus thread pool size keeps the number of active JGroup threads below the maximum JGroup thread pool size. [#load-shedding] diff --git a/quarkus/runtime/src/main/resources/cache-ispn.xml b/quarkus/runtime/src/main/resources/cache-ispn.xml index 672e51fa23f..14827b50a50 100644 --- a/quarkus/runtime/src/main/resources/cache-ispn.xml +++ b/quarkus/runtime/src/main/resources/cache-ispn.xml @@ -22,7 +22,7 @@ xmlns="urn:infinispan:config:15.0"> - + From 9d7d40f6b364b81a843705c2400efbf4dbd1e26f Mon Sep 17 00:00:00 2001 From: Erik Jan de Wit Date: Wed, 17 Jul 2024 09:43:11 +0200 Subject: [PATCH 061/103] fixed the url missed after refactoring (#31284) (#31298) fixes: #31244 Signed-off-by: Erik Jan de Wit (cherry picked from commit fab9028caa4ab8bbb305f9d8731947b3bddd78f4) --- .../src/identity-providers/component/RedirectUrl.tsx | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/js/apps/admin-ui/src/identity-providers/component/RedirectUrl.tsx b/js/apps/admin-ui/src/identity-providers/component/RedirectUrl.tsx index 3f110aa37f7..f6e57e40a11 100644 --- a/js/apps/admin-ui/src/identity-providers/component/RedirectUrl.tsx +++ b/js/apps/admin-ui/src/identity-providers/component/RedirectUrl.tsx @@ -1,18 +1,16 @@ import { ClipboardCopy, FormGroup } from "@patternfly/react-core"; import { useTranslation } from "react-i18next"; -import { HelpItem } from "@keycloak/keycloak-ui-shared"; -import { useAdminClient } from "../../admin-client"; +import { HelpItem, useEnvironment } from "@keycloak/keycloak-ui-shared"; import { useRealm } from "../../context/realm-context/RealmContext"; import { addTrailingSlash } from "../../util"; export const RedirectUrl = ({ id }: { id: string }) => { - const { adminClient } = useAdminClient(); - + const { environment } = useEnvironment(); const { t } = useTranslation(); const { realm } = useRealm(); const callbackUrl = `${addTrailingSlash( - adminClient.baseUrl, + environment.serverBaseUrl, )}realms/${realm}/broker`; return ( From d12adba078885af83560d57709661cb3bf9c1eb5 Mon Sep 17 00:00:00 2001 From: Ricardo Martin Date: Wed, 17 Jul 2024 09:38:29 +0200 Subject: [PATCH 062/103] Correctly moves to the next required action (#31358) Closes #31014 Signed-off-by: Giuseppe Graziano Co-authored-by: Giuseppe Graziano Co-authored-by: rmartinc (cherry picked from commit 3d12c05005170d7c63f84850803316b047924382) --- .../managers/AuthenticationManager.java | 43 +++++++++++--- .../RequiredActionEmailVerificationTest.java | 58 +++++++++++++++++++ .../actions/RequiredActionPriorityTest.java | 35 +++++++++++ .../broker/AbstractFirstBrokerLoginTest.java | 16 ++--- 4 files changed, 133 insertions(+), 19 deletions(-) diff --git a/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java b/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java index 10fd0e7523b..acba5312c3b 100755 --- a/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java +++ b/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java @@ -958,7 +958,14 @@ public static boolean isSSOAuthentication(AuthenticatedClientSessionModel client public static Response nextActionAfterAuthentication(KeycloakSession session, AuthenticationSessionModel authSession, ClientConnection clientConnection, HttpRequest request, UriInfo uriInfo, EventBuilder event) { - Response requiredAction = actionRequired(session, authSession, request, event); + return nextActionAfterAuthentication(session, authSession, clientConnection, request, uriInfo, event, new HashSet<>()); + } + + private static Response nextActionAfterAuthentication(KeycloakSession session, AuthenticationSessionModel authSession, + ClientConnection clientConnection, + HttpRequest request, UriInfo uriInfo, EventBuilder event, + Set ignoredActions) { + Response requiredAction = actionRequired(session, authSession, request, event, ignoredActions); if (requiredAction != null) return requiredAction; return finishedRequiredActions(session, authSession, null, clientConnection, request, uriInfo, event); @@ -1041,7 +1048,7 @@ public static String nextRequiredAction(final KeycloakSession session, final Aut final var realm = authSession.getRealm(); final var user = authSession.getAuthenticatedUser(); - evaluateRequiredActionTriggers(session, authSession, request, event, realm, user); + evaluateRequiredActionTriggers(session, authSession, request, event, realm, user, new HashSet<>()); final var kcAction = authSession.getClientNote(Constants.KC_ACTION); final var nextApplicableAction = @@ -1093,17 +1100,21 @@ private static UserConsentModel getEffectiveGrantedConsent(KeycloakSession sessi } } - public static Response actionRequired(final KeycloakSession session, final AuthenticationSessionModel authSession, final HttpRequest request, final EventBuilder event) { + return actionRequired(session, authSession, request, event, new HashSet<>()); + } + + private static Response actionRequired(final KeycloakSession session, final AuthenticationSessionModel authSession, + final HttpRequest request, final EventBuilder event, Set ignoredActions) { final var realm = authSession.getRealm(); final var user = authSession.getAuthenticatedUser(); - evaluateRequiredActionTriggers(session, authSession, request, event, realm, user); + evaluateRequiredActionTriggers(session, authSession, request, event, realm, user, ignoredActions); event.detail(Details.CODE_ID, authSession.getParentSession().getId()); - final var actionResponse = executionActions(session, authSession, request, event, realm, user); + final var actionResponse = executionActions(session, authSession, request, event, realm, user, ignoredActions); if (actionResponse != null) { return actionResponse; } @@ -1218,21 +1229,22 @@ public static RequiredActionProvider createRequiredAction(RequiredActionContextR protected static Response executionActions(KeycloakSession session, AuthenticationSessionModel authSession, - HttpRequest request, EventBuilder event, RealmModel realm, UserModel user) { + HttpRequest request, EventBuilder event, RealmModel realm, UserModel user, Set ignoredActions) { final var kcAction = authSession.getClientNote(Constants.KC_ACTION); final var firstApplicableRequiredAction = getFirstApplicableRequiredAction(realm, authSession, user, kcAction); if (firstApplicableRequiredAction != null) { return executeAction(session, authSession, firstApplicableRequiredAction, request, event, realm, user, - kcAction != null); + kcAction != null, ignoredActions); } return null; } private static Response executeAction(KeycloakSession session, AuthenticationSessionModel authSession, RequiredActionProviderModel model, - HttpRequest request, EventBuilder event, RealmModel realm, UserModel user, boolean kcActionExecution) { + HttpRequest request, EventBuilder event, RealmModel realm, UserModel user, boolean kcActionExecution, + Set ignoredActions) { RequiredActionFactory factory = (RequiredActionFactory) session.getKeycloakSessionFactory() .getProviderFactory(RequiredActionProvider.class, model.getProviderId()); if (factory == null) { @@ -1279,12 +1291,20 @@ else if (context.getStatus() == RequiredActionContext.Status.CHALLENGE) { authSession.setAuthNote(AuthenticationProcessor.CURRENT_AUTHENTICATION_EXECUTION, model.getProviderId()); return context.getChallenge(); } + else if (context.getStatus() == RequiredActionContext.Status.IGNORE) { + authSession.getAuthenticatedUser().removeRequiredAction(factory.getId()); + authSession.removeRequiredAction(factory.getId()); + setKcActionStatus(factory.getId(), RequiredActionContext.KcActionStatus.SUCCESS, authSession); + ignoredActions.add(factory.getId()); + return nextActionAfterAuthentication(session, authSession, session.getContext().getConnection(), request, session.getContext().getUri(), event, ignoredActions); + } else if (context.getStatus() == RequiredActionContext.Status.SUCCESS) { event.clone().event(EventType.CUSTOM_REQUIRED_ACTION).detail(Details.CUSTOM_REQUIRED_ACTION, factory.getId()).success(); // don't have to perform the same action twice, so remove it from both the user and session required actions authSession.getAuthenticatedUser().removeRequiredAction(factory.getId()); authSession.removeRequiredAction(factory.getId()); setKcActionStatus(factory.getId(), RequiredActionContext.KcActionStatus.SUCCESS, authSession); + return nextActionAfterAuthentication(session, authSession, session.getContext().getConnection(), request, session.getContext().getUri(), event, ignoredActions); } return null; @@ -1370,9 +1390,16 @@ private static RequiredActionProviderModel getApplicableRequiredAction(final Rea public static void evaluateRequiredActionTriggers(final KeycloakSession session, final AuthenticationSessionModel authSession, final HttpRequest request, final EventBuilder event, final RealmModel realm, final UserModel user) { + evaluateRequiredActionTriggers(session, authSession, request, event, realm, user, new HashSet<>()); + } + + private static void evaluateRequiredActionTriggers(final KeycloakSession session, final AuthenticationSessionModel authSession, + final HttpRequest request, final EventBuilder event, + final RealmModel realm, final UserModel user, Set ignoredActions) { // see if any required actions need triggering, i.e. an expired password realm.getRequiredActionProvidersStream() .filter(RequiredActionProviderModel::isEnabled) + .filter(model -> !ignoredActions.contains(model.getProviderId())) .map(model -> toRequiredActionFactory(session, model, realm)) .filter(Objects::nonNull) .forEachOrdered(f -> evaluateRequiredAction(session, authSession, request, event, realm, user, f)); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionEmailVerificationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionEmailVerificationTest.java index 7ba1a461f75..6895ccdf5e4 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionEmailVerificationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionEmailVerificationTest.java @@ -31,6 +31,7 @@ import org.keycloak.events.EventType; import org.keycloak.models.Constants; import org.keycloak.models.RealmModel; +import org.keycloak.models.UserModel; import org.keycloak.models.UserModel.RequiredAction; import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.representations.idm.EventRepresentation; @@ -51,6 +52,7 @@ import org.keycloak.testsuite.pages.LoginPage; import org.keycloak.testsuite.pages.RegisterPage; import org.keycloak.testsuite.pages.VerifyEmailPage; +import org.keycloak.testsuite.pages.VerifyProfilePage; import org.keycloak.testsuite.updaters.UserAttributeUpdater; import org.keycloak.testsuite.util.GreenMailRule; import org.keycloak.testsuite.util.InfinispanTestTimeServiceRule; @@ -108,6 +110,9 @@ public class RequiredActionEmailVerificationTest extends AbstractTestRealmKeyclo @Page protected VerifyEmailPage verifyEmailPage; + @Page + protected VerifyProfilePage verifyProfilePage; + @Page protected RegisterPage registerPage; @@ -137,10 +142,18 @@ public void before() { ApiUtil.removeUserByUsername(testRealm(), "test-user@localhost"); UserRepresentation user = UserBuilder.create().enabled(true) .username("test-user@localhost") + .firstName("test-user") + .lastName("test-user") + .emailVerified(false) .email("test-user@localhost").build(); testUserId = ApiUtil.createUserAndResetPasswordWithAdminClient(testRealm(), user, "password"); } + protected boolean removeVerifyProfileAtImport() { + // in this test verify profile is enabled + return false; + } + /** * see KEYCLOAK-4163 */ @@ -1104,4 +1117,49 @@ public void actionTokenWithInvalidRequiredActions() throws IOException { // Required action included in the action token is not valid anymore, because we don't know the provider for it assertThat(errorPage.getError(), is("Required actions included in the link are not valid")); } + + @Test + public void testVerifyEmailWithNoEmailAndVerifyProfile() throws Exception { + UserResource user = testRealm().users().get(testUserId); + UserRepresentation userRep = user.toRepresentation(); + userRep.setEmail(""); + user.update(userRep); + + loginPage.open(); + loginPage.login("test-user@localhost", "password"); + + // verify profile should be presented first as the verify email is ignored without email + verifyProfilePage.assertCurrent(); + events.expectRequiredAction(EventType.VERIFY_PROFILE) + .user(testUserId) + .detail(Details.FIELDS_TO_UPDATE, UserModel.EMAIL) + .assertEvent(); + + verifyProfilePage.updateEmail("test-user@localhost", "test-user", "test-user"); + + verifyEmailPage.assertCurrent(); + + events.expectRequiredAction(EventType.UPDATE_PROFILE) + .user(testUserId) + .detail(Details.UPDATED_EMAIL, "test-user@localhost") + .assertEvent(); + + // verify email is presented now + Assert.assertEquals(1, greenMail.getReceivedMessages().length); + + final MimeMessage message = greenMail.getLastReceivedMessage(); + + final String verificationUrl = getEmailLink(message); + + // confirm + driver.navigate().to(verificationUrl); + + // back to app, already logged in + appPage.assertCurrent(); + + // email should be verified and required actions empty + userRep = user.toRepresentation(); + assertTrue(userRep.isEmailVerified()); + assertThat(userRep.getRequiredActions(), Matchers.empty()); + } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionPriorityTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionPriorityTest.java index 830281d16c4..bcd4f9e8929 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionPriorityTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionPriorityTest.java @@ -416,6 +416,41 @@ public void setupTotpAfterUpdatePassword() { } + @Test + public void skipToNextRequiredActionWithCustomPriority() { + enableRequiredActionForUser(RequiredAction.VERIFY_EMAIL); + enableRequiredActionForUser(RequiredAction.UPDATE_PASSWORD); + + RealmRepresentation realmRep = testRealm().toRepresentation(); + realmRep.setVerifyEmail(true); + testRealm().update(realmRep); + + final var userResource = testRealm().users().get(testUserId); + final var user = userResource.toRepresentation(); + user.setEmailVerified(true); + userResource.update(user); + + final var requiredActionsCustomOrdered = List.of( + RequiredAction.VERIFY_EMAIL, + RequiredAction.UPDATE_PASSWORD + ); + ApiUtil.updateRequiredActionsOrder(testRealm(), requiredActionsCustomOrdered); + + // Login + loginPage.open(); + loginPage.login(USERNAME, PASSWORD); + events.expectRequiredAction(EventType.CUSTOM_REQUIRED_ACTION).assertEvent(); + + // change password + changePasswordPage.assertCurrent(); + changePasswordPage.changePassword(NEW_PASSWORD, NEW_PASSWORD); + events.expectRequiredAction(EventType.UPDATE_PASSWORD).assertEvent(); + + appPage.assertCurrent(); + assertThat(appPage.getRequestType(), is(RequestType.AUTH_RESPONSE)); + events.expectLogin().assertEvent(); + } + private void enableRequiredActionForUser(final RequiredAction requiredAction) { setRequiredActionEnabled(TEST_REALM_NAME, testUserId, requiredAction.name(), true); } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractFirstBrokerLoginTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractFirstBrokerLoginTest.java index 58eddbdd32f..a6e9ec866b1 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractFirstBrokerLoginTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractFirstBrokerLoginTest.java @@ -20,7 +20,6 @@ import org.keycloak.events.EventType; import org.keycloak.models.IdentityProviderMapperModel; import org.keycloak.models.IdentityProviderSyncMode; -import org.keycloak.models.UserModel; import org.keycloak.representations.idm.ComponentRepresentation; import org.keycloak.representations.idm.EventRepresentation; import org.keycloak.representations.idm.FederatedIdentityRepresentation; @@ -33,7 +32,6 @@ import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.federation.UserMapStorageFactory; -import org.keycloak.testsuite.forms.VerifyProfileTest; import org.keycloak.testsuite.pages.LoginPasswordUpdatePage; import org.keycloak.testsuite.util.AccountHelper; import org.keycloak.testsuite.util.FederatedIdentityBuilder; @@ -45,7 +43,6 @@ import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; -import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.support.PageFactory; import static org.junit.Assert.assertEquals; @@ -72,7 +69,7 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractInitializedBa @Drone @SecondBrowser protected WebDriver driver2; - + @Rule public AssertEvents events = new AssertEvents(this); @@ -893,9 +890,6 @@ public void testSuccessfulAuthenticationWithoutUpdateProfile_emailNotProvided_em List users = realm.users().search("no-email"); assertEquals(1, users.size()); - List requiredActions = users.get(0).getRequiredActions(); - assertEquals(1, requiredActions.size()); - assertEquals(UserModel.RequiredAction.VERIFY_EMAIL.name(), requiredActions.get(0)); } @@ -1146,7 +1140,7 @@ public void testVerifyEmailInNewBrowserWithPreserveClient() { //test if the user has verified email assertTrue(consumerRealm.users().get(linkedUserId).toRepresentation().isEmailVerified()); } - + @Test public void testEventsOnUpdateProfileNoEmailChange() { updateExecutions(AbstractBrokerTest::setUpMissingUpdateProfileOnFirstLogin); @@ -1165,7 +1159,7 @@ public void testEventsOnUpdateProfileNoEmailChange() { loginPage.login("no-first-name", "password"); waitForPage(driver, "update account information", false); - + updateAccountInformationPage.assertCurrent(); updateAccountInformationPage.updateAccountInformation("FirstName", "LastName"); @@ -1219,7 +1213,7 @@ public void testEventsOnUpdateProfileWithEmailChange() { loginPage.login("no-first-name", "password"); waitForPage(driver, "update account information", false); - + updateAccountInformationPage.assertCurrent(); updateAccountInformationPage.updateAccountInformation("new-email@localhost.com","FirstName", "LastName"); @@ -1294,7 +1288,7 @@ public void testUpdateProfileIfMissingInformation() { loginPage.login("no-first-name", "password"); waitForPage(driver, "update account information", false); - + updateAccountInformationPage.assertCurrent(); updateAccountInformationPage.updateAccountInformation("FirstName", "LastName"); From 3fa8137823435ca871385f3776bb58a194f35d14 Mon Sep 17 00:00:00 2001 From: rmartinc Date: Wed, 17 Jul 2024 13:46:57 +0200 Subject: [PATCH 063/103] Wait for the brute force off-thread processing in AbstractAdvancedBrokerTest Closes #30188 Closes #30641 Signed-off-by: rmartinc (cherry picked from commit 5ea3becef57fa239961bd52f3d89235e86c238aa) --- .../org/keycloak/testsuite/AssertEvents.java | 35 +++++++++++++++++-- .../broker/AbstractAdvancedBrokerTest.java | 22 ++++++++++-- 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java index 05a6169512c..94e7617a033 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/AssertEvents.java @@ -27,6 +27,7 @@ import org.junit.runners.model.Statement; import org.keycloak.OAuth2Constants; import org.keycloak.authentication.authenticators.client.ClientIdAndSecretAuthenticator; +import org.keycloak.common.util.Time; import org.keycloak.events.Details; import org.keycloak.events.EventType; import org.keycloak.representations.idm.ClientRepresentation; @@ -41,6 +42,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.concurrent.TimeUnit; import static org.hamcrest.Matchers.emptyOrNullString; import static org.hamcrest.Matchers.is; @@ -369,16 +371,21 @@ public ExpectedEvent error(String error) { } public EventRepresentation assertEvent() { - return assertEvent(false); + return assertEvent(false, 0); + } + + public EventRepresentation assertEvent(boolean ignorePreviousEvents) { + return assertEvent(ignorePreviousEvents, 0); } /** * Assert the expected event was sent to the listener by Keycloak server. Returns this event. * * @param ignorePreviousEvents if true, test will ignore all the events, which were already present. Test will poll the events from the queue until it finds the event of expected type + * @param seconds The seconds to wait for the next event to come * @return the expected event */ - public EventRepresentation assertEvent(boolean ignorePreviousEvents) { + public EventRepresentation assertEvent(boolean ignorePreviousEvents, int seconds) { if (expected.getError() != null && ! expected.getType().endsWith("_ERROR")) { expected.setType(expected.getType() + "_ERROR"); } @@ -387,7 +394,7 @@ public EventRepresentation assertEvent(boolean ignorePreviousEvents) { // Consider 25 as a "limit" for maximum number of events in the queue for now List presentedEventTypes = new LinkedList<>(); for (int i = 0 ; i < 25 ; i++) { - EventRepresentation event = fetchNextEvent(); + EventRepresentation event = fetchNextEvent(seconds); if (event == null) { Assert.fail("Did not find the event of expected type " + expected.getType() +". Events present: " + presentedEventTypes); } @@ -523,4 +530,26 @@ private UserRepresentation getUser(String username) { private EventRepresentation fetchNextEvent() { return context.testingClient.testing().pollEvent(); } + + private EventRepresentation fetchNextEvent(int seconds) { + if (seconds <= 0) { + return fetchNextEvent(); + } + + final long millis = TimeUnit.SECONDS.toMillis(seconds); + final long start = Time.currentTimeMillis(); + do { + try { + EventRepresentation event = fetchNextEvent(); + if (event != null) { + return event; + } + // wait a bit to receive the event + TimeUnit.MILLISECONDS.sleep(millis / 10L); + } catch (InterruptedException e) { + // no-op + } + } while (Time.currentTimeMillis() - start < millis); + return null; + } } diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractAdvancedBrokerTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractAdvancedBrokerTest.java index ec38b1dd978..e6b645aee33 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractAdvancedBrokerTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/broker/AbstractAdvancedBrokerTest.java @@ -1,10 +1,13 @@ package org.keycloak.testsuite.broker; +import org.junit.Rule; import org.junit.Test; import org.keycloak.admin.client.resource.IdentityProviderResource; import org.keycloak.admin.client.resource.RealmResource; import org.keycloak.admin.client.resource.UserResource; import org.keycloak.common.util.Time; +import org.keycloak.events.Details; +import org.keycloak.events.EventType; import org.keycloak.models.IdentityProviderMapperSyncMode; import org.keycloak.models.IdentityProviderSyncMode; import org.keycloak.models.utils.TimeBasedOTP; @@ -18,6 +21,7 @@ import org.keycloak.services.Urls; import org.keycloak.storage.UserStorageProvider; import org.keycloak.testsuite.Assert; +import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.federation.DummyUserFederationProviderFactory; import org.keycloak.testsuite.util.AccountHelper; @@ -70,6 +74,8 @@ */ public abstract class AbstractAdvancedBrokerTest extends AbstractBrokerTest { + @Rule + public AssertEvents events = new AssertEvents(this); protected void createRoleMappersForConsumerRealm() { createRoleMappersForConsumerRealm(IdentityProviderMapperSyncMode.FORCE); @@ -546,7 +552,8 @@ public void testPostBrokerLoginFlowWithOTP_bruteForceEnabled() { totpPage.assertCurrent(); String totpSecret = totpPage.getTotpSecret(); totpPage.configure(totp.generateTOTP(totpSecret)); - assertNumFederatedIdentities(realm.users().search(bc.getUserLogin()).get(0).getId(), 1); + final UserRepresentation user = realm.users().search(bc.getUserLogin()).get(0); + assertNumFederatedIdentities(user.getId(), 1); AccountHelper.logout(adminClient.realm(bc.consumerRealmName()), bc.getUserLogin()); AccountHelper.logout(adminClient.realm(bc.providerRealmName()), bc.getUserLogin()); @@ -563,16 +570,25 @@ public void testPostBrokerLoginFlowWithOTP_bruteForceEnabled() { loginTotpPage.login("bad-totp"); Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); + events.clear(); + loginTotpPage.login("bad-totp"); Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); + // wait for the disabled to come + events.expect(EventType.USER_DISABLED_BY_TEMPORARY_LOCKOUT) + .realm(consumerRealmRep.getId()) + .user(user.getId()) + .client((String) null) + .detail(Details.REASON, "brute_force_attack detected") + .assertEvent(true, 5); + // Login with valid TOTP. I should not be able to login loginTotpPage.login(totp.generateTOTP(totpSecret)); Assert.assertEquals("Invalid authenticator code.", loginTotpPage.getInputError()); // Clear login failures - String userId = ApiUtil.findUserByUsername(realm, bc.getUserLogin()).getId(); - realm.attackDetection().clearBruteForceForUser(userId); + realm.attackDetection().clearBruteForceForUser(user.getId()); setOtpTimeOffset(TimeBasedOTP.DEFAULT_INTERVAL_SECONDS, totp); From c36a4a195c16b4e468091c275987f3383b0537ad Mon Sep 17 00:00:00 2001 From: Erik Jan de Wit Date: Mon, 22 Jul 2024 12:15:41 +0200 Subject: [PATCH 064/103] small fix for library mode (#30645) (#31427) Signed-off-by: Erik Jan de Wit (cherry picked from commit 5dd6e1412dea5f0db4dbdd34e7532a0688bb60ca) --- js/apps/account-ui/vite.config.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/js/apps/account-ui/vite.config.ts b/js/apps/account-ui/vite.config.ts index d3d666f7dff..638b753f245 100644 --- a/js/apps/account-ui/vite.config.ts +++ b/js/apps/account-ui/vite.config.ts @@ -9,6 +9,7 @@ export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd(), ""); const external = ["react", "react/jsx-runtime", "react-dom"]; const plugins = [react(), checker({ typescript: true })]; + const input = env.LIB ? undefined : "src/main.tsx"; if (env.LIB) { external.push("react-router-dom"); external.push("react-i18next"); @@ -23,7 +24,9 @@ export default defineConfig(({ mode }) => { formats: ["es"], }, } - : undefined; + : { + outDir: "target/classes/theme/keycloak.v3/account/resources", + }; return { base: "", server: { @@ -38,7 +41,7 @@ export default defineConfig(({ mode }) => { cssMinify: "lightningcss", manifest: true, rollupOptions: { - input: "src/main.tsx", + input, external, }, }, From 049785ef552948680d9d3f0d00247cdf90a69044 Mon Sep 17 00:00:00 2001 From: Jon Koops Date: Mon, 22 Jul 2024 15:46:24 +0200 Subject: [PATCH 065/103] Fix selector used to construct list of recovery codes (#31475) (#31483) Closes #31260 Signed-off-by: Jon Koops (cherry picked from commit d16e1ac1069444af7b75db7ee1584238eaaca0da) --- .../theme/base/login/login-recovery-authn-code-config.ftl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/themes/src/main/resources/theme/base/login/login-recovery-authn-code-config.ftl b/themes/src/main/resources/theme/base/login/login-recovery-authn-code-config.ftl index 143da9e2b0b..c664fc70766 100644 --- a/themes/src/main/resources/theme/base/login/login-recovery-authn-code-config.ftl +++ b/themes/src/main/resources/theme/base/login/login-recovery-authn-code-config.ftl @@ -75,7 +75,7 @@ /* copy recovery codes */ function copyRecoveryCodes() { var tmpTextarea = document.createElement("textarea"); - var codes = document.getElementById("kc-recovery-codes-list").getElementsByTagName("li"); + var codes = document.querySelectorAll("#kc-recovery-codes-list li"); for (i = 0; i < codes.length; i++) { tmpTextarea.value = tmpTextarea.value + codes[i].innerText + "\n"; } @@ -106,7 +106,7 @@ } function parseRecoveryCodeList() { - var recoveryCodes = document.querySelectorAll(".kc-recovery-codes-list li"); + var recoveryCodes = document.querySelectorAll("#kc-recovery-codes-list li"); var recoveryCodeList = ""; for (var i = 0; i < recoveryCodes.length; i++) { From d9073d6b336602399af6676b7339383c18374490 Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Tue, 23 Jul 2024 10:33:55 +0100 Subject: [PATCH 066/103] Backport to remove unused help text (#31482) Signed-off-by: Agnieszka Gancarczyk --- .../theme/keycloak.v2/admin/messages/messages_en.properties | 1 - 1 file changed, 1 deletion(-) diff --git a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties index bb0a6c7f30a..2dadc40c1c4 100644 --- a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties +++ b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties @@ -807,7 +807,6 @@ endpoints=Endpoints roleSaveError=Could not save role\: {{error}} keySize=Key size membershipUserLdapAttributeHelp=Used just if Membership Attribute Type is UID. It is the name of the LDAP attribute on user, which is used for membership mappings. Usually it will be 'uid'. For example if the value of 'Membership User LDAP Attribute' is 'uid' and LDAP group has 'memberUid\: john', then it is expected that particular LDAP user will have attribute 'uid\: john'. -validatingX509CertsHelp=The certificate in PEM format that must be used to check for signatures. Multiple certificates can be entered, separated by comma (,). The action "Import keys" can be used to re-import certificates from the "Metadata descriptor URL" (if present) into this option. The configuration should be saved after the import to definitely store the new certificates. samlCapabilityConfig=SAML capabilities accessTokenSignatureAlgorithmHelp=JWA algorithm used for signing access tokens. derFormatted=DER formatted From be8651e2b9d452a5b5aa160896caf7af091fa6d7 Mon Sep 17 00:00:00 2001 From: Steven Hawkins Date: Wed, 24 Jul 2024 03:27:45 -0400 Subject: [PATCH 067/103] fix: always omit hidden options (#31488) closes: #31340 Signed-off-by: Steve Hawkins --- .../keycloak/quarkus/runtime/cli/Help.java | 35 ++++++------------- ...andDistTest.testExportHelpAll.approved.txt | 8 +---- ...andDistTest.testImportHelpAll.approved.txt | 8 +---- ...dDistTest.testStartDevHelpAll.approved.txt | 12 +------ ...mandDistTest.testStartHelpAll.approved.txt | 12 +------ ...est.testStartOptimizedHelpAll.approved.txt | 12 +------ 6 files changed, 16 insertions(+), 71 deletions(-) diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Help.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Help.java index 40b199a78e4..bf5a960729c 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Help.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Help.java @@ -157,45 +157,32 @@ private void configureUsageMessage(CommandLine.Model.CommandSpec commandSpec) { } private boolean isVisible(OptionSpec option) { - if (option.description().length == 0) { - // do not show options without a description + if (option.description().length == 0 || option.hidden()) { + // do not show options without a description nor hidden return false; } + + if (allOptions) { + return true; + } String optionName = undecorateDuplicitOptionName(option.longestName()); OptionCategory category = null; - if (option.group() != null) { + if (option.group() != null && option.group().heading() != null) { category = OptionCategory.fromHeading(removeSuffix(option.group().heading(), ":")); } PropertyMapper mapper = getMapper(optionName, category); if (mapper == null) { final var disabledMapper = PropertyMappers.getDisabledMapper(optionName); - final var isDisabledMapper = disabledMapper.isPresent(); - + // Show disabled mappers, which do not have a description when they're enabled - final var isEnabledWhenEmpty = isDisabledMapper && disabledMapper.get().getEnabledWhen().isEmpty(); - if (isEnabledWhenEmpty) { - return true; - } - - if (allOptions && isDisabledMapper) { - return true; - } - - // only filter mapped options, defaults to the hidden marker - return !option.hidden() && !isDisabledMapper; - } - - boolean isUnsupportedOption = !PropertyMappers.isSupported(mapper); - - if (isUnsupportedOption) { - // unsupported options removed from help if all options are not requested - return !option.hidden() && allOptions; + return disabledMapper.flatMap(PropertyMapper::getEnabledWhen).isEmpty(); } - return !option.hidden(); + // unsupported options removed from help if all options are not requested + return PropertyMappers.isSupported(mapper); } public void setAllOptions(boolean allOptions) { diff --git a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testExportHelpAll.approved.txt b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testExportHelpAll.approved.txt index 3090fad2ccf..8798eae4625 100644 --- a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testExportHelpAll.approved.txt +++ b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testExportHelpAll.approved.txt @@ -171,16 +171,10 @@ Logging: DEPRECATED. Set the format for the GELF timestamp field. Uses Java SimpleDateFormat pattern. Default: yyyy-MM-dd HH:mm:ss,SSS. Available only when GELF is activated. ---log-gelf-version - The GELF version to be used. Possible values are: 1.0, 1.1. Default: 1.1. - Available only when GELF is activated. --log-level The log level of the root category or a comma-separated list of individual categories and their levels. For the root category, you don't need to specify a category. Default: info. ---log-syslog-app-name - The app name used when formatting the message in RFC5424 format. Default: - keycloak. Available only when Syslog is activated. --log-syslog-endpoint The IP address and port of the syslog server. Default: localhost:514. Available only when Syslog is activated. @@ -217,4 +211,4 @@ Export: --users-per-file Set the number of users per file. It is used only if 'users' is set to 'different_files'. Increasing this number leads to exponentially increasing - export times. Default: 50. + export times. Default: 50. \ No newline at end of file diff --git a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testImportHelpAll.approved.txt b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testImportHelpAll.approved.txt index 1486b7a9879..10b9f14eaf1 100644 --- a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testImportHelpAll.approved.txt +++ b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testImportHelpAll.approved.txt @@ -171,16 +171,10 @@ Logging: DEPRECATED. Set the format for the GELF timestamp field. Uses Java SimpleDateFormat pattern. Default: yyyy-MM-dd HH:mm:ss,SSS. Available only when GELF is activated. ---log-gelf-version - The GELF version to be used. Possible values are: 1.0, 1.1. Default: 1.1. - Available only when GELF is activated. --log-level The log level of the root category or a comma-separated list of individual categories and their levels. For the root category, you don't need to specify a category. Default: info. ---log-syslog-app-name - The app name used when formatting the message in RFC5424 format. Default: - keycloak. Available only when Syslog is activated. --log-syslog-endpoint The IP address and port of the syslog server. Default: localhost:514. Available only when Syslog is activated. @@ -211,4 +205,4 @@ Import: --file Set the path to a file that will be read. --override Set if existing data should be overwritten. If set to false, data will be - ignored. Default: true. + ignored. Default: true. \ No newline at end of file diff --git a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testStartDevHelpAll.approved.txt b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testStartDevHelpAll.approved.txt index 9cee99fa773..a5229b5677c 100644 --- a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testStartDevHelpAll.approved.txt +++ b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testStartDevHelpAll.approved.txt @@ -191,10 +191,6 @@ Hostname v1 (Deprecated): headers to allow internal and external applications. If all applications use the public URL this option should be enabled. Default: false. Available only when hostname:v1 feature is enabled. ---hostname-strict-https - DEPRECATED. Forces frontend URLs to use the 'https' scheme. If set to false, - the HTTP scheme is inferred from requests. Default: true. Available only - when hostname:v1 feature is enabled. --hostname-url DEPRECATED. Set the base URL for frontend URLs, including scheme, host, port and path. Available only when hostname:v1 feature is enabled. @@ -384,16 +380,10 @@ Logging: DEPRECATED. Set the format for the GELF timestamp field. Uses Java SimpleDateFormat pattern. Default: yyyy-MM-dd HH:mm:ss,SSS. Available only when GELF is activated. ---log-gelf-version - The GELF version to be used. Possible values are: 1.0, 1.1. Default: 1.1. - Available only when GELF is activated. --log-level The log level of the root category or a comma-separated list of individual categories and their levels. For the root category, you don't need to specify a category. Default: info. ---log-syslog-app-name - The app name used when formatting the message in RFC5424 format. Default: - keycloak. Available only when Syslog is activated. --log-syslog-endpoint The IP address and port of the syslog server. Default: localhost:514. Available only when Syslog is activated. @@ -430,4 +420,4 @@ Security: Do NOT start the server using this command when deploying to production. Use 'kc.sh start-dev --help-all' to list all available options, including build -options. +options. \ No newline at end of file diff --git a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testStartHelpAll.approved.txt b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testStartHelpAll.approved.txt index 71f903f1d2a..c50deebb8f3 100644 --- a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testStartHelpAll.approved.txt +++ b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testStartHelpAll.approved.txt @@ -192,10 +192,6 @@ Hostname v1 (Deprecated): headers to allow internal and external applications. If all applications use the public URL this option should be enabled. Default: false. Available only when hostname:v1 feature is enabled. ---hostname-strict-https - DEPRECATED. Forces frontend URLs to use the 'https' scheme. If set to false, - the HTTP scheme is inferred from requests. Default: true. Available only - when hostname:v1 feature is enabled. --hostname-url DEPRECATED. Set the base URL for frontend URLs, including scheme, host, port and path. Available only when hostname:v1 feature is enabled. @@ -385,16 +381,10 @@ Logging: DEPRECATED. Set the format for the GELF timestamp field. Uses Java SimpleDateFormat pattern. Default: yyyy-MM-dd HH:mm:ss,SSS. Available only when GELF is activated. ---log-gelf-version - The GELF version to be used. Possible values are: 1.0, 1.1. Default: 1.1. - Available only when GELF is activated. --log-level The log level of the root category or a comma-separated list of individual categories and their levels. For the root category, you don't need to specify a category. Default: info. ---log-syslog-app-name - The app name used when formatting the message in RFC5424 format. Default: - keycloak. Available only when Syslog is activated. --log-syslog-endpoint The IP address and port of the syslog server. Default: localhost:514. Available only when Syslog is activated. @@ -435,4 +425,4 @@ By default, this command tries to update the server configuration by running a $ kc.sh start '--optimized' By doing that, the server should start faster based on any previous -configuration you have set when manually running the 'build' command. +configuration you have set when manually running the 'build' command. \ No newline at end of file diff --git a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testStartOptimizedHelpAll.approved.txt b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testStartOptimizedHelpAll.approved.txt index 0df3c2a7c94..475d8243467 100644 --- a/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testStartOptimizedHelpAll.approved.txt +++ b/quarkus/tests/integration/src/test/resources/org/keycloak/it/cli/dist/approvals/cli/help/HelpCommandDistTest.testStartOptimizedHelpAll.approved.txt @@ -177,10 +177,6 @@ Hostname v1 (Deprecated): headers to allow internal and external applications. If all applications use the public URL this option should be enabled. Default: false. Available only when hostname:v1 feature is enabled. ---hostname-strict-https - DEPRECATED. Forces frontend URLs to use the 'https' scheme. If set to false, - the HTTP scheme is inferred from requests. Default: true. Available only - when hostname:v1 feature is enabled. --hostname-url DEPRECATED. Set the base URL for frontend URLs, including scheme, host, port and path. Available only when hostname:v1 feature is enabled. @@ -336,16 +332,10 @@ Logging: DEPRECATED. Set the format for the GELF timestamp field. Uses Java SimpleDateFormat pattern. Default: yyyy-MM-dd HH:mm:ss,SSS. Available only when GELF is activated. ---log-gelf-version - The GELF version to be used. Possible values are: 1.0, 1.1. Default: 1.1. - Available only when GELF is activated. --log-level The log level of the root category or a comma-separated list of individual categories and their levels. For the root category, you don't need to specify a category. Default: info. ---log-syslog-app-name - The app name used when formatting the message in RFC5424 format. Default: - keycloak. Available only when Syslog is activated. --log-syslog-endpoint The IP address and port of the syslog server. Default: localhost:514. Available only when Syslog is activated. @@ -377,4 +367,4 @@ By default, this command tries to update the server configuration by running a $ kc.sh start '--optimized' By doing that, the server should start faster based on any previous -configuration you have set when manually running the 'build' command. +configuration you have set when manually running the 'build' command. \ No newline at end of file From fd0eddf44f4e3c33d9d49430a03ff821512bd5c2 Mon Sep 17 00:00:00 2001 From: Miquel Simon Date: Wed, 24 Jul 2024 11:12:58 +0200 Subject: [PATCH 068/103] Updated connection configuration for MSSQL test container Closes #31558 Signed-off-by: Miquel Simon (cherry picked from commit aab7a912c46527c3da2aa254aefd653504fd1cef) --- testsuite/integration-arquillian/pom.xml | 4 ++-- testsuite/integration-arquillian/tests/base/pom.xml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/testsuite/integration-arquillian/pom.xml b/testsuite/integration-arquillian/pom.xml index 0fa1bc9385d..e51370209ef 100644 --- a/testsuite/integration-arquillian/pom.xml +++ b/testsuite/integration-arquillian/pom.xml @@ -569,14 +569,14 @@ mcr.microsoft.com/mssql/server:${mssql.version} 1433 false - /opt/mssql-tools/bin/sqlcmd -e -U sa -P vEry5tron9Pwd -d master -Q CREATE\ DATABASE\ ${keycloak.connectionsJpa.database} + /opt/mssql-tools18/bin/sqlcmd -e -U sa -P ${keycloak.connectionsJpa.password} -No -d master -Q CREATE\ DATABASE\ ${keycloak.connectionsJpa.database} /bin/sh -c /opt/mssql/bin/sqlservr Recovery is complete. This is an informational message only. No user action is required. mssql com.microsoft.sqlserver.jdbc.SQLServerDriver keycloak sa - vEry5tron9Pwd + vEry$tron9Pwd jdbc:sqlserver://${auth.server.db.host}:${docker.database.port};databaseName=${keycloak.connectionsJpa.database};integratedSecurity=false;encrypt=false;trustServerCertificate=true;sendStringParametersAsUnicode=false; diff --git a/testsuite/integration-arquillian/tests/base/pom.xml b/testsuite/integration-arquillian/tests/base/pom.xml index 8676cf3e229..95cc57f2506 100644 --- a/testsuite/integration-arquillian/tests/base/pom.xml +++ b/testsuite/integration-arquillian/tests/base/pom.xml @@ -414,7 +414,7 @@ Y - ${keycloak.connectionsJpa.password} + ${keycloak.connectionsJpa.password} ${keycloak.connectionsJpa.database} From a573ce82037c2d99f57efb22cd02676a6931ed7b Mon Sep 17 00:00:00 2001 From: Erik Jan de Wit Date: Wed, 24 Jul 2024 16:47:06 +0200 Subject: [PATCH 069/103] removed strange searching pagination logic (#31430) (#31560) fixes: #31386 Signed-off-by: Erik Jan de Wit (cherry picked from commit 28c1035c5ba80ec853810457cc48596d31597565) --- js/apps/admin-ui/src/components/group/GroupPickerDialog.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/apps/admin-ui/src/components/group/GroupPickerDialog.tsx b/js/apps/admin-ui/src/components/group/GroupPickerDialog.tsx index 90a1506da8b..4e20382cabc 100644 --- a/js/apps/admin-ui/src/components/group/GroupPickerDialog.tsx +++ b/js/apps/admin-ui/src/components/group/GroupPickerDialog.tsx @@ -167,7 +167,7 @@ export const GroupPickerDialog = ({ ]} > Date: Wed, 24 Jul 2024 11:34:38 -0400 Subject: [PATCH 070/103] doc: add a note about setting proxy=edge (#31486) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * doc: add a note about setting proxy=edge closes: #30945 Signed-off-by: Steve Hawkins * Update docs/guides/operator/basic-deployment.adoc Co-authored-by: Martin Bartoš Signed-off-by: Steven Hawkins --------- Signed-off-by: Steve Hawkins Signed-off-by: Steven Hawkins Co-authored-by: Martin Bartoš --- docs/guides/operator/basic-deployment.adoc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/guides/operator/basic-deployment.adoc b/docs/guides/operator/basic-deployment.adoc index 0b62ea552e1..a8268ad6121 100644 --- a/docs/guides/operator/basic-deployment.adoc +++ b/docs/guides/operator/basic-deployment.adoc @@ -265,6 +265,8 @@ Misconfiguration will leave {project_name} exposed to security vulnerabilities. For more details refer to the <@links.server id="reverseproxy"/> guide. +NOTE: In an edge scenario where you do not wish to set `proxy.headers`, you must set `proxy=edge` as an option in `additionalOptions` field to override the implied default of `proxy=passthrough`. This will not be necessary in subsequent major releases. + === Accessing the Admin Console When deploying {project_name}, the operator generates an arbitrary initial admin `username` and `password` and stores those credentials as a basic-auth Secret object in the same namespace as the CR. From d767c784c9e5bf60e5933162840d536baab8896a Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Fri, 19 Jul 2024 17:12:49 +0200 Subject: [PATCH 071/103] Filter out null values when looking up entries by ID This should prevent null elements in the stream when doing concurrent operations. Closes #28865 Signed-off-by: Alexander Schwartz --- .../keycloak/models/jpa/JpaRealmProvider.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java index 5e143b153df..6b3b00589ae 100644 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java @@ -278,7 +278,7 @@ public Stream getRealmRolesStream(RealmModel realm) { query.setParameter("realm", realm.getId()); Stream roles = query.getResultStream(); - return closing(roles.map(realm::getRoleById)); + return closing(roles.map(realm::getRoleById).filter(Objects::nonNull)); } @Override @@ -331,7 +331,7 @@ public Stream getRolesStream(RealmModel realm, Stream ids, St .setParameter("ids", ids.collect(Collectors.toList())); return closing(paginateQuery(query, first, max).getResultStream()) - .map(g -> session.roles().getRoleById(realm, g)); + .map(g -> session.roles().getRoleById(realm, g)).filter(Objects::nonNull); } @Override @@ -555,7 +555,7 @@ public Stream getGroupsStream(RealmModel realm, Stream ids, .setParameter("ids", idsList); return closing(paginateQuery(query, first, max).getResultStream()) - .map(g -> session.groups().getGroupById(realm, g)); + .map(g -> session.groups().getGroupById(realm, g)).filter(Objects::nonNull); } @Override @@ -575,7 +575,7 @@ public Stream getGroupsStream(RealmModel realm, Stream ids, return closing(paginateQuery(query, first, max).getResultStream()) - .map(g -> session.groups().getGroupById(realm, g)); + .map(g -> session.groups().getGroupById(realm, g)).filter(Objects::nonNull); } @Override @@ -892,7 +892,7 @@ public Stream searchClientsByAttributes(RealmModel realm, Map query = em.createQuery(queryBuilder); return closing(paginateQuery(query, firstResult, maxResults).getResultStream()) - .map(id -> session.clients().getClientById(realm, id)); + .map(id -> session.clients().getClientById(realm, id)).filter(Objects::nonNull); } @Override @@ -937,7 +937,7 @@ public Stream searchClientsByAuthenticationFlowBindingOverrides(Rea TypedQuery query = em.createQuery(queryBuilder); return closing(paginateQuery(query, firstResult, maxResults).getResultStream()) - .map(id -> session.clients().getClientById(realm, id)); + .map(id -> session.clients().getClientById(realm, id)).filter(Objects::nonNull); } @Override @@ -1007,7 +1007,7 @@ public Stream getClientScopesStream(RealmModel realm) { query.setParameter("realm", realm.getId()); Stream scopes = query.getResultStream(); - return closing(scopes.map(realm::getClientScopeById)); + return closing(scopes.map(realm::getClientScopeById).filter(Objects::nonNull)); } @Override @@ -1132,7 +1132,7 @@ public Stream searchForGroupByNameStream(RealmModel realm, String se .setParameter("search", search); Stream groups = paginateQuery(query, first, max).getResultStream(); - return closing(groups.map(id -> session.groups().getGroupById(realm, id)).sorted(GroupModel.COMPARE_BY_NAME).distinct()); + return closing(groups.map(id -> session.groups().getGroupById(realm, id)).filter(Objects::nonNull).sorted(GroupModel.COMPARE_BY_NAME).distinct()); } @Override From 671e7a29c27b8a3867d3fb5825b482634ca55d29 Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Thu, 25 Jul 2024 05:20:28 +0100 Subject: [PATCH 072/103] Backport to add inputOptionLabelsI18nPrefix when looking up label (#31584) Signed-off-by: Agnieszka Gancarczyk --- .../ui-shared/src/user-profile/OptionsComponent.tsx | 5 ++++- .../ui-shared/src/user-profile/SelectComponent.tsx | 5 ++++- .../ui-shared/src/user-profile/TextComponent.tsx | 2 ++ js/libs/ui-shared/src/user-profile/utils.ts | 13 ++++++++----- 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/js/libs/ui-shared/src/user-profile/OptionsComponent.tsx b/js/libs/ui-shared/src/user-profile/OptionsComponent.tsx index 61634d03cb9..77f222fc911 100644 --- a/js/libs/ui-shared/src/user-profile/OptionsComponent.tsx +++ b/js/libs/ui-shared/src/user-profile/OptionsComponent.tsx @@ -18,6 +18,9 @@ export const OptionComponent = (props: UserProfileFieldProps) => { const optionLabel = (attribute.annotations?.["inputOptionLabels"] as OptionLabel) || {}; + const prefix = attribute.annotations?.[ + "inputOptionLabelsI18nPrefix" + ] as string; return ( @@ -32,7 +35,7 @@ export const OptionComponent = (props: UserProfileFieldProps) => { key={option} id={option} data-testid={option} - label={label(props.t, optionLabel[option], option)} + label={label(props.t, optionLabel[option], option, prefix)} value={option} isChecked={field.value.includes(option)} onChange={() => { diff --git a/js/libs/ui-shared/src/user-profile/SelectComponent.tsx b/js/libs/ui-shared/src/user-profile/SelectComponent.tsx index a1f07e28546..5c4531c53d2 100644 --- a/js/libs/ui-shared/src/user-profile/SelectComponent.tsx +++ b/js/libs/ui-shared/src/user-profile/SelectComponent.tsx @@ -40,9 +40,12 @@ export const SelectComponent = (props: UserProfileFieldProps) => { const optionLabel = (attribute.annotations?.["inputOptionLabels"] as OptionLabel) || {}; + const prefix = attribute.annotations?.[ + "inputOptionLabelsI18nPrefix" + ] as string; const fetchLabel = (option: string) => - label(props.t, optionLabel[option], option); + label(props.t, optionLabel[option], option, prefix); const convertOptions = (selected: string) => options diff --git a/js/libs/ui-shared/src/user-profile/TextComponent.tsx b/js/libs/ui-shared/src/user-profile/TextComponent.tsx index b3ae3832dd5..e6a5929eb26 100644 --- a/js/libs/ui-shared/src/user-profile/TextComponent.tsx +++ b/js/libs/ui-shared/src/user-profile/TextComponent.tsx @@ -20,6 +20,8 @@ export const TextComponent = (props: UserProfileFieldProps) => { placeholder={label( props.t, attribute.annotations?.["inputTypePlaceholder"] as string, + attribute.name, + attribute.annotations?.["inputOptionLabelsI18nPrefix"] as string, )} readOnly={attribute.readOnly} isRequired={isRequired} diff --git a/js/libs/ui-shared/src/user-profile/utils.ts b/js/libs/ui-shared/src/user-profile/utils.ts index 4009c66ae24..bbc30901294 100644 --- a/js/libs/ui-shared/src/user-profile/utils.ts +++ b/js/libs/ui-shared/src/user-profile/utils.ts @@ -31,7 +31,13 @@ export const label = ( t: TFunction, text: string | undefined, fallback?: string, -) => (isBundleKey(text) ? t(unWrap(text!)) : text) || fallback; + prefix?: string, +) => { + const value = text || fallback; + const bundleKey = isBundleKey(value) ? unWrap(value!) : value; + const key = prefix ? `${prefix}.${bundleKey}` : bundleKey; + return t(key || ""); +}; export const labelAttribute = ( t: TFunction, @@ -44,10 +50,7 @@ export const isRootAttribute = (attr?: string) => attr && ROOT_ATTRIBUTES.includes(attr); export const fieldName = (name?: string) => - `${isRootAttribute(name) ? "" : "attributes."}${name?.replaceAll( - ".", - "🍺", - )}` as FieldPath; + `${isRootAttribute(name) ? "" : "attributes."}${name?.replaceAll(".", "🍺")}` as FieldPath; export const beerify = (name: T) => name.replaceAll(".", "🍺"); From 3fdc78bab9b83956e7aad059ec4a24158546ed5a Mon Sep 17 00:00:00 2001 From: Erik Jan de Wit Date: Thu, 25 Jul 2024 10:02:39 +0200 Subject: [PATCH 073/103] add onOpenChange to all dropdown and selects (#31230) (#31562) * add onOpenChange to all dropdown and selects fixes: #31166 Signed-off-by: Erik Jan de Wit * fixed test Signed-off-by: Erik Jan de Wit --------- Signed-off-by: Erik Jan de Wit (cherry picked from commit b5597c629381685301f17ebd932732dd1450b817) --- js/apps/admin-ui/cypress/e2e/client_scopes_test.spec.ts | 2 ++ .../admin-ui/src/authentication/components/AddFlowDropdown.tsx | 1 + js/apps/admin-ui/src/client-scopes/ChangeTypeDropdown.tsx | 1 + js/apps/admin-ui/src/client-scopes/ClientScopesSection.tsx | 1 + js/apps/admin-ui/src/client-scopes/details/MapperList.tsx | 1 + js/apps/admin-ui/src/client-scopes/details/SearchFilter.tsx | 1 + js/apps/admin-ui/src/clients/advanced/AdvancedSettings.tsx | 1 + js/apps/admin-ui/src/clients/advanced/TokenLifespan.tsx | 1 + js/apps/admin-ui/src/clients/authorization/Permissions.tsx | 1 + js/apps/admin-ui/src/clients/authorization/SearchDropdown.tsx | 1 + js/apps/admin-ui/src/clients/scopes/AddScopeDialog.tsx | 3 +++ js/apps/admin-ui/src/clients/scopes/ClientScopes.tsx | 1 + .../admin-ui/src/components/client-scope/ClientScopeTypes.tsx | 1 + .../admin-ui/src/components/download-dialog/DownloadDialog.tsx | 1 + js/apps/admin-ui/src/components/help-enabler/HelpHeader.tsx | 1 + js/apps/admin-ui/src/components/keycloak-card/KeycloakCard.tsx | 1 + .../admin-ui/src/components/realm-selector/RealmSelector.tsx | 1 + .../src/components/role-mapping/AddRoleMappingModal.tsx | 1 + .../src/components/users/UserDataTableToolbarItems.tsx | 1 + js/apps/admin-ui/src/components/users/UserSelect.tsx | 1 + js/apps/admin-ui/src/components/view-header/ViewHeader.tsx | 2 ++ js/apps/admin-ui/src/groups/Members.tsx | 1 + js/apps/admin-ui/src/groups/components/GroupToolbar.tsx | 1 + js/apps/admin-ui/src/groups/components/GroupTree.tsx | 1 + .../src/identity-providers/IdentityProvidersSection.tsx | 1 + js/apps/admin-ui/src/organizations/IdentityProviderSelect.tsx | 1 + js/apps/admin-ui/src/organizations/Members.tsx | 1 + js/apps/admin-ui/src/realm-settings/DefaultGroupsTab.tsx | 1 + .../src/realm-settings/localization/RealmOverrides.tsx | 1 + js/apps/admin-ui/src/user/details/SearchFilter.tsx | 1 + js/apps/admin-ui/src/user/user-credentials/CredentialRow.tsx | 1 + js/libs/ui-shared/src/masthead/KeycloakDropdown.tsx | 1 + js/libs/ui-shared/src/select/SingleSelect.tsx | 2 +- js/libs/ui-shared/src/select/TypeaheadSelect.tsx | 2 +- 34 files changed, 38 insertions(+), 2 deletions(-) diff --git a/js/apps/admin-ui/cypress/e2e/client_scopes_test.spec.ts b/js/apps/admin-ui/cypress/e2e/client_scopes_test.spec.ts index c6c5f6cb2b7..f1ec9ab4e82 100644 --- a/js/apps/admin-ui/cypress/e2e/client_scopes_test.spec.ts +++ b/js/apps/admin-ui/cypress/e2e/client_scopes_test.spec.ts @@ -192,9 +192,11 @@ describe("Client Scopes test", () => { .checkDropdownItemIsDisabled("Delete") .clickItemCheckbox(itemName) .checkInSearchBarChangeTypeToButtonIsDisabled(false) + .clickSearchBarActionButton() .checkDropdownItemIsDisabled("Delete", false) .clickItemCheckbox(itemName) .checkInSearchBarChangeTypeToButtonIsDisabled() + .clickSearchBarActionButton() .checkDropdownItemIsDisabled("Delete"); }); diff --git a/js/apps/admin-ui/src/authentication/components/AddFlowDropdown.tsx b/js/apps/admin-ui/src/authentication/components/AddFlowDropdown.tsx index 55ea06ac84a..b4053e9cc98 100644 --- a/js/apps/admin-ui/src/authentication/components/AddFlowDropdown.tsx +++ b/js/apps/admin-ui/src/authentication/components/AddFlowDropdown.tsx @@ -49,6 +49,7 @@ export const AddFlowDropdown = ({ position: "right", }} isOpen={open} + onOpenChange={(isOpen) => setOpen(isOpen)} toggle={(ref) => ( setOpen(isOpen)} isOpen={open} toggle={(ref) => ( setKebabOpen(isOpen)} toggle={(ref) => ( setMapperAction(false)} + onOpenChange={(isOpen) => setMapperAction(isOpen)} toggle={(ref) => ( setSearchToggle(isOpen)} toggle={(ref) => ( )} isOpen={open} + onOpenChange={(isOpen) => setOpen(isOpen)} onSelect={(_, value) => { field.onChange(value); setOpen(false); diff --git a/js/apps/admin-ui/src/clients/advanced/TokenLifespan.tsx b/js/apps/admin-ui/src/clients/advanced/TokenLifespan.tsx index 1434737388b..99f0859c7c2 100644 --- a/js/apps/admin-ui/src/clients/advanced/TokenLifespan.tsx +++ b/js/apps/admin-ui/src/clients/advanced/TokenLifespan.tsx @@ -71,6 +71,7 @@ export const TokenLifespan = ({ )} isOpen={open} + onOpenChange={(isOpen) => setOpen(isOpen)} onSelect={(_, value) => { field.onChange(value); setOpen(false); diff --git a/js/apps/admin-ui/src/clients/authorization/Permissions.tsx b/js/apps/admin-ui/src/clients/authorization/Permissions.tsx index f95f4adca49..0ae01bd5468 100644 --- a/js/apps/admin-ui/src/clients/authorization/Permissions.tsx +++ b/js/apps/admin-ui/src/clients/authorization/Permissions.tsx @@ -208,6 +208,7 @@ export const AuthorizationPermissions = ({ ( ( setAddToggle(isOpen)} className="keycloak__client-scopes-add__add-dropdown" key="add-dropdown" isOpen={addToggle} @@ -215,6 +216,7 @@ export const AddScopeDialog = ({ onSelect={() => { onFilterTypeDropdownSelect(filterType); }} + onOpenChange={toggleIsFilterTypeDropdownOpen} toggle={(ref) => ( { onFilterTypeDropdownSelect(filterType); }} + onOpenChange={toggleIsFilterTypeDropdownOpen} data-testid="filter-type-dropdown" toggle={(ref) => ( setKebabOpen(isOpen)} toggle={(ref) => ( )} isOpen={open} + onOpenChange={(isOpen) => setOpen(isOpen)} selected={[type]} onSelect={(_, value) => { onSelect( diff --git a/js/apps/admin-ui/src/components/download-dialog/DownloadDialog.tsx b/js/apps/admin-ui/src/components/download-dialog/DownloadDialog.tsx index 7fa3e47df00..cea2e794a0f 100644 --- a/js/apps/admin-ui/src/components/download-dialog/DownloadDialog.tsx +++ b/js/apps/admin-ui/src/components/download-dialog/DownloadDialog.tsx @@ -125,6 +125,7 @@ export const DownloadDialog = ({ > ( ( ( { setIsKebabOpen(isOpen)} toggle={(ref) => ( ( ( setAddProviderOpen(isOpen)} toggle={(ref) => ( ( onToggle?.(false)} + onOpenChange={(isOpen) => onToggle?.(isOpen)} onSelect={(_, value) => onSelect?.(value || "")} maxMenuHeight={propertyToString(maxHeight)} popperProps={{ direction, width: propertyToString(width) }} From c0ed46a011c56d3e52c08b4017f86418d8d97104 Mon Sep 17 00:00:00 2001 From: Steven Hawkins Date: Thu, 25 Jul 2024 11:34:34 -0400 Subject: [PATCH 074/103] fix: backport of looking for separated --spi arguments for the config (#31576) closes: #31578 Signed-off-by: Steve Hawkins --- .../runtime/configuration/ConfigArgsConfigSource.java | 3 +-- .../runtime/configuration/ConfigArgsConfigSourceTest.java | 7 +++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/ConfigArgsConfigSource.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/ConfigArgsConfigSource.java index b37ff0f4a43..f48654d060f 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/ConfigArgsConfigSource.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/ConfigArgsConfigSource.java @@ -156,8 +156,7 @@ public static void parseConfigArgs(List args, BiConsumer // the weaknesses here: // - needs to know all of the short name options that accept a value // - does not know all of the picocli parsing rules. picocli will accept -cffile, and short option grouping - that's not accounted for - // - does not understand spi options, they will be assumed to be unary - if (mapper != null || SHORT_OPTIONS_ACCEPTING_VALUE.contains(key)) { + if (mapper != null || SHORT_OPTIONS_ACCEPTING_VALUE.contains(key) || arg.startsWith("--spi")) { i++; // consume next as a value to the key value = args.get(i); } else { diff --git a/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/ConfigArgsConfigSourceTest.java b/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/ConfigArgsConfigSourceTest.java index d5bc35b12f4..e3b29040db4 100644 --- a/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/ConfigArgsConfigSourceTest.java +++ b/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/ConfigArgsConfigSourceTest.java @@ -33,5 +33,12 @@ public void testParseArgs() { ConfigArgsConfigSource.parseConfigArgs(Arrays.asList("--key=value", "-cf", "file", "command", "arg", "--db", "value"), (key, value) -> values.add(key+'='+value), values::add); assertEquals(Arrays.asList("--key=value", "-cf=file", "command", "arg", "--db=value"), values); } + + @Test + public void testParseArgsWithSpi() { + List values = new ArrayList<>(); + ConfigArgsConfigSource.parseConfigArgs(Arrays.asList("--spi-some-thing-enabled=value", "--spi-some-thing-else", "other-value"), (key, value) -> values.add(key+'='+value), ignored -> {}); + assertEquals(Arrays.asList("--spi-some-thing-enabled=value", "--spi-some-thing-else=other-value"), values); + } } From ee712cc45a5238532285b00eb4691265e8ab5ba7 Mon Sep 17 00:00:00 2001 From: Jon Koops Date: Fri, 26 Jul 2024 12:14:46 +0200 Subject: [PATCH 075/103] don't lazy load when searching (#31100) (#31658) fixes: #31070 Signed-off-by: Erik Jan de Wit (cherry picked from commit 932a92a31688e08a95e174c99e6cc15fcf2cfa14) Co-authored-by: Erik Jan de Wit --- .../src/groups/components/GroupTree.tsx | 30 ++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/js/apps/admin-ui/src/groups/components/GroupTree.tsx b/js/apps/admin-ui/src/groups/components/GroupTree.tsx index 9869dc9edf5..0f1eb7c7480 100644 --- a/js/apps/admin-ui/src/groups/components/GroupTree.tsx +++ b/js/apps/admin-ui/src/groups/components/GroupTree.tsx @@ -148,6 +148,21 @@ type GroupTreeProps = { const SUBGROUP_COUNT = 50; +const TreeLoading = () => { + const { t } = useTranslation(); + return ( + <> + {t("spinnerLoading")} + + ); +}; + +const LOADING_TREE = [ + { + name: , + }, +]; + export const GroupTree = ({ refresh: viewRefresh, canViewDetails, @@ -184,6 +199,7 @@ export const GroupTree = ({ group: GroupRepresentation, refresh: () => void, ): ExtendedTreeViewDataItem => { + const hasSubGroups = group.subGroupCount; return { id: group.id, name: ( @@ -192,16 +208,10 @@ export const GroupTree = ({ ), access: group.access || {}, - children: group.subGroupCount - ? [ - { - name: ( - <> - {t("spinnerLoading")} - - ), - }, - ] + children: hasSubGroups + ? search.length === 0 + ? LOADING_TREE + : group.subGroups?.map((g) => mapGroup(g, refresh)) : undefined, action: (hasAccess("manage-users") || group.access?.manage) && ( From 69642f142728b1e3a16887b1022e13d8b5b2ed61 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Fri, 26 Jul 2024 12:38:27 +0200 Subject: [PATCH 076/103] All CURL commands should check the HTTP response code (#31601) Closes #31598 Signed-off-by: Alexander Schwartz --- .../ansible/roles/aws_ec2/tasks/create-resources.yml | 2 +- .github/scripts/snyk-report.sh | 8 ++++---- distribution/licenses-common/download-license-files.sh | 4 ++-- operator/scripts/install-olm.sh | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/scripts/ansible/roles/aws_ec2/tasks/create-resources.yml b/.github/scripts/ansible/roles/aws_ec2/tasks/create-resources.yml index 65c029c487f..3ce145a605d 100644 --- a/.github/scripts/ansible/roles/aws_ec2/tasks/create-resources.yml +++ b/.github/scripts/ansible/roles/aws_ec2/tasks/create-resources.yml @@ -1,5 +1,5 @@ - name: Get Ansible Control Host's public IP - shell: curl -ks --ipv4 https://ifconfig.me + shell: curl -fks --ipv4 https://ifconfig.me register: control_host_ip no_log: "{{ no_log_sensitive }}" diff --git a/.github/scripts/snyk-report.sh b/.github/scripts/snyk-report.sh index 5630d941074..4c094c6ce31 100755 --- a/.github/scripts/snyk-report.sh +++ b/.github/scripts/snyk-report.sh @@ -14,7 +14,7 @@ check_github_issue_exists() { # Extract the CVE ID local CVE_ID=$(echo "$issue_title" | grep -oE '(CVE-[0-9]{4}-[0-9]{4,7}|SNYK-[A-Z]+-[A-Z0-9]+-[0-9]{4,7})') local search_url="https://api.github.com/search/issues?q=$CVE_ID+is%3Aissue+sort%3Aupdated-desc+repo:$KEYCLOAK_REPO" - local response=$(curl -s -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3+json" "$search_url") + local response=$(curl -f -s -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3+json" "$search_url") local count=$(echo "$response" | jq '.total_count') # Check for bad credentials @@ -52,7 +52,7 @@ create_github_issue() { local api_url="https://api.github.com/repos/$KEYCLOAK_REPO/issues" local data=$(jq -n --arg title "$title" --arg body "$body" --arg branch "backport/$BRANCH_NAME" \ '{title: $title, body: $body, labels: ["status/triage", "kind/cve", "kind/bug", $branch]}') - local response=$(curl -s -w "%{http_code}" -X POST -H "Authorization: token $GITHUB_TOKEN" -H "Content-Type: application/json" -d "$data" "$api_url") + local response=$(curl -f -s -w "%{http_code}" -X POST -H "Authorization: token $GITHUB_TOKEN" -H "Content-Type: application/json" -d "$data" "$api_url") local http_code=$(echo "$response" | tail -n1) if [[ $http_code -eq 201 ]]; then @@ -67,11 +67,11 @@ create_github_issue() { update_github_issue() { local issue_id="$1" local api_url="https://api.github.com/repos/$KEYCLOAK_REPO/issues/$issue_id" - local existing_labels=$(curl -s -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3+json" "$api_url" | jq '.labels | .[].name' | jq -s .) + local existing_labels=$(curl -f -s -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3+json" "$api_url" | jq '.labels | .[].name' | jq -s .) local new_label="backport/$BRANCH_NAME" local updated_labels=$(echo "$existing_labels" | jq --arg new_label "$new_label" '. + [$new_label] | unique') local data=$(jq -n --argjson labels "$updated_labels" '{labels: $labels}') - local response=$(curl -s -w "%{http_code}" -X PATCH -H "Authorization: token $GITHUB_TOKEN" -H "Content-Type: application/json" -d "$data" "$api_url") + local response=$(curl -f -s -w "%{http_code}" -X PATCH -H "Authorization: token $GITHUB_TOKEN" -H "Content-Type: application/json" -d "$data" "$api_url") local http_code=$(echo "$response" | tail -n1) if [[ $http_code -eq 200 ]]; then diff --git a/distribution/licenses-common/download-license-files.sh b/distribution/licenses-common/download-license-files.sh index 1b3089043ec..9e9efddf602 100755 --- a/distribution/licenses-common/download-license-files.sh +++ b/distribution/licenses-common/download-license-files.sh @@ -64,7 +64,7 @@ do # Windows won't like it if : is used as a separator filename="$groupid,$artifactid,$version,$name.txt" echo "$filename" - curl -LsS -o "$output_dir/$filename" "$url" + curl -LfsS -o "$output_dir/$filename" "$url" done xmlstarlet sel -T -t -m "/licenseSummary/others/other/licenses/license" -v "../../description/text()" -o $'\t' -v "name/text()" -o $'\t' -v "url/text()" --nl "$xml" | \ @@ -73,7 +73,7 @@ do # Windows won't like it if : is used as a separator filename="$description,$name.txt" echo "$filename" - curl -LsS -o "$output_dir/$filename" "$url" + curl -LfsS -o "$output_dir/$filename" "$url" done echo "==> Normalizing license line endings" >&2 diff --git a/operator/scripts/install-olm.sh b/operator/scripts/install-olm.sh index 02c3acd31fd..ba945182def 100755 --- a/operator/scripts/install-olm.sh +++ b/operator/scripts/install-olm.sh @@ -2,6 +2,6 @@ set -euxo pipefail mkdir -p /tmp/olm/ -curl -L https://github.com/operator-framework/operator-lifecycle-manager/releases/download/v0.26.0/install.sh -o /tmp/olm/install.sh +curl -f -L https://github.com/operator-framework/operator-lifecycle-manager/releases/download/v0.26.0/install.sh -o /tmp/olm/install.sh chmod +x /tmp/olm/install.sh /tmp/olm/install.sh v0.26.0 From 9273bb519af64ddeba7bd98139776975bd33eaf2 Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Mon, 29 Jul 2024 08:40:49 +0100 Subject: [PATCH 077/103] Backport to remove needless aria-label (#31655) Signed-off-by: Agnieszka Gancarczyk --- .../admin-ui/src/components/table-toolbar/KeycloakDataTable.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/js/apps/admin-ui/src/components/table-toolbar/KeycloakDataTable.tsx b/js/apps/admin-ui/src/components/table-toolbar/KeycloakDataTable.tsx index 55b8cd8fcef..1855963a1f6 100644 --- a/js/apps/admin-ui/src/components/table-toolbar/KeycloakDataTable.tsx +++ b/js/apps/admin-ui/src/components/table-toolbar/KeycloakDataTable.tsx @@ -150,7 +150,6 @@ function DataTable({ {columns.map((column) => ( {t(column.displayKey || column.name)} From b65ec7f2c7931956acc5e52b216228e0f040184d Mon Sep 17 00:00:00 2001 From: Giuseppe Graziano Date: Wed, 24 Jul 2024 17:40:16 +0200 Subject: [PATCH 078/103] Client scope assignment for client registration Closes #31062 Signed-off-by: Giuseppe Graziano (cherry picked from commit 12732333c80db8478aa70556c62e3f71ede44cbd) --- .../AbstractClientRegistrationProvider.java | 4 ++++ .../oidc/DescriptionConverter.java | 5 ++++- .../oidc/OIDCClientRegistrationProvider.java | 10 ++++++++++ .../ClientScopesClientRegistrationPolicy.java | 20 +++++++++++-------- .../client/ClientRegistrationTest.java | 14 ++++++------- .../client/OIDCClientRegistrationTest.java | 14 ++++++++++--- .../OIDCPairwiseClientRegistrationTest.java | 2 +- .../keycloak/testsuite/oauth/par/ParTest.java | 2 +- 8 files changed, 50 insertions(+), 21 deletions(-) diff --git a/services/src/main/java/org/keycloak/services/clientregistration/AbstractClientRegistrationProvider.java b/services/src/main/java/org/keycloak/services/clientregistration/AbstractClientRegistrationProvider.java index caaf1bb0709..8929bbd7ddf 100755 --- a/services/src/main/java/org/keycloak/services/clientregistration/AbstractClientRegistrationProvider.java +++ b/services/src/main/java/org/keycloak/services/clientregistration/AbstractClientRegistrationProvider.java @@ -37,6 +37,7 @@ import org.keycloak.models.RoleModel; import org.keycloak.models.utils.ModelToRepresentation; import org.keycloak.models.utils.RepresentationToModel; +import org.keycloak.protocol.oidc.OIDCLoginProtocolFactory; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.oidc.OIDCClientRepresentation; import org.keycloak.services.ErrorResponseException; @@ -67,6 +68,9 @@ public AbstractClientRegistrationProvider(KeycloakSession session) { public ClientRepresentation create(ClientRegistrationContext context) { ClientRepresentation client = context.getClient(); + if(client.getOptionalClientScopes() != null && client.getDefaultClientScopes() == null) { + client.setDefaultClientScopes(List.of(OIDCLoginProtocolFactory.BASIC_SCOPE)); + } event.event(EventType.CLIENT_REGISTER); diff --git a/services/src/main/java/org/keycloak/services/clientregistration/oidc/DescriptionConverter.java b/services/src/main/java/org/keycloak/services/clientregistration/oidc/DescriptionConverter.java index 951f561d008..30b0b726f99 100755 --- a/services/src/main/java/org/keycloak/services/clientregistration/oidc/DescriptionConverter.java +++ b/services/src/main/java/org/keycloak/services/clientregistration/oidc/DescriptionConverter.java @@ -55,6 +55,7 @@ import java.security.PublicKey; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -82,7 +83,9 @@ public static ClientRepresentation toInternal(KeycloakSession session, OIDCClien client.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL); String scopeParam = clientOIDC.getScope(); - if (scopeParam != null) client.setOptionalClientScopes(new ArrayList<>(Arrays.asList(scopeParam.split(" ")))); + if (scopeParam != null) { + client.setOptionalClientScopes(scopeParam.isEmpty() ? Collections.emptyList() : Arrays.asList(scopeParam.split(" "))); + } List oidcResponseTypes = clientOIDC.getResponseTypes(); if (oidcResponseTypes == null || oidcResponseTypes.isEmpty()) { diff --git a/services/src/main/java/org/keycloak/services/clientregistration/oidc/OIDCClientRegistrationProvider.java b/services/src/main/java/org/keycloak/services/clientregistration/oidc/OIDCClientRegistrationProvider.java index 893b29d98bc..8acf0500aee 100755 --- a/services/src/main/java/org/keycloak/services/clientregistration/oidc/OIDCClientRegistrationProvider.java +++ b/services/src/main/java/org/keycloak/services/clientregistration/oidc/OIDCClientRegistrationProvider.java @@ -29,6 +29,7 @@ import org.keycloak.models.utils.RepresentationToModel; import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper; import org.keycloak.protocol.oidc.OIDCLoginProtocol; +import org.keycloak.protocol.oidc.OIDCLoginProtocolFactory; import org.keycloak.protocol.oidc.mappers.AbstractPairwiseSubMapper; import org.keycloak.protocol.oidc.mappers.PairwiseSubMapperHelper; import org.keycloak.protocol.oidc.mappers.SHA256PairwiseSubMapper; @@ -56,6 +57,8 @@ import org.keycloak.urls.UrlType; import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; @@ -129,6 +132,13 @@ public Response getOIDC(@PathParam("clientId") String clientId) { public Response updateOIDC(@PathParam("clientId") String clientId, OIDCClientRepresentation clientOIDC) { try { ClientRepresentation client = DescriptionConverter.toInternal(session, clientOIDC); + + if (clientOIDC.getScope() != null) { + ClientModel oldClient = session.getContext().getRealm().getClientById(clientOIDC.getClientId()); + Collection defaultClientScopes = oldClient.getClientScopes(true).keySet(); + client.setDefaultClientScopes(new ArrayList<>(defaultClientScopes)); + } + OIDCClientRegistrationContext oidcContext = new OIDCClientRegistrationContext(session, client, this, clientOIDC); client = update(clientId, oidcContext); diff --git a/services/src/main/java/org/keycloak/services/clientregistration/policy/impl/ClientScopesClientRegistrationPolicy.java b/services/src/main/java/org/keycloak/services/clientregistration/policy/impl/ClientScopesClientRegistrationPolicy.java index a9837dc8743..d4356c33b5a 100644 --- a/services/src/main/java/org/keycloak/services/clientregistration/policy/impl/ClientScopesClientRegistrationPolicy.java +++ b/services/src/main/java/org/keycloak/services/clientregistration/policy/impl/ClientScopesClientRegistrationPolicy.java @@ -17,6 +17,7 @@ package org.keycloak.services.clientregistration.policy.impl; +import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; @@ -54,11 +55,13 @@ public void beforeRegister(ClientRegistrationContext context) throws ClientRegis List requestedDefaultScopeNames = context.getClient().getDefaultClientScopes(); List requestedOptionalScopeNames = context.getClient().getOptionalClientScopes(); - List allowedDefaultScopeNames = getAllowedScopeNames(realm, true); - List allowedOptionalScopeNames = getAllowedScopeNames(realm, false); + List allowedScopeNames = new ArrayList<>(); + allowedScopeNames.addAll(getAllowedScopeNames(realm, true)); + allowedScopeNames.addAll(getAllowedScopeNames(realm, false)); - checkClientScopesAllowed(requestedDefaultScopeNames, allowedDefaultScopeNames); - checkClientScopesAllowed(requestedOptionalScopeNames, allowedOptionalScopeNames); + + checkClientScopesAllowed(requestedDefaultScopeNames, allowedScopeNames); + checkClientScopesAllowed(requestedOptionalScopeNames, allowedScopeNames); } @Override @@ -82,11 +85,12 @@ public void beforeUpdate(ClientRegistrationContext context, ClientModel clientMo requestedDefaultScopeNames.removeAll(clientModel.getClientScopes(true).keySet()); requestedOptionalScopeNames.removeAll(clientModel.getClientScopes(false).keySet()); - List allowedDefaultScopeNames = getAllowedScopeNames(realm, true); - List allowedOptionalScopeNames = getAllowedScopeNames(realm, false); + List allowedScopeNames = new ArrayList<>(); + allowedScopeNames.addAll(getAllowedScopeNames(realm, true)); + allowedScopeNames.addAll(getAllowedScopeNames(realm, false)); - checkClientScopesAllowed(requestedDefaultScopeNames, allowedDefaultScopeNames); - checkClientScopesAllowed(requestedOptionalScopeNames, allowedOptionalScopeNames); + checkClientScopesAllowed(requestedDefaultScopeNames, allowedScopeNames); + checkClientScopesAllowed(requestedOptionalScopeNames, allowedScopeNames); } @Override diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRegistrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRegistrationTest.java index 1f8436dee77..4990fe32754 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRegistrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/ClientRegistrationTest.java @@ -32,6 +32,7 @@ import org.keycloak.client.registration.ClientRegistration; import org.keycloak.client.registration.ClientRegistrationException; import org.keycloak.client.registration.HttpErrorException; +import org.keycloak.common.util.CollectionUtil; import org.keycloak.events.Errors; import org.keycloak.models.Constants; import org.keycloak.models.utils.KeycloakModelUtils; @@ -251,27 +252,26 @@ public void updateClientScopes() throws ClientRegistrationException { ClientRepresentation client = buildClient(); ArrayList optionalClientScopes = new ArrayList<>(List.of("address")); client.setOptionalClientScopes(optionalClientScopes); - ClientRepresentation createdClient = registerClient(client); Set requestedClientScopes = new HashSet<>(optionalClientScopes); Set registeredClientScopes = new HashSet<>(createdClient.getOptionalClientScopes()); assertEquals(requestedClientScopes, registeredClientScopes); - assertTrue(createdClient.getDefaultClientScopes().isEmpty()); + assertTrue(CollectionUtil.collectionEquals(createdClient.getDefaultClientScopes(), Set.of("basic"))); authManageClients(); ClientRepresentation obtainedClient = reg.get(CLIENT_ID); registeredClientScopes = new HashSet<>(obtainedClient.getOptionalClientScopes()); assertEquals(requestedClientScopes, registeredClientScopes); - assertTrue(obtainedClient.getDefaultClientScopes().isEmpty()); + assertTrue(CollectionUtil.collectionEquals(obtainedClient.getDefaultClientScopes(), Set.of("basic"))); optionalClientScopes = new ArrayList<>(List.of("address", "phone")); - client.setOptionalClientScopes(optionalClientScopes); - ClientRepresentation updatedClient = reg.update(client); + obtainedClient.setOptionalClientScopes(optionalClientScopes); + ClientRepresentation updatedClient = reg.update(obtainedClient); requestedClientScopes = new HashSet<>(optionalClientScopes); registeredClientScopes = new HashSet<>(updatedClient.getOptionalClientScopes()); assertEquals(requestedClientScopes, registeredClientScopes); - assertTrue(updatedClient.getDefaultClientScopes().isEmpty()); + assertTrue(CollectionUtil.collectionEquals(updatedClient.getDefaultClientScopes(), Set.of("basic"))); } @Test @@ -730,7 +730,7 @@ public void registerClientAsAdminWithScope() throws ClientRegistrationException Set requestedClientScopes = new HashSet<>(optionalClientScopes); Set registeredClientScopes = new HashSet<>(client.getOptionalClientScopes()); assertTrue(requestedClientScopes.equals(registeredClientScopes)); - assertTrue(client.getDefaultClientScopes().isEmpty()); + assertTrue(CollectionUtil.collectionEquals(client.getDefaultClientScopes(), Set.of("basic"))); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationTest.java index 8e3ba20f330..2d27f8939bd 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCClientRegistrationTest.java @@ -40,6 +40,7 @@ import org.keycloak.representations.idm.ClientInitialAccessPresentation; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.RealmRepresentation; +import org.keycloak.representations.idm.ClientScopeRepresentation; import org.keycloak.representations.oidc.OIDCClientRepresentation; import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.admin.ApiUtil; @@ -179,19 +180,27 @@ public void getClient() throws ClientRegistrationException { @Test public void updateClient() throws ClientRegistrationException { + Set realmDefaultClientScopes = adminClient.realm(REALM_NAME).getDefaultDefaultClientScopes().stream() + .filter(scope -> Objects.equals(scope.getProtocol(), OIDCLoginProtocol.LOGIN_PROTOCOL)) + .map(ClientScopeRepresentation::getName).collect(Collectors.toSet()); + OIDCClientRepresentation response = create(); reg.auth(Auth.token(response)); response.setRedirectUris(Collections.singletonList("http://newredirect")); response.setResponseTypes(Arrays.asList("code", "id_token token", "code id_token token")); response.setGrantTypes(Arrays.asList(OAuth2Constants.AUTHORIZATION_CODE, OAuth2Constants.REFRESH_TOKEN, OAuth2Constants.PASSWORD)); - OIDCClientRepresentation updated = reg.oidc().update(response); + ClientResource clientResource = adminClient.realm(REALM_NAME).clients().get(response.getClientId()); + ClientRepresentation rep = clientResource.toRepresentation(); + Set registeredDefaultClientScopes = new HashSet<>(rep.getDefaultClientScopes()); + assertEquals(AUTH_SERVER_ROOT + "/realms/" + REALM_NAME + "/clients-registrations/openid-connect/" + updated.getClientId(), updated.getRegistrationClientUri()); assertTrue(CollectionUtil.collectionEquals(Collections.singletonList("http://newredirect"), updated.getRedirectUris())); assertTrue(CollectionUtil.collectionEquals(Arrays.asList(OAuth2Constants.AUTHORIZATION_CODE, OAuth2Constants.IMPLICIT, OAuth2Constants.REFRESH_TOKEN, OAuth2Constants.PASSWORD), updated.getGrantTypes())); assertTrue(CollectionUtil.collectionEquals(Arrays.asList(OAuth2Constants.CODE, OIDCResponseType.NONE, OIDCResponseType.ID_TOKEN, "id_token token", "code id_token", "code token", "code id_token token"), updated.getResponseTypes())); + assertTrue(CollectionUtil.collectionEquals(realmDefaultClientScopes, registeredDefaultClientScopes)); } @Test @@ -743,8 +752,7 @@ public void testClientWithScope() throws Exception { assertTrue(clientScopes.equals(registeredClientScopes)); ClientResource clientResource = adminClient.realm(REALM_NAME).clients().get(response.getClientId()); - assertTrue(clientResource.toRepresentation().getDefaultClientScopes().isEmpty()); - + assertTrue(CollectionUtil.collectionEquals(clientResource.toRepresentation().getDefaultClientScopes(), Set.of("basic"))); } @Test diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCPairwiseClientRegistrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCPairwiseClientRegistrationTest.java index 59fd747fd01..860b4d17483 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCPairwiseClientRegistrationTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/client/OIDCPairwiseClientRegistrationTest.java @@ -508,4 +508,4 @@ public void removeDefaultBasicClientScope(String clientId) { ApiUtil.findClientResourceByClientId(adminClient.realm(REALM_NAME), clientId).removeDefaultClientScope(scope.getId()); }); } -} \ No newline at end of file +} diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParTest.java index ca53bdb944b..a3a8fc905c5 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oauth/par/ParTest.java @@ -1334,4 +1334,4 @@ private static void assertNotCors(CloseableHttpResponse response) { assertEquals(0, response.getHeaders("Access-Control-Expose-Headers").length); } -} \ No newline at end of file +} From 89ad2e6b1708e43a320d0cbc24601839be970f34 Mon Sep 17 00:00:00 2001 From: Marek Posolda Date: Tue, 30 Jul 2024 10:05:14 +0200 Subject: [PATCH 079/103] Documentation for Delete Credential action and related changes (#31719) closes #31718 Signed-off-by: mposolda Signed-off-by: Marek Posolda Co-authored-by: andymunro <48995441+andymunro@users.noreply.github.com> (cherry picked from commit 5b521173518a80b9ce87ae8fd48bb13e86a657ca) --- .../login-settings/update-email-workflow.adoc | 2 +- .../server_admin/topics/users/con-aia.adoc | 21 +++++++++++++++++-- .../topics/users/con-required-actions.adoc | 6 +++++- .../topics/changes/changes-24_0_3.adoc | 5 +++++ 4 files changed, 30 insertions(+), 4 deletions(-) diff --git a/docs/documentation/server_admin/topics/login-settings/update-email-workflow.adoc b/docs/documentation/server_admin/topics/login-settings/update-email-workflow.adoc index 836fa6f4ce2..c884bf12b66 100644 --- a/docs/documentation/server_admin/topics/login-settings/update-email-workflow.adoc +++ b/docs/documentation/server_admin/topics/login-settings/update-email-workflow.adoc @@ -6,7 +6,7 @@ With this workflow, users will have to use an UPDATE_EMAIL action to change thei The action is associated with a single email input form. If the realm has email verification disabled, this action will allow to update the email without verification. If the realm has email verification enabled, the action will send an email update action token to the new email address without changing the account email. Only the action token triggering will complete the email update. -Applications are able to send their users to the email update form by leveraging UPDATE_EMAIL as an AIA (Application Initiated Action). +Applications are able to send their users to the email update form by leveraging UPDATE_EMAIL as an <>. :tech_feature_name: UpdateEmail :tech_feature_id: update-email diff --git a/docs/documentation/server_admin/topics/users/con-aia.adoc b/docs/documentation/server_admin/topics/users/con-aia.adoc index a2077b7b2db..e2b6fa8f4ab 100644 --- a/docs/documentation/server_admin/topics/users/con-aia.adoc +++ b/docs/documentation/server_admin/topics/users/con-aia.adoc @@ -39,18 +39,35 @@ by checking the claims like `acr` in the tokens. [id="con-aia-reauth_{context}"] == Re-authentication during AIA -In case the user is already authenticated due to an active SSO session, that user usually does not need to actively re-authenticate. However, if that user actively authenticated longer than five minutes ago, +In case the user is already authenticated due to an active SSO session, that user usually does not need to actively re-authenticate. However, if that user actively authenticated longer than five minutes ago, the client can still request re-authentication when some AIA is requested. Exceptions exist from this guideline as follows: * The action `delete_account` will always require the user to actively re-authenticate * The action `update_password` might require the user to actively re-authenticate according to the configured <>. -In case the policy is not configured, it also defaults to five minutes. +In case the policy is not configured, it is also possible to configure it on the required action itself in the <> +when configuring the particular required action. If the policy is not configured in any of those places, it defaults to five minutes. * If you want to use a shorter re-authentication, you can still use a parameter query parameter such as `max_age` with the specified shorter value or eventually `prompt=login`, which will always require user to actively re-authenticate as described in the OIDC specification. Note that using `max_age` for a longer value than the default five minutes (or the one prescribed by password policy) is not supported. The `max_age` can be currently used only to make the value shorter than the default five minutes. +* If <<_step-up-flow,Step-up authentication>> is enabled and the action is to add or delete a credential, authentication is required with the level corresponding +to the given credential. This requirement exists in case the user already has the credential of the particular level. For example, if `otp` and `webauthn` are configured in the authentication flow as 2nd-factor authenticators +(both in the authentication flow at level 2) and the user already has a 2nd-factor credential (`otp` or `webauthn` in this case), the user is required to authenticate with an existing 2nd-factor credential to add another 2nd-level credential. +In the same manner, deleting an existing 2nd-factor credential (`otp` or `webauthn` in this case), authentication with an existing 2nd-factor level credential is required. The requirement exists for security reasons. + +[id="con-aia-parameterized_{context}"] +== Parameterized AIA + +Some AIA can require the parameter to be sent together with the action name. For instance, the `Delete Credential` action can be triggered only by AIA and it requires a parameter to be sent together with the name +of the action, which points to the ID of the removed credential. So the URL for this example would be `kc_action=delete_credential:ce1008ac-f811-427f-825a-c0b878d1c24b`. In this case, the +part after the colon character (`ce1008ac-f811-427f-825a-c0b878d1c24b`) contains the ID of the credential of the particular user, which is to be deleted. The `Delete Credential` action +displays the confirmation screen where the user can confirm agreement to delete the credential. + +NOTE: The <<_account-service,{project_name} Account Console>> typically uses the `Delete Credential` action when deleting a 2nd-factor credential. You can check the Account Console for examples if you want +to use this action directly from your own applications. However, relying on the Account Console is best instead of managing credentials from your own applications. + [id="con-aia-available-actions_{context}"] == Available actions diff --git a/docs/documentation/server_admin/topics/users/con-required-actions.adoc b/docs/documentation/server_admin/topics/users/con-required-actions.adoc index c3cbf38f332..ff6c33a99f6 100644 --- a/docs/documentation/server_admin/topics/users/con-required-actions.adoc +++ b/docs/documentation/server_admin/topics/users/con-required-actions.adoc @@ -13,7 +13,7 @@ action can require the user to update the <> as long The following are examples of required action types: -Update Password:: +Update Password:: The user must change their password. Configure OTP:: @@ -25,3 +25,7 @@ Verify Email:: Update Profile:: The user must update profile information, such as name, address, email, and phone number. +NOTE: Some actions do not makes sense to be added to the user account directly. For example, the `Update User Locale` is a helper action to handle some localization related parameters. Another +example is the `Delete Credential` action, which is supposed to be triggered as a <>. Regarding this one, if the administrator wants to delete the credential of some +user, that administrator can do it directly in the Admin Console. The `Delete Credential` action is dedicated to be used for example by the <<_account-service,{project_name} Account Console>>. + diff --git a/docs/documentation/upgrading/topics/changes/changes-24_0_3.adoc b/docs/documentation/upgrading/topics/changes/changes-24_0_3.adoc index 9dcfc982302..85792dc5514 100644 --- a/docs/documentation/upgrading/topics/changes/changes-24_0_3.adoc +++ b/docs/documentation/upgrading/topics/changes/changes-24_0_3.adoc @@ -22,3 +22,8 @@ Because of security concerns, the redirect URI verification now performs a exact The full wildcard `*` can still be used as a valid redirect in development for http(s) URIs with those characteristics. In production environments a exact valid redirect URI without wildcard needs to be configured for any URI of that type. Please note that wildcard valid redirect URIs are not recommended for production and not covered by the OAuth 2.0 specification. + += Deprecated Account REST endpoint for removing credential + +The Account REST endpoint for removing the credential of the user is deprecated. Starting at this version, the Account Console no longer uses this endpoint. It is replaced by the `Delete Credential` application-initiated +action, which is triggered by the Account Console when a user want to remove the credential of a user. From 213063bed1dc417b2b1fe607714d464d5e3b9386 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Tue, 30 Jul 2024 14:58:32 +0200 Subject: [PATCH 080/103] Trigger clearing the user cache when the duplicate email allowed flag changes (#31722) Closes #31045 Signed-off-by: Alexander Schwartz --- .../InfinispanUserCacheProviderFactory.java | 12 +--- .../models/cache/infinispan/RealmAdapter.java | 60 ++++++++++++++++--- .../resources/admin/RealmAdminResource.java | 6 -- 3 files changed, 53 insertions(+), 25 deletions(-) diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanUserCacheProviderFactory.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanUserCacheProviderFactory.java index 6ed60570f28..24723cd9242 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanUserCacheProviderFactory.java +++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanUserCacheProviderFactory.java @@ -29,12 +29,11 @@ import org.keycloak.models.cache.UserCacheProviderFactory; import org.keycloak.models.cache.infinispan.entities.Revisioned; import org.keycloak.models.cache.infinispan.events.InvalidationEvent; -import org.keycloak.provider.InvalidationHandler; /** * @author Stian Thorgersen */ -public class InfinispanUserCacheProviderFactory implements UserCacheProviderFactory, InvalidationHandler { +public class InfinispanUserCacheProviderFactory implements UserCacheProviderFactory { private static final Logger log = Logger.getLogger(InfinispanUserCacheProviderFactory.class); public static final String USER_CLEAR_CACHE_EVENTS = "USER_CLEAR_CACHE_EVENTS"; @@ -79,15 +78,6 @@ private void lazyInit(KeycloakSession session) { } } - @Override - public void invalidate(KeycloakSession session, InvalidableObjectType type, Object... params) { - if (type == ObjectType.REALM || type == ObjectType.USER) { - if (this.userCache != null) { - this.userCache.clear(); - } - } - } - @Override public void init(Config.Scope config) { } diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java index eb17b8f8a0d..7ea0e5daa0a 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java +++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java @@ -18,9 +18,32 @@ package org.keycloak.models.cache.infinispan; import org.keycloak.Config; +import org.keycloak.cluster.ClusterProvider; import org.keycloak.common.enums.SslRequired; import org.keycloak.component.ComponentModel; -import org.keycloak.models.*; +import org.keycloak.models.AbstractKeycloakTransaction; +import org.keycloak.models.AuthenticationExecutionModel; +import org.keycloak.models.AuthenticationFlowModel; +import org.keycloak.models.AuthenticatorConfigModel; +import org.keycloak.models.CibaConfig; +import org.keycloak.models.ClientInitialAccessModel; +import org.keycloak.models.ClientModel; +import org.keycloak.models.ClientScopeModel; +import org.keycloak.models.GroupModel; +import org.keycloak.models.IdentityProviderMapperModel; +import org.keycloak.models.IdentityProviderModel; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.OAuth2DeviceConfig; +import org.keycloak.models.OTPPolicy; +import org.keycloak.models.OrganizationModel; +import org.keycloak.models.ParConfig; +import org.keycloak.models.PasswordPolicy; +import org.keycloak.models.RealmModel; +import org.keycloak.models.RequiredActionConfigModel; +import org.keycloak.models.RequiredActionProviderModel; +import org.keycloak.models.RequiredCredentialModel; +import org.keycloak.models.RoleModel; +import org.keycloak.models.WebAuthnPolicy; import org.keycloak.models.cache.CachedRealmModel; import org.keycloak.models.cache.UserCache; import org.keycloak.models.cache.infinispan.entities.CachedRealm; @@ -28,7 +51,12 @@ import org.keycloak.storage.UserStorageUtil; import org.keycloak.storage.client.ClientStorageProvider; -import java.util.*; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; import java.util.stream.Stream; @@ -362,6 +390,22 @@ public boolean isDuplicateEmailsAllowed() { @Override public void setDuplicateEmailsAllowed(boolean duplicateEmailsAllowed) { getDelegateForUpdate(); + if (updated.isDuplicateEmailsAllowed() != duplicateEmailsAllowed) { + // If the flag changed, we need to clear all entries from the user cache as there are entries with the key of the email address which need to be re-evaluated. + // Still, this must only happen after all changes have been written to the database, therefore we enlist this to run after the completion of the transaction. + session.getTransactionManager().enlistAfterCompletion(new AbstractKeycloakTransaction() { + @Override + protected void commitImpl() { + ClusterProvider cluster = session.getProvider(ClusterProvider.class); + cluster.notify(InfinispanUserCacheProviderFactory.USER_CLEAR_CACHE_EVENTS, new ClearCacheEvent(), false, ClusterProvider.DCNotify.ALL_DCS); + } + + @Override + protected void rollbackImpl() { + + } + }); + } updated.setDuplicateEmailsAllowed(duplicateEmailsAllowed); } @@ -1074,7 +1118,7 @@ public RoleModel getRole(String name) { public Stream getRolesStream() { return cacheSession.getRealmRolesStream(this); } - + @Override public Stream getRolesStream(Integer first, Integer max) { return cacheSession.getRealmRolesStream(this, first, max); @@ -1084,7 +1128,7 @@ public Stream getRolesStream(Integer first, Integer max) { public Stream searchForRolesStream(String search, Integer first, Integer max) { return cacheSession.searchForRolesStream(this, search, first, max); } - + @Override public RoleModel addRole(String name) { return cacheSession.addRealmRole(this, name); @@ -1601,10 +1645,10 @@ public ComponentModel importComponentModel(ComponentModel model) { public void executeEvictions(ComponentModel model) { if (model == null) return; - + // if user cache is disabled this is null UserCache userCache = UserStorageUtil.userCache(session); - if (userCache != null) { + if (userCache != null) { // If not realm component, check to see if it is a user storage provider child component (i.e. LDAP mapper) if (model.getParentId() != null && !model.getParentId().equals(getId())) { ComponentModel parent = getComponent(model.getParentId()); @@ -1613,13 +1657,13 @@ public void executeEvictions(ComponentModel model) { } return; } - + // invalidate entire user cache if we're dealing with user storage SPI if (UserStorageProvider.class.getName().equals(model.getProviderType())) { userCache.evict(this); } } - + // invalidate entire realm if we're dealing with client storage SPI // entire realm because of client roles, client lists, and clients if (ClientStorageProvider.class.getName().equals(model.getProviderType())) { diff --git a/services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java b/services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java index 17ac2468017..36e617c7a47 100644 --- a/services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java @@ -95,7 +95,6 @@ import org.keycloak.partialimport.ErrorResponseException; import org.keycloak.partialimport.PartialImportResult; import org.keycloak.partialimport.PartialImportResults; -import org.keycloak.provider.InvalidationHandler; import org.keycloak.representations.adapters.action.GlobalRequestResult; import org.keycloak.representations.idm.AdminEventRepresentation; import org.keycloak.representations.idm.ClientRepresentation; @@ -446,7 +445,6 @@ public Response updateRealm(final RealmRepresentation rep) { } } - boolean wasDuplicateEmailsAllowed = realm.isDuplicateEmailsAllowed(); RepresentationToModel.updateRealm(rep, realm, session); // Refresh periodic sync tasks for configured federationProviders @@ -457,10 +455,6 @@ public Response updateRealm(final RealmRepresentation rep) { adminEvent.operation(OperationType.UPDATE).representation(rep).success(); - if (rep.isDuplicateEmailsAllowed() != null && rep.isDuplicateEmailsAllowed() != wasDuplicateEmailsAllowed) { - session.invalidate(InvalidationHandler.ObjectType.REALM, realm.getId()); - } - return Response.noContent().build(); } catch (ModelDuplicateException e) { throw ErrorResponse.exists("Realm with same name exists"); From 10aaa67d1a3246073d9428a27f08b630d4df8edd Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Wed, 31 Jul 2024 12:00:23 +0200 Subject: [PATCH 081/103] For persistent sessions, don't remove user session if there is no session in the remote store (#31787) Closes #31115 Signed-off-by: Alexander Schwartz --- ...nispanUserLoginFailureProviderFactory.java | 2 +- .../InfinispanUserSessionProviderFactory.java | 10 +++- .../PersistentUserSessionProvider.java | 49 ++----------------- .../ClientListenerExecutorDecorator.java | 7 ++- .../RemoteCacheSessionListener.java | 17 +++++-- .../managers/UserSessionCrossDCManager.java | 5 +- 6 files changed, 34 insertions(+), 56 deletions(-) diff --git a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserLoginFailureProviderFactory.java b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserLoginFailureProviderFactory.java index 79b16bb9d02..688f401b384 100644 --- a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserLoginFailureProviderFactory.java +++ b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserLoginFailureProviderFactory.java @@ -161,7 +161,7 @@ private RemoteCache checkRemoteCache(KeycloakSessio remoteCacheInvoker.addRemoteCache(ispnCache.getName(), remoteCache, maxIdleLoader); - RemoteCacheSessionListener hotrodListener = RemoteCacheSessionListener.createListener(session, ispnCache, remoteCache, lifespanMsLoader, maxIdleTimeMsLoader); + RemoteCacheSessionListener hotrodListener = RemoteCacheSessionListener.createListener(session, ispnCache, remoteCache, lifespanMsLoader, maxIdleTimeMsLoader, null); remoteCache.addClientListener(hotrodListener); return remoteCache; } diff --git a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserSessionProviderFactory.java b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserSessionProviderFactory.java index f6246ccbd2e..63d07440475 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserSessionProviderFactory.java +++ b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserSessionProviderFactory.java @@ -340,7 +340,15 @@ private RemoteCache checkRemoteCache(KeycloakSessio remoteCacheInvoker.addRemoteCache(ispnCache.getName(), remoteCache, maxIdleLoader); - RemoteCacheSessionListener hotrodListener = RemoteCacheSessionListener.createListener(session, ispnCache, remoteCache, lifespanMsLoader, maxIdleTimeMsLoader); + Runnable onFailover = null; + if (Profile.isFeatureEnabled(Profile.Feature.PERSISTENT_USER_SESSIONS)) { + // If persistent sessions are enabled, we want to clear the local caches when a failover of the listener on the remote store changes as we might have missed some of the remote store events + // which might have been triggered by another Keycloak site connected to the same remote Infinispan cluster. + // Due to this, we can be sure that we never have outdated information in our local cache. All entries will be re-loaded from the remote cache or the database as necessary lazily. + onFailover = ispnCache::clear; + } + + RemoteCacheSessionListener hotrodListener = RemoteCacheSessionListener.createListener(session, ispnCache, remoteCache, lifespanMsLoader, maxIdleTimeMsLoader, onFailover); remoteCache.addClientListener(hotrodListener); return remoteCache; } diff --git a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/PersistentUserSessionProvider.java b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/PersistentUserSessionProvider.java index bb6f499d79e..af1ff90c04b 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/PersistentUserSessionProvider.java +++ b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/PersistentUserSessionProvider.java @@ -23,7 +23,6 @@ import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.infinispan.commons.api.BasicCache; import org.infinispan.commons.util.ByRef; -import org.infinispan.context.Flag; import org.infinispan.factories.ComponentRegistry; import org.infinispan.persistence.manager.PersistenceManager; import org.jboss.logging.Logger; @@ -422,51 +421,9 @@ public UserSessionModel getUserSessionWithPredicate(RealmModel realm, String id, return userSession; } - // Try lookup userSession from remoteCache - Cache> cache = getCache(offline); - RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache); - - if (remoteCache != null) { - SessionEntityWrapper remoteSessionEntityWrapper = (SessionEntityWrapper) remoteCache.get(id); - if (remoteSessionEntityWrapper != null) { - UserSessionEntity remoteSessionEntity = remoteSessionEntityWrapper.getEntity(); - remoteSessionEntity.setOffline(offline); - log.debugf("getUserSessionWithPredicate(%s): remote cache contains session entity %s", id, remoteSessionEntity); - - UserSessionModel remoteSessionAdapter = wrap(realm, remoteSessionEntity, offline); - if (predicate.test(remoteSessionAdapter)) { - - // Remote entity contains our predicate. Update local cache with the remote entity - SessionEntityWrapper sessionWrapper = remoteSessionEntity.mergeRemoteEntityWithLocalEntity(sessionTx.get(id, offline)); - - // Replace entity just in ispn cache. Skip remoteStore - cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_STORE, Flag.SKIP_CACHE_LOAD, Flag.IGNORE_RETURN_VALUES) - .replace(id, sessionWrapper); - - sessionTx.reloadEntityInCurrentTransaction(realm, id, sessionWrapper); - - // Recursion. We should have it locally now - return getUserSessionWithPredicate(realm, id, offline, predicate); - } else { - log.debugf("getUserSessionWithPredicate(%s): found, but predicate doesn't pass", id); - - return null; - } - } else { - log.debugf("getUserSessionWithPredicate(%s): not found", id); - - // Session not available on remoteCache. Was already removed there. So removing locally too. - // TODO: Can be optimized to skip calling remoteCache.remove - removeUserSession(realm, userSession); - - return null; - } - } else { - - log.debugf("getUserSessionWithPredicate(%s): remote cache not available", id); - - return null; - } + // The logic to remove the local entry if there is no entry in the remote cache that is present in the InfinispanUserSessionProvider is removed here, + // as with persistent sessions we will have only a subset of all sessions in memory (both locally and in the remote store). + return null; } diff --git a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/remotestore/ClientListenerExecutorDecorator.java b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/remotestore/ClientListenerExecutorDecorator.java index f8912c0ce45..1e739cb800f 100644 --- a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/remotestore/ClientListenerExecutorDecorator.java +++ b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/remotestore/ClientListenerExecutorDecorator.java @@ -26,6 +26,7 @@ import org.infinispan.client.hotrod.event.ClientCacheEntryCreatedEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryModifiedEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryRemovedEvent; +import org.infinispan.client.hotrod.event.ClientCacheFailoverEvent; import org.infinispan.client.hotrod.event.ClientEvent; import org.jboss.logging.Logger; import org.keycloak.common.util.MultivaluedHashMap; @@ -59,7 +60,11 @@ public ClientListenerExecutorDecorator(ExecutorService decorated) { } - // Explicitly use 3 submit methods to ensure that different type of ClientEvent is not used + // Use explicit submit methods to ensure that different type of ClientEvent is not used + + public void submit(ClientCacheFailoverEvent clientCacheFailoverEvent, Runnable r) { + decorated.submit(r); + } public void submit(ClientCacheEntryCreatedEvent cacheEntryCreatedEvent, Runnable r) { MyClientEvent event = convertIspnClientEvent(cacheEntryCreatedEvent); diff --git a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/remotestore/RemoteCacheSessionListener.java b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/remotestore/RemoteCacheSessionListener.java index 82b02dde8c7..84cdaed988e 100644 --- a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/remotestore/RemoteCacheSessionListener.java +++ b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/remotestore/RemoteCacheSessionListener.java @@ -28,10 +28,12 @@ import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated; import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified; import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved; +import org.infinispan.client.hotrod.annotation.ClientCacheFailover; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.event.ClientCacheEntryCreatedEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryModifiedEvent; import org.infinispan.client.hotrod.event.ClientCacheEntryRemovedEvent; +import org.infinispan.client.hotrod.event.ClientCacheFailoverEvent; import org.infinispan.client.hotrod.event.ClientEvent; import org.infinispan.context.Flag; import org.jboss.logging.Logger; @@ -57,6 +59,7 @@ public class RemoteCacheSessionListener { protected static final Logger logger = Logger.getLogger(RemoteCacheSessionListener.class); private static final int MAXIMUM_REPLACE_RETRIES = 10; + private final Runnable onFailover; private Cache> cache; private RemoteCache> remoteCache; @@ -67,7 +70,8 @@ public class RemoteCacheSessionListener { private KeycloakSessionFactory sessionFactory; - protected RemoteCacheSessionListener() { + protected RemoteCacheSessionListener(Runnable onFailover) { + this.onFailover = onFailover; } @@ -103,6 +107,13 @@ public void created(ClientCacheEntryCreatedEvent event) { } } + @ClientCacheFailover + public void cacheFailover(ClientCacheFailoverEvent event) { + if (onFailover != null) { + this.executor.submit(event, onFailover); + } + } + @ClientCacheEntryModified public void updated(ClientCacheEntryModifiedEvent event) { @@ -250,7 +261,7 @@ protected boolean shouldUpdateLocalCache(ClientEvent.Type type, K key, boolean c } public static RemoteCacheSessionListener createListener(KeycloakSession session, Cache> cache, RemoteCache> remoteCache, - SessionFunction lifespanMsLoader, SessionFunction maxIdleTimeMsLoader) { + SessionFunction lifespanMsLoader, SessionFunction maxIdleTimeMsLoader, Runnable onFailover) { /*boolean isCoordinator = InfinispanUtil.isCoordinator(cache); // Just cluster coordinator will fetch userSessions from remote cache. @@ -264,7 +275,7 @@ public static RemoteCacheSessionListener createList listener = new DontFetchInitialStateCacheListener(); }*/ - RemoteCacheSessionListener listener = new RemoteCacheSessionListener<>(); + RemoteCacheSessionListener listener = new RemoteCacheSessionListener<>(onFailover); listener.init(session, cache, remoteCache, lifespanMsLoader, maxIdleTimeMsLoader); return listener; diff --git a/services/src/main/java/org/keycloak/services/managers/UserSessionCrossDCManager.java b/services/src/main/java/org/keycloak/services/managers/UserSessionCrossDCManager.java index 6d50cd5a77b..32ad1969bfe 100644 --- a/services/src/main/java/org/keycloak/services/managers/UserSessionCrossDCManager.java +++ b/services/src/main/java/org/keycloak/services/managers/UserSessionCrossDCManager.java @@ -17,10 +17,6 @@ package org.keycloak.services.managers; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - import org.jboss.logging.Logger; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; @@ -87,6 +83,7 @@ public UserSessionModel getUserSessionIfExistsRemotely(AuthenticationSessionMana AuthSessionId authSessionId = asm.decodeAuthSessionId(oldEncodedId); String sessionId = authSessionId.getDecodedId(); + // TODO: remove this code once InfinispanUserSessionProvider is removed or no longer using any remote caches, as other implementations don't need this call. // This will remove userSession "locally" if it doesn't exist on remoteCache kcSession.sessions().getUserSessionWithPredicate(realm, sessionId, false, (UserSessionModel userSession2) -> userSession2 == null); From 1f35877a107cf0855f0be4514b323f8b9fd0e867 Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Wed, 31 Jul 2024 13:50:19 +0100 Subject: [PATCH 082/103] Backport to make realm the namespace so we can change the bundle (#31666) * Backport to make realm the namespace so we can change the bundle Signed-off-by: Agnieszka Gancarczyk * fix Signed-off-by: Agnieszka Gancarczyk --------- Signed-off-by: Agnieszka Gancarczyk --- .../src/context/realm-context/RealmContext.tsx | 15 +++++++++++---- js/apps/admin-ui/src/i18n/i18n.ts | 4 +++- .../localization/RealmOverrides.tsx | 2 +- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/js/apps/admin-ui/src/context/realm-context/RealmContext.tsx b/js/apps/admin-ui/src/context/realm-context/RealmContext.tsx index 7faf4d3116b..6e6e93ea071 100644 --- a/js/apps/admin-ui/src/context/realm-context/RealmContext.tsx +++ b/js/apps/admin-ui/src/context/realm-context/RealmContext.tsx @@ -1,14 +1,15 @@ -import { PropsWithChildren, useEffect, useMemo, useState } from "react"; -import { useMatch } from "react-router-dom"; +import RealmRepresentation from "@keycloak/keycloak-admin-client/lib/defs/realmRepresentation"; import { createNamedContext, useEnvironment, useRequiredContext, } from "@keycloak/keycloak-ui-shared"; +import { PropsWithChildren, useEffect, useMemo, useState } from "react"; +import { useMatch } from "react-router-dom"; import { useAdminClient } from "../../admin-client"; import { DashboardRouteWithRealm } from "../../dashboard/routes/Dashboard"; -import RealmRepresentation from "@keycloak/keycloak-admin-client/lib/defs/realmRepresentation"; import { useFetch } from "../../utils/useFetch"; +import { i18n } from "../../i18n/i18n"; type RealmContextType = { realm: string; @@ -41,7 +42,13 @@ export const RealmContextProvider = ({ children }: PropsWithChildren) => { ); // Configure admin client to use selected realm when it changes. - useEffect(() => adminClient.setConfig({ realmName: realm }), [realm]); + useEffect(() => { + (async () => { + adminClient.setConfig({ realmName: realm }); + await i18n.loadNamespaces(realm); + i18n.setDefaultNamespace(realm); + })(); + }, [realm]); useFetch( () => adminClient.realms.findOne({ realm }), setRealmRepresentation, diff --git a/js/apps/admin-ui/src/i18n/i18n.ts b/js/apps/admin-ui/src/i18n/i18n.ts index 98dcae643c3..ba95391f22c 100644 --- a/js/apps/admin-ui/src/i18n/i18n.ts +++ b/js/apps/admin-ui/src/i18n/i18n.ts @@ -16,10 +16,12 @@ export const i18n = createInstance({ interpolation: { escapeValue: false, }, + defaultNS: [environment.realm], + ns: [environment.realm], backend: { loadPath: joinPath( environment.adminBaseUrl, - `resources/${environment.realm}/admin/{{lng}}`, + `resources/{{ns}}/admin/{{lng}}`, ), parse: (data: string) => { const messages = JSON.parse(data); diff --git a/js/apps/admin-ui/src/realm-settings/localization/RealmOverrides.tsx b/js/apps/admin-ui/src/realm-settings/localization/RealmOverrides.tsx index f5c2ce72fd2..ac4fa5d645b 100644 --- a/js/apps/admin-ui/src/realm-settings/localization/RealmOverrides.tsx +++ b/js/apps/admin-ui/src/realm-settings/localization/RealmOverrides.tsx @@ -241,7 +241,7 @@ export const RealmOverrides = ({ try { for (const key of selectedRowKeys) { delete ( - i18n.store.data[whoAmI.getLocale()]["translation"] as Record< + i18n.store.data[whoAmI.getLocale()][currentRealm] as Record< string, string > From 9aef33f5be62f6265d4230d6f678c520f46de5a6 Mon Sep 17 00:00:00 2001 From: agagancarczyk <4890675+agagancarczyk@users.noreply.github.com> Date: Tue, 6 Aug 2024 12:16:04 +0100 Subject: [PATCH 083/103] Backport to revert accidental change to logout url (#31933) Signed-off-by: Agnieszka Gancarczyk --- .../admin-ui/src/identity-providers/add/DescriptorSettings.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/js/apps/admin-ui/src/identity-providers/add/DescriptorSettings.tsx b/js/apps/admin-ui/src/identity-providers/add/DescriptorSettings.tsx index d8d3a6f7cac..0cdc41b84b9 100644 --- a/js/apps/admin-ui/src/identity-providers/add/DescriptorSettings.tsx +++ b/js/apps/admin-ui/src/identity-providers/add/DescriptorSettings.tsx @@ -77,7 +77,6 @@ const Fields = ({ readOnly }: DescriptorSettingsProps) => { labelIcon={t("singleLogoutServiceUrlHelp")} type="url" readOnly={readOnly} - rules={{ required: t("required") }} /> Date: Tue, 6 Aug 2024 13:46:33 +0200 Subject: [PATCH 084/103] disable save when all fields are readonly (#31535) (#31765) fixes: #31304 Signed-off-by: Erik Jan de Wit (cherry picked from commit 814e958e1184874b591ff037458fe57ddb8dea26) --- .../src/personal-info/PersonalInfo.tsx | 43 +++++++++++-------- 1 file changed, 25 insertions(+), 18 deletions(-) diff --git a/js/apps/account-ui/src/personal-info/PersonalInfo.tsx b/js/apps/account-ui/src/personal-info/PersonalInfo.tsx index c176f5c5b37..5bcfaa9eed3 100644 --- a/js/apps/account-ui/src/personal-info/PersonalInfo.tsx +++ b/js/apps/account-ui/src/personal-info/PersonalInfo.tsx @@ -93,6 +93,11 @@ export const PersonalInfo = () => { return ; } + const allFieldsReadOnly = () => + userProfileMetadata?.attributes + ?.map((a) => a.readOnly) + .reduce((p, c) => p && c, true); + const { updateEmailFeatureEnabled, updateEmailActionEnabled, @@ -130,24 +135,26 @@ export const PersonalInfo = () => { ) : undefined } /> - - - - + {!allFieldsReadOnly() && ( + + + + + )} {context.environment.features.deleteAccountAllowed && ( Date: Tue, 6 Aug 2024 13:47:36 +0200 Subject: [PATCH 085/103] use stringify on use meta data descriptor (#31717) (#31906) fixes: #31687 Signed-off-by: Erik Jan de Wit (cherry picked from commit 3f6136c6487f715bee2badf3d686efd3520eac21) --- .../admin-ui/src/identity-providers/add/DescriptorSettings.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/js/apps/admin-ui/src/identity-providers/add/DescriptorSettings.tsx b/js/apps/admin-ui/src/identity-providers/add/DescriptorSettings.tsx index 0cdc41b84b9..e6d8d813111 100644 --- a/js/apps/admin-ui/src/identity-providers/add/DescriptorSettings.tsx +++ b/js/apps/admin-ui/src/identity-providers/add/DescriptorSettings.tsx @@ -282,6 +282,7 @@ const Fields = ({ readOnly }: DescriptorSettingsProps) => { name="config.useMetadataDescriptorUrl" label={t("useMetadataDescriptorUrl")} isDisabled={readOnly} + stringify /> {useMetadataDescriptorUrl !== "true" && ( Date: Tue, 6 Aug 2024 13:52:59 +0200 Subject: [PATCH 086/103] Use TextControl in StringComponent (#31442) (#31743) * Use TextControl in StringComponent This makes that the field is required and partially fixes: Signed-off-by: Erik Jan de Wit #26963 * enable test-id override Signed-off-by: Erik Jan de Wit --------- Signed-off-by: Erik Jan de Wit (cherry picked from commit 0b5f42f95d13296a124c64a63ee355d7a1c962dd) --- .../tabs/mappers/MapperDetailsPage.ts | 2 +- .../realm_settings/RealmSettingsPage.ts | 2 +- .../components/dynamic/StringComponent.tsx | 29 +++++-------------- .../ui-shared/src/controls/TextControl.tsx | 9 +++--- 4 files changed, 15 insertions(+), 27 deletions(-) diff --git a/js/apps/admin-ui/cypress/support/pages/admin-ui/manage/client_scopes/client_scope_details/tabs/mappers/MapperDetailsPage.ts b/js/apps/admin-ui/cypress/support/pages/admin-ui/manage/client_scopes/client_scope_details/tabs/mappers/MapperDetailsPage.ts index 951f4d7cb7d..6f4b42a2c25 100644 --- a/js/apps/admin-ui/cypress/support/pages/admin-ui/manage/client_scopes/client_scope_details/tabs/mappers/MapperDetailsPage.ts +++ b/js/apps/admin-ui/cypress/support/pages/admin-ui/manage/client_scopes/client_scope_details/tabs/mappers/MapperDetailsPage.ts @@ -10,7 +10,7 @@ export enum ClaimJsonType { export default class MapperDetailsPage extends CommonPage { #userAttributeInput = '[data-testid="config.user🍺attribute"]'; - #tokenClaimNameInput = '[id="claim.name"]'; + #tokenClaimNameInput = '[data-testid="claim.name"]'; #claimJsonType = '[id="jsonType.label"]'; fillUserAttribute(userAttribute: string) { diff --git a/js/apps/admin-ui/cypress/support/pages/admin-ui/manage/realm_settings/RealmSettingsPage.ts b/js/apps/admin-ui/cypress/support/pages/admin-ui/manage/realm_settings/RealmSettingsPage.ts index 1f7cac1f1a3..061f9be5229 100644 --- a/js/apps/admin-ui/cypress/support/pages/admin-ui/manage/realm_settings/RealmSettingsPage.ts +++ b/js/apps/admin-ui/cypress/support/pages/admin-ui/manage/realm_settings/RealmSettingsPage.ts @@ -207,7 +207,7 @@ export default class RealmSettingsPage extends CommonPage { #availablePeriodExecutorFld = "available-period"; #editExecutorBtn = '[aria-label="Executors"] > li > div:first-child [data-testid="editExecutor"]'; - #executorAvailablePeriodInput = "#available-period"; + #executorAvailablePeriodInput = "[data-testid='available-period']"; #listingPage = new ListingPage(); #addCondition = "addCondition"; diff --git a/js/apps/admin-ui/src/components/dynamic/StringComponent.tsx b/js/apps/admin-ui/src/components/dynamic/StringComponent.tsx index 3da266c1a81..7bff36d3fa1 100644 --- a/js/apps/admin-ui/src/components/dynamic/StringComponent.tsx +++ b/js/apps/admin-ui/src/components/dynamic/StringComponent.tsx @@ -1,8 +1,5 @@ -import { FormGroup, TextInput } from "@patternfly/react-core"; -import { useFormContext } from "react-hook-form"; +import { TextControl } from "@keycloak/keycloak-ui-shared"; import { useTranslation } from "react-i18next"; -import { HelpItem } from "@keycloak/keycloak-ui-shared"; - import { convertToName } from "./DynamicComponents"; import type { ComponentProps } from "./components"; @@ -10,27 +7,17 @@ export const StringComponent = ({ name, label, helpText, - defaultValue, - isDisabled = false, - required, + ...props }: ComponentProps) => { const { t } = useTranslation(); - const { register } = useFormContext(); return ( - } - fieldId={name!} - isRequired={required} - > - - + helperText={t(helpText!)} + data-testid={name} + {...props} + /> ); }; diff --git a/js/libs/ui-shared/src/controls/TextControl.tsx b/js/libs/ui-shared/src/controls/TextControl.tsx index b29e10f6901..668ec2868b9 100644 --- a/js/libs/ui-shared/src/controls/TextControl.tsx +++ b/js/libs/ui-shared/src/controls/TextControl.tsx @@ -26,6 +26,7 @@ export type TextControlProps< labelIcon?: string | ReactNode; isDisabled?: boolean; helperText?: string; + "data-testid"?: string; }; export const TextControl = < @@ -34,7 +35,7 @@ export const TextControl = < >( props: TextControlProps, ) => { - const { labelIcon, ...rest } = props; + const { labelIcon, helperText, ...rest } = props; const required = !!props.rules?.required; const defaultValue = props.defaultValue ?? ("" as PathValue); @@ -54,7 +55,7 @@ export const TextControl = < - {props.helperText && ( + {helperText && ( - {props.helperText} + {helperText} )} From c70f729a6776e508ef893afbe747394118c9eeb7 Mon Sep 17 00:00:00 2001 From: Ryan Emerson Date: Wed, 7 Aug 2024 10:18:54 +0100 Subject: [PATCH 087/103] Upgrade to Infinispan 15.0.7.Final Closes #31963 Signed-off-by: Ryan Emerson --- .../high-availability/examples/generated/ispn-single.yaml | 2 +- .../high-availability/examples/generated/ispn-site-a.yaml | 2 +- .../high-availability/examples/generated/ispn-site-b.yaml | 2 +- pom.xml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/guides/high-availability/examples/generated/ispn-single.yaml b/docs/guides/high-availability/examples/generated/ispn-single.yaml index e92fe9f3add..08f61651c7f 100644 --- a/docs/guides/high-availability/examples/generated/ispn-single.yaml +++ b/docs/guides/high-availability/examples/generated/ispn-single.yaml @@ -224,7 +224,7 @@ spec: expose: type: Route configMapName: "cluster-config" - image: quay.io/infinispan/server:15.0.5.Final + image: quay.io/infinispan/server:15.0.7.Final configListener: enabled: false container: diff --git a/docs/guides/high-availability/examples/generated/ispn-site-a.yaml b/docs/guides/high-availability/examples/generated/ispn-site-a.yaml index daa88e8912d..85c1d017e36 100644 --- a/docs/guides/high-availability/examples/generated/ispn-site-a.yaml +++ b/docs/guides/high-availability/examples/generated/ispn-site-a.yaml @@ -363,7 +363,7 @@ spec: expose: type: Route configMapName: "cluster-config" - image: quay.io/infinispan/server:15.0.5.Final + image: quay.io/infinispan/server:15.0.7.Final configListener: enabled: false container: diff --git a/docs/guides/high-availability/examples/generated/ispn-site-b.yaml b/docs/guides/high-availability/examples/generated/ispn-site-b.yaml index eb2b36fc0ee..e990a0d1427 100644 --- a/docs/guides/high-availability/examples/generated/ispn-site-b.yaml +++ b/docs/guides/high-availability/examples/generated/ispn-site-b.yaml @@ -363,7 +363,7 @@ spec: expose: type: Route configMapName: "cluster-config" - image: quay.io/infinispan/server:15.0.5.Final + image: quay.io/infinispan/server:15.0.7.Final configListener: enabled: false container: diff --git a/pom.xml b/pom.xml index b1099022087..2233714f036 100644 --- a/pom.xml +++ b/pom.xml @@ -93,7 +93,7 @@ 2.2.224 6.2.13.Final 6.2.13.Final - 15.0.5.Final + 15.0.7.Final 2.1.1 From 2fb358e1a21c5387cdc11100ce3562b4dcfe5416 Mon Sep 17 00:00:00 2001 From: Pedro Igor Date: Fri, 17 May 2024 11:16:04 -0300 Subject: [PATCH 088/103] Support for blocking concurrent requests when brute force is enabled Closes #31726 Signed-off-by: Pedro Igor Signed-off-by: Douglas Palmer Signed-off-by: mposolda --- .../DefaultBlockingBruteForceProtector.java | 118 ++++++++++++++++++ .../DefaultBruteForceProtectorFactory.java | 7 +- .../testsuite/forms/BruteForceTest.java | 106 ++++++++++++++-- 3 files changed, 217 insertions(+), 14 deletions(-) create mode 100644 services/src/main/java/org/keycloak/services/managers/DefaultBlockingBruteForceProtector.java diff --git a/services/src/main/java/org/keycloak/services/managers/DefaultBlockingBruteForceProtector.java b/services/src/main/java/org/keycloak/services/managers/DefaultBlockingBruteForceProtector.java new file mode 100644 index 00000000000..5d6f0dc2548 --- /dev/null +++ b/services/src/main/java/org/keycloak/services/managers/DefaultBlockingBruteForceProtector.java @@ -0,0 +1,118 @@ +/* + * Copyright 2016 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.keycloak.services.managers; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; + +import org.keycloak.models.AbstractKeycloakTransaction; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.KeycloakSessionFactory; +import org.keycloak.models.RealmModel; +import org.keycloak.models.UserModel; +import org.keycloak.sessions.AuthenticationSessionModel; + +public class DefaultBlockingBruteForceProtector extends DefaultBruteForceProtector { + + // make this configurable? + private static final int DEFAULT_MAX_CONCURRENT_ATTEMPTS = 1000; + private static final float DEFAULT_LOAD_FACTOR = 0.75f; + + private final Map loginAttempts = Collections.synchronizedMap(new LinkedHashMap<>(100, DEFAULT_LOAD_FACTOR) { + @Override + protected boolean removeEldestEntry(Entry eldest) { + return loginAttempts.size() > DEFAULT_MAX_CONCURRENT_ATTEMPTS; + } + }); + + DefaultBlockingBruteForceProtector(KeycloakSessionFactory factory) { + super(factory); + } + + @Override + public boolean isPermanentlyLockedOut(KeycloakSession session, RealmModel realm, UserModel user) { + if (super.isPermanentlyLockedOut(session, realm, user)) { + return true; + } + + if (!realm.isPermanentLockout()) return false; + + return isLoginInProgress(session, user); + } + + @Override + public boolean isTemporarilyDisabled(KeycloakSession session, RealmModel realm, UserModel user) { + if (super.isTemporarilyDisabled(session, realm, user)) { + return true; + } + + return isLoginInProgress(session, user); + } + + private boolean isLoginInProgress(KeycloakSession session, UserModel user) { + AuthenticationSessionModel authSession = session.getContext().getAuthenticationSession(); + + if (authSession == null) { + // not authenticating as there is no auth session bound to the session + return false; + } + + if (isCurrentLoginAttempt(user)) { + return !tryEnlistBlockingTransaction(session, user); + } + + return true; + } + + // Return true if this thread successfully enlisted itself + private boolean tryEnlistBlockingTransaction(KeycloakSession session, UserModel user) { + String threadInProgress = loginAttempts.computeIfAbsent(user.getId(), k -> getThreadName()); + + // This means that this thread successfully added itself into the map. We can enlist transaction just in that case + if (threadInProgress.equals(getThreadName())) { + session.getTransactionManager().enlistAfterCompletion(new AbstractKeycloakTransaction() { + @Override + protected void commitImpl() { + unblock(); + } + + @Override + protected void rollbackImpl() { + unblock(); + } + + private void unblock() { + loginAttempts.remove(user.getId()); + } + }); + + return true; + } else { + return false; + } + } + + private boolean isCurrentLoginAttempt(UserModel user) { + return loginAttempts.getOrDefault(user.getId(), getThreadName()).equals(getThreadName()); + } + + private String getThreadName() { + return Thread.currentThread().getName(); + } +} diff --git a/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtectorFactory.java b/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtectorFactory.java index 0769c7b506a..53a8ad6d46e 100755 --- a/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtectorFactory.java +++ b/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtectorFactory.java @@ -28,6 +28,8 @@ public class DefaultBruteForceProtectorFactory implements BruteForceProtectorFactory { DefaultBruteForceProtector protector; + private boolean allowConcurrentRequests; + @Override public BruteForceProtector create(KeycloakSession session) { return protector; @@ -35,12 +37,13 @@ public BruteForceProtector create(KeycloakSession session) { @Override public void init(Config.Scope config) { - + // this can be a brute force setting? + this.allowConcurrentRequests = config.getBoolean("allowConcurrentRequests", Boolean.FALSE); } @Override public void postInit(KeycloakSessionFactory factory) { - protector = new DefaultBruteForceProtector(factory); + protector = allowConcurrentRequests ? new DefaultBruteForceProtector(factory) : new DefaultBlockingBruteForceProtector(factory); } @Override diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BruteForceTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BruteForceTest.java index 431b12a7cf9..811761df530 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BruteForceTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BruteForceTest.java @@ -100,7 +100,7 @@ public class BruteForceTest extends AbstractTestRealmKeycloakTest { private int lifespan; - private static final Integer failureFactor= 2; + private static final Integer failureFactor = 2; @Override public void configureTestRealm(RealmRepresentation testRealm) { @@ -380,13 +380,13 @@ public void testNumberOfFailuresForPermanentlyDisabledUsersWithPasswordGrantType assertUserNumberOfFailures(user.getId(), failureFactor); events.clear(); - } finally { - realm.setPermanentLockout(false); - testRealm().update(realm); - UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0); - user.setEnabled(true); - updateUser(user); - } + } finally { + realm.setPermanentLockout(false); + testRealm().update(realm); + UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0); + user.setEnabled(true); + updateUser(user); + } } @Test @@ -416,7 +416,7 @@ public void testFailureResetForTemporaryLockout() throws Exception { loginInvalidPassword(); //Wait for brute force executor to process the login and then wait for delta time - waitForExecutors(numExecutors+1); + waitForExecutors(numExecutors + 1); testingClient.testing().setTimeOffset(Collections.singletonMap("offset", String.valueOf(5))); loginInvalidPassword(); @@ -438,7 +438,7 @@ public void testNoFailureResetForPermanentLockout() throws Exception { loginInvalidPassword(); //Wait for brute force executor to process the login and then wait for delta time - waitForExecutors(numExecutors+1); + waitForExecutors(numExecutors + 1); testingClient.testing().setTimeOffset(Collections.singletonMap("offset", String.valueOf(5))); loginInvalidPassword(); @@ -468,10 +468,11 @@ private void waitForExecutors(long numExecutors) { ExecutorsProvider provider = session.getProvider(ExecutorsProvider.class); ExecutorService executor = provider.getExecutor("bruteforce"); ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor; - while(!threadPoolExecutor.getQueue().isEmpty()) { + while (!threadPoolExecutor.getQueue().isEmpty()) { try { Thread.sleep(1000); - } catch (Exception e) {} + } catch (Exception e) { + } } assertEquals(numExecutors, threadPoolExecutor.getCompletedTaskCount()); }); @@ -753,6 +754,87 @@ public void testResetPassword() throws Exception { events.clear(); } + @Test + public void testRaceAttackTemporaryLockout() throws Exception { + RealmRepresentation realm = testRealm().toRepresentation(); + UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0); + try { + realm.setWaitIncrementSeconds(120); + realm.setQuickLoginCheckMilliSeconds(120000L); + testRealm().update(realm); + clearUserFailures(); + clearAllUserFailures(); + user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0); + user.setEnabled(true); + testRealm().users().get(user.getId()).update(user); + String totpSecret = totp.generateTOTP("totpSecret"); + OAuthClient.AccessTokenResponse response = getTestToken("password", totpSecret); + Assert.assertNotNull(response.getAccessToken()); + raceAttack(user); + } finally { + realm.setWaitIncrementSeconds(5); + realm.setQuickLoginCheckMilliSeconds(100L); + testRealm().update(realm); + user.setEnabled(true); + updateUser(user); + } + } + + @Test + public void testRaceAttackPermanentLockout() throws Exception { + RealmRepresentation realm = testRealm().toRepresentation(); + UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0); + try { + realm.setPermanentLockout(true); + testRealm().update(realm); + raceAttack(user); + clearUserFailures(); + clearAllUserFailures(); + user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0); + user.setEnabled(true); + testRealm().users().get(user.getId()).update(user); + String totpSecret = totp.generateTOTP("totpSecret"); + OAuthClient.AccessTokenResponse response = getTestToken("password", totpSecret); + Assert.assertNotNull(response.getAccessToken()); + } finally { + realm.setPermanentLockout(false); + testRealm().update(realm); + user.setEnabled(true); + updateUser(user); + } + } + + private void raceAttack(UserRepresentation user) throws Exception { + int num = 100; + LoginThread[] threads = new LoginThread[num]; + for (int i = 0; i < num; ++i) { + threads[i] = new LoginThread(); + } + for (int i = 0; i < num; ++i) { + threads[i].start(); + } + for (int i = 0; i < num; ++i) { + threads[i].join(); + } + int invalidCount = (int) adminClient.realm("test").attackDetection().bruteForceUserStatus(user.getId()).get("numFailures"); + assertTrue("Invalid count should be less than or equal 2 but was: " + invalidCount, invalidCount <= 2); + } + + public class LoginThread extends Thread { + + public void run() { + try { + String totpSecret = totp.generateTOTP("totpSecret"); + OAuthClient.AccessTokenResponse response = getTestToken("invalid", totpSecret); + Assert.assertNull(response.getAccessToken()); + Assert.assertEquals(response.getError(), "invalid_grant"); + Assert.assertEquals(response.getErrorDescription(), "Invalid user credentials"); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + public void expectTemporarilyDisabled() { expectTemporarilyDisabled("test-user@localhost", null, "password"); } From 99f92ad5fff5555d53930c2d32f8be3e08c514c1 Mon Sep 17 00:00:00 2001 From: rmartinc Date: Tue, 6 Aug 2024 12:58:50 +0200 Subject: [PATCH 089/103] Remove the attempt in brute force when the off-thread finishes Closes #31881 Signed-off-by: rmartinc --- .../DefaultBlockingBruteForceProtector.java | 71 ++++++++++++++----- .../managers/DefaultBruteForceProtector.java | 9 +-- 2 files changed, 59 insertions(+), 21 deletions(-) diff --git a/services/src/main/java/org/keycloak/services/managers/DefaultBlockingBruteForceProtector.java b/services/src/main/java/org/keycloak/services/managers/DefaultBlockingBruteForceProtector.java index 5d6f0dc2548..2b148a30b9a 100644 --- a/services/src/main/java/org/keycloak/services/managers/DefaultBlockingBruteForceProtector.java +++ b/services/src/main/java/org/keycloak/services/managers/DefaultBlockingBruteForceProtector.java @@ -20,7 +20,9 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import org.keycloak.common.ClientConnection; import org.keycloak.models.AbstractKeycloakTransaction; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; @@ -33,6 +35,7 @@ public class DefaultBlockingBruteForceProtector extends DefaultBruteForceProtect // make this configurable? private static final int DEFAULT_MAX_CONCURRENT_ATTEMPTS = 1000; private static final float DEFAULT_LOAD_FACTOR = 0.75f; + private static final String OFF_THREAD_STARTED = "#brute_force_started"; private final Map loginAttempts = Collections.synchronizedMap(new LinkedHashMap<>(100, DEFAULT_LOAD_FACTOR) { @Override @@ -73,46 +76,80 @@ private boolean isLoginInProgress(KeycloakSession session, UserModel user) { return false; } - if (isCurrentLoginAttempt(user)) { - return !tryEnlistBlockingTransaction(session, user); - } - - return true; + return !tryEnlistBlockingTransactionOrSameThread(session, user); } - // Return true if this thread successfully enlisted itself - private boolean tryEnlistBlockingTransaction(KeycloakSession session, UserModel user) { - String threadInProgress = loginAttempts.computeIfAbsent(user.getId(), k -> getThreadName()); + // Return true if this thread successfully enlisted itself or it was already done by the same thread + private boolean tryEnlistBlockingTransactionOrSameThread(KeycloakSession session, UserModel user) { + AtomicBoolean inserted = new AtomicBoolean(false); + String threadInProgress = loginAttempts.computeIfAbsent(user.getId(), k -> { + inserted.set(true); + return getThreadName(); + }); // This means that this thread successfully added itself into the map. We can enlist transaction just in that case - if (threadInProgress.equals(getThreadName())) { + if (inserted.get()) { session.getTransactionManager().enlistAfterCompletion(new AbstractKeycloakTransaction() { @Override protected void commitImpl() { - unblock(); + // remove or wait the brute force thread to finish + loginAttempts.computeIfPresent(user.getId(), (k, v) -> v.endsWith(OFF_THREAD_STARTED)? "" : null); } @Override protected void rollbackImpl() { - unblock(); - } - - private void unblock() { + // remove on rollback loginAttempts.remove(user.getId()); } }); return true; } else { - return false; + return isCurrentThread(threadInProgress); } } - private boolean isCurrentLoginAttempt(UserModel user) { - return loginAttempts.getOrDefault(user.getId(), getThreadName()).equals(getThreadName()); + private boolean isCurrentThread(String name) { + return name.equals(getThreadName()) || name.equals(getThreadName() + OFF_THREAD_STARTED); } private String getThreadName() { return Thread.currentThread().getName(); } + + private void enlistRemoval(KeycloakSession session, String userId) { + session.getTransactionManager().enlistAfterCompletion(new AbstractKeycloakTransaction() { + @Override + protected void commitImpl() { + // remove or wait the main thread to finish + loginAttempts.computeIfPresent(userId, (k, v) -> v.isEmpty()? null : v.substring(0, v.length() - OFF_THREAD_STARTED.length())); + } + + @Override + protected void rollbackImpl() { + loginAttempts.remove(userId); + } + }); + } + + @Override + protected void processLogin(RealmModel realm, UserModel user, ClientConnection clientConnection, boolean success) { + // mark the off-thread is started for this request + loginAttempts.computeIfPresent(user.getId(), (k, v) -> v + OFF_THREAD_STARTED); + super.processLogin(realm, user, clientConnection, success); + } + + @Override + protected void failure(KeycloakSession session, RealmModel realm, String userId, String remoteAddr, long failureTime) { + // remove the user from concurrent login attemps once it's processed + enlistRemoval(session, userId); + super.failure(session, realm, userId, remoteAddr, failureTime); + } + + @Override + protected void success(KeycloakSession session, RealmModel realm, String userId) { + // remove the user from concurrent login attemps once it's processed + enlistRemoval(session, userId); + super.success(session, realm, userId); + } } diff --git a/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtector.java b/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtector.java index 7415bac2bc1..7a82ff0480a 100644 --- a/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtector.java +++ b/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtector.java @@ -180,10 +180,11 @@ public void successfulLogin(RealmModel realm, UserModel user, ClientConnection c logger.trace("sent success event"); } - private void processLogin(RealmModel realm, UserModel user, ClientConnection clientConnection, boolean success) { - KeycloakSession session = factory.create(); - ExecutorsProvider provider = session.getProvider(ExecutorsProvider.class); - ExecutorService executor = provider.getExecutor("bruteforce"); + protected void processLogin(RealmModel realm, UserModel user, ClientConnection clientConnection, boolean success) { + ExecutorService executor = KeycloakModelUtils.runJobInTransactionWithResult(factory, session -> { + ExecutorsProvider provider = session.getProvider(ExecutorsProvider.class); + return provider.getExecutor("bruteforce"); + }); executor.execute(() -> KeycloakModelUtils.runJobInTransaction(factory, s -> { if (success) { success(s, realm, user.getId()); From 2a8f104f268ebb0290773914ea8763cf06dcd6b5 Mon Sep 17 00:00:00 2001 From: rmartinc Date: Wed, 7 Aug 2024 10:49:53 +0200 Subject: [PATCH 090/103] Adding upgrading notes for brute force changes Closes #31960 Signed-off-by: rmartinc --- .../upgrading/topics/changes/changes-25_0_3.adoc | 10 ++++++++++ .../upgrading/topics/changes/changes.adoc | 4 ++++ .../DefaultBruteForceProtectorFactory.java | 15 +++++++++++++++ 3 files changed, 29 insertions(+) create mode 100644 docs/documentation/upgrading/topics/changes/changes-25_0_3.adoc diff --git a/docs/documentation/upgrading/topics/changes/changes-25_0_3.adoc b/docs/documentation/upgrading/topics/changes/changes-25_0_3.adoc new file mode 100644 index 00000000000..f7c81a038fd --- /dev/null +++ b/docs/documentation/upgrading/topics/changes/changes-25_0_3.adoc @@ -0,0 +1,10 @@ += Concurrent login requests are blocked by default when brute force is enabled + +If an attacker launched many login attempts in parallel then the attacker could have more guesses at a password than the brute force protection configuration permits. This was due to the brute force check occurring before the brute force protector has locked the user. To prevent this race the Brute Force Protector now rejects all login attempts that occur while another login is in progress in the same server. + +If, for whatever reason, the new feature wants to be disabled there is a startup factory option: + +[source,bash] +---- +bin/kc.[sh|bat] start --spi-brute-force-protector-default-brute-force-detector-allow-concurrent-requests=true +---- diff --git a/docs/documentation/upgrading/topics/changes/changes.adoc b/docs/documentation/upgrading/topics/changes/changes.adoc index ee779657332..3983d68a0b4 100644 --- a/docs/documentation/upgrading/topics/changes/changes.adoc +++ b/docs/documentation/upgrading/topics/changes/changes.adoc @@ -1,6 +1,10 @@ [[migration-changes]] == Migration Changes +=== Migrating to 25.0.3 + +include::changes-25_0_3.adoc[leveloffset=3] + === Migrating to 25.0.2 include::changes-25_0_2.adoc[leveloffset=3] diff --git a/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtectorFactory.java b/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtectorFactory.java index 53a8ad6d46e..daf5e80dec9 100755 --- a/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtectorFactory.java +++ b/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtectorFactory.java @@ -17,9 +17,12 @@ package org.keycloak.services.managers; +import java.util.List; import org.keycloak.Config; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; +import org.keycloak.provider.ProviderConfigProperty; +import org.keycloak.provider.ProviderConfigurationBuilder; /** * @author Bill Burke @@ -55,4 +58,16 @@ public void close() { public String getId() { return "default-brute-force-detector"; } + + @Override + public List getConfigMetadata() { + return ProviderConfigurationBuilder.create() + .property() + .name("allowConcurrentRequests") + .type("boolean") + .helpText("If concurrent logins are allowed by the brute force protection.") + .defaultValue(false) + .add() + .build(); + } } From b072f6df07f2874bb4904dfbb9bff800a8d213e2 Mon Sep 17 00:00:00 2001 From: Stan Silvert Date: Fri, 9 Aug 2024 05:58:36 -0400 Subject: [PATCH 091/103] Fix for Network error attempting to view events without permissions (#31920) (#31988) * Fix for #31918 Signed-off-by: kaustubh B * Update js/apps/admin-ui/src/realm-settings/RealmSettingsTabs.tsx Co-authored-by: Stan Silvert Signed-off-by: kaustubh-rh <88367583+kaustubh-rh@users.noreply.github.com> --------- Signed-off-by: kaustubh B Signed-off-by: kaustubh-rh <88367583+kaustubh-rh@users.noreply.github.com> Co-authored-by: Stan Silvert (cherry picked from commit e090b0d26035af69def569410e60dac58ea845f0) Co-authored-by: kaustubh-rh <88367583+kaustubh-rh@users.noreply.github.com> --- .../src/realm-settings/RealmSettingsTabs.tsx | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/js/apps/admin-ui/src/realm-settings/RealmSettingsTabs.tsx b/js/apps/admin-ui/src/realm-settings/RealmSettingsTabs.tsx index b3e1a490000..5e630de9563 100644 --- a/js/apps/admin-ui/src/realm-settings/RealmSettingsTabs.tsx +++ b/js/apps/admin-ui/src/realm-settings/RealmSettingsTabs.tsx @@ -293,6 +293,9 @@ export const RealmSettingsTabs = () => { const clientPoliciesTab = useTab("client-policies"); const userProfileTab = useTab("user-profile"); const userRegistrationTab = useTab("user-registration"); + const { hasAccess, hasSomeAccess } = useAccess(); + const canViewOrManageEvents = + hasAccess("view-realm") && hasSomeAccess("view-events", "manage-events"); const useClientPoliciesTab = (tab: ClientPoliciesTab) => useRoutableTab( @@ -366,13 +369,15 @@ export const RealmSettingsTabs = () => { > - {t("events")}} - data-testid="rs-realm-events-tab" - {...eventsTab} - > - - + {canViewOrManageEvents && ( + {t("events")}} + data-testid="rs-realm-events-tab" + {...eventsTab} + > + + + )} {t("localization")}} data-testid="rs-localization-tab" From e0d37bd18d58a62c69bc19870151a433537380c7 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Tue, 13 Aug 2024 09:04:21 +0200 Subject: [PATCH 092/103] Cache node binary for Windows to avoid download failures (#32053) Closes #31835 Signed-off-by: Alexander Schwartz --- .../actions/integration-test-setup/action.yml | 3 ++- .github/actions/maven-cache/action.yml | 26 +++++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/.github/actions/integration-test-setup/action.yml b/.github/actions/integration-test-setup/action.yml index d777e68bd87..ec5a9b8723d 100644 --- a/.github/actions/integration-test-setup/action.yml +++ b/.github/actions/integration-test-setup/action.yml @@ -40,6 +40,7 @@ runs: shell: bash run: | if [ "$RUNNER_OS" == "Windows" ]; then - choco install zstandard + # zstd binary might be missing in older versions, install only when necessary + which zstd > /dev/null || choco install zstandard fi tar -C ~/ --use-compress-program="zstd -d" -xf m2-keycloak.tzts diff --git a/.github/actions/maven-cache/action.yml b/.github/actions/maven-cache/action.yml index b131eaba52f..a4f1ffedb25 100644 --- a/.github/actions/maven-cache/action.yml +++ b/.github/actions/maven-cache/action.yml @@ -28,18 +28,40 @@ runs: ~/.m2/repository/*/* !~/.m2/repository/org/keycloak key: ${{ steps.weekly-cache-key.outputs.key }} + # Enable cross-os archive use the cache on both Linux and Windows + enableCrossOsArchive: true + + - id: download-node-for-windows + # This is necessary as the build which creates the cache will run on a Linux node and therefore will never download the Windows artifact by default. + # If we wouldn't download it manually, it would be downloaded on each Windows build, which proved to be unstable as downloads would randomly fail in the middle of the download. + if: inputs.create-cache-if-it-doesnt-exist == 'true' && steps.cache-maven-repository.outputs.cache-hit != 'true' + shell: bash + run: | + export VERSION=$(mvn help:evaluate -Dexpression=node.version -q -DforceStdout | cut -c 2-) + curl -Lf https://nodejs.org/dist/v${VERSION}/win-x64/node.exe --create-dirs -o ~/.m2/repository/com/github/eirslett/node/${VERSION}/node-${VERSION}-win-x64.exe + + - shell: powershell + name: Link the cached Maven repository to the OS-dependent location + if: inputs.create-cache-if-it-doesnt-exist == 'false' && runner.os == 'Windows' + # The cache restore in the next step uses the relative path which was valid on Linux and that is part of the archive it downloads. + # You'll see that path when you enable debugging for the GitHub workflow on Windows. + # On Windows, the .m2 folder is in different location, so move all the contents to the right folder here. + # Also, not using the C: drive will speed up the build, see https://github.com/actions/runner-images/issues/8755 + run: | + mkdir -p ../../../.m2/repository + cmd /c mklink /d $HOME\.m2\repository D:\.m2\repository - id: restore-maven-repository name: Maven cache uses: actions/cache/restore@v4 if: inputs.create-cache-if-it-doesnt-exist == 'false' with: - # Two asterisks are needed to make the follow-up exclusion work - # see https://github.com/actions/toolkit/issues/713 for the upstream issue + # This needs to repeat the same path pattern as above to find the matching cache path: | ~/.m2/repository/*/* !~/.m2/repository/org/keycloak key: ${{ steps.weekly-cache-key.outputs.key }} + enableCrossOsArchive: true - name: Cache Maven Wrapper uses: actions/cache@v4 From 04a3b22603e7bd91195cd62f4c8585920a651dca Mon Sep 17 00:00:00 2001 From: himanshi1099 <143601879+himanshi1099@users.noreply.github.com> Date: Mon, 5 Aug 2024 22:08:10 +0530 Subject: [PATCH 093/103] Fix for Network error attempting to view default realm roles without permissions (#31902) * fix for issue #29211 Signed-off-by: Himanshi Gupta * fix for issue #29211 Signed-off-by: Himanshi Gupta --------- Signed-off-by: Himanshi Gupta (cherry picked from commit 7cf9946040ba3334fecef144170520ea08e25c3e) --- .../src/components/roles-list/RolesList.tsx | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/js/apps/admin-ui/src/components/roles-list/RolesList.tsx b/js/apps/admin-ui/src/components/roles-list/RolesList.tsx index 16064e899d2..42aa68fec68 100644 --- a/js/apps/admin-ui/src/components/roles-list/RolesList.tsx +++ b/js/apps/admin-ui/src/components/roles-list/RolesList.tsx @@ -12,8 +12,8 @@ import { useAlerts } from "../alert/Alerts"; import { useConfirmDialog } from "../confirm-dialog/ConfirmDialog"; import { ListEmptyState } from "../list-empty-state/ListEmptyState"; import { Action, KeycloakDataTable } from "../table-toolbar/KeycloakDataTable"; - import "./RolesList.css"; +import { useAccess } from "../../context/access/Access"; type RoleDetailLinkProps = RoleRepresentation & { defaultRoleName?: string; @@ -29,13 +29,21 @@ const RoleDetailLink = ({ }: RoleDetailLinkProps) => { const { t } = useTranslation(messageBundle); const { realm } = useRealm(); + const { hasAccess, hasSomeAccess } = useAccess(); + const canViewUserRegistration = + hasAccess("view-realm") && hasSomeAccess("view-clients", "manage-clients"); + return role.name !== defaultRoleName ? ( {role.name} ) : ( <> - - {role.name}{" "} - + {canViewUserRegistration ? ( + + {role.name} + + ) : ( + {role.name} + )} Date: Fri, 16 Aug 2024 10:15:24 +0200 Subject: [PATCH 094/103] Caches the id-to-user mapping for the evaluation in the current session (#32138) Closes #31519 Signed-off-by: Alexander Schwartz --- .../policy/evaluation/DefaultEvaluation.java | 32 +++++++++++++------ 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/server-spi-private/src/main/java/org/keycloak/authorization/policy/evaluation/DefaultEvaluation.java b/server-spi-private/src/main/java/org/keycloak/authorization/policy/evaluation/DefaultEvaluation.java index b1583249a3b..82273359fe6 100644 --- a/server-spi-private/src/main/java/org/keycloak/authorization/policy/evaluation/DefaultEvaluation.java +++ b/server-spi-private/src/main/java/org/keycloak/authorization/policy/evaluation/DefaultEvaluation.java @@ -168,20 +168,34 @@ public boolean isUserInGroup(String id, String groupId, boolean checkParent) { return user.isMemberOf(group); } + private final String USER_CACHE_SESSION_ATTRIBUTE = DefaultEvaluation.class.getName() + ".userCache"; private UserModel getUser(String id, KeycloakSession session) { - RealmModel realm = session.getContext().getRealm(); - UserModel user = session.users().getUserById(realm, id); - - if (Objects.isNull(user)) { - user = session.users().getUserByUsername(realm ,id); - } - if (Objects.isNull(user)) { - user = session.users().getUserByEmail(realm, id); + @SuppressWarnings("unchecked") HashMap cache = (HashMap) session.getAttribute(USER_CACHE_SESSION_ATTRIBUTE); + if (cache == null) { + cache = new HashMap<>(); + session.setAttribute(USER_CACHE_SESSION_ATTRIBUTE, cache); } + UserModel user = cache.get(id); + if (Objects.isNull(user)) { - user = session.users().getServiceAccount(realm.getClientById(id)); + if (cache.containsKey(id)) { + return null; + } + RealmModel realm = session.getContext().getRealm(); + user = session.users().getUserById(realm, id); + if (Objects.isNull(user)) { + user = session.users().getUserByUsername(realm, id); + } + if (Objects.isNull(user)) { + user = session.users().getUserByEmail(realm, id); + } + if (Objects.isNull(user)) { + user = session.users().getServiceAccount(realm.getClientById(id)); + } } + cache.put(id, user); + return user; } From 01ae858fe9a337dfb440d9030c6cb266a6cba99e Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Fri, 16 Aug 2024 10:15:51 +0200 Subject: [PATCH 095/103] Handle non-existing client gracefully (#32167) Closes #32150 Signed-off-by: Alexander Schwartz --- .../org/keycloak/admin/ui/rest/SessionsResource.java | 4 ++++ .../services/resources/account/SessionResource.java | 10 ++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/rest/admin-ui-ext/src/main/java/org/keycloak/admin/ui/rest/SessionsResource.java b/rest/admin-ui-ext/src/main/java/org/keycloak/admin/ui/rest/SessionsResource.java index ed7c12bbbd8..94161bd561a 100644 --- a/rest/admin-ui-ext/src/main/java/org/keycloak/admin/ui/rest/SessionsResource.java +++ b/rest/admin-ui-ext/src/main/java/org/keycloak/admin/ui/rest/SessionsResource.java @@ -75,6 +75,10 @@ public Stream realmSessions(@QueryParam("type") @DefaultV Stream result = sessionIdStream.flatMap((clientIdSessionType) -> { ClientModel clientModel = realm.getClientById(clientIdSessionType.getClientId()); + if (clientModel == null) { + // client has been removed in the meantime + return Stream.empty(); + } switch (clientIdSessionType.getType()) { case REGULAR: return session.sessions().getUserSessionsStream(realm, clientModel) diff --git a/services/src/main/java/org/keycloak/services/resources/account/SessionResource.java b/services/src/main/java/org/keycloak/services/resources/account/SessionResource.java index ccf7be813b9..f520302de42 100755 --- a/services/src/main/java/org/keycloak/services/resources/account/SessionResource.java +++ b/services/src/main/java/org/keycloak/services/resources/account/SessionResource.java @@ -172,10 +172,12 @@ private SessionRepresentation createSessionRepresentation(UserSessionModel s, De for (String clientUUID : s.getAuthenticatedClientSessions().keySet()) { ClientModel client = realm.getClientById(clientUUID); - ClientRepresentation clientRep = new ClientRepresentation(); - clientRep.setClientId(client.getClientId()); - clientRep.setClientName(client.getName()); - sessionRep.getClients().add(clientRep); + if (client != null) { + ClientRepresentation clientRep = new ClientRepresentation(); + clientRep.setClientId(client.getClientId()); + clientRep.setClientName(client.getName()); + sessionRep.getClients().add(clientRep); + } } return sessionRep; } From 6dbe66b3a0279db04a392b4a2615e91f7353140b Mon Sep 17 00:00:00 2001 From: Michal Hajas Date: Fri, 16 Aug 2024 09:23:14 +0200 Subject: [PATCH 096/103] Remove information about online_user_session table Closes #32178 Signed-off-by: Michal Hajas Co-authored-by: Alexander Schwartz (cherry picked from commit 36ad5fb3bd365314e77bd4103d62e91d89111066) --- docs/documentation/upgrading/topics/changes/changes-25_0_0.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/documentation/upgrading/topics/changes/changes-25_0_0.adoc b/docs/documentation/upgrading/topics/changes/changes-25_0_0.adoc index 1e2dbd88983..6abf8cfc862 100644 --- a/docs/documentation/upgrading/topics/changes/changes-25_0_0.adoc +++ b/docs/documentation/upgrading/topics/changes/changes-25_0_0.adoc @@ -142,7 +142,7 @@ The first starting node will: . Migrate the database to the schema version 25. . Copy all session information from either the remote {jdgserver_name} or the JDBC persistence configured for {project_name}'s embedded cache to the database of {project_name}. + -The data will be stored in the tables `offline_user_session` and `online_user_session` with `offline_flag` set to `false`. +The data will be stored in the tables `offline_user_session` and `offline_client_session` with `offline_flag` set to `false`. . Clear the caches. + From 31d393a12aade21ae058089440e95a999198f265 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Fri, 16 Aug 2024 13:27:37 +0200 Subject: [PATCH 097/103] Specify version column name in a case-sensitive manner (#32190) Closes #32127 Signed-off-by: Alexander Schwartz --- .../models/jpa/session/PersistentClientSessionEntity.java | 1 + .../keycloak/models/jpa/session/PersistentUserSessionEntity.java | 1 + 2 files changed, 2 insertions(+) diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentClientSessionEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentClientSessionEntity.java index 265aa0391c6..892b8022a58 100644 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentClientSessionEntity.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentClientSessionEntity.java @@ -75,6 +75,7 @@ public class PersistentClientSessionEntity { protected int timestamp; @Version + @Column(name="VERSION") private int version; @Id diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentUserSessionEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentUserSessionEntity.java index 4facb253db2..957eeddd5e6 100644 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentUserSessionEntity.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/session/PersistentUserSessionEntity.java @@ -86,6 +86,7 @@ public class PersistentUserSessionEntity { protected String brokerSessionId; @Version + @Column(name="VERSION") private int version; @Id From 9bd5075caaf03c329f6bdc24ca61738cb1a9cf62 Mon Sep 17 00:00:00 2001 From: Stan Silvert Date: Wed, 14 Aug 2024 03:49:48 -0400 Subject: [PATCH 098/103] Hide User Reg tab if you don't have permissions (#32021) Fixes #31920 Signed-off-by: Stan Silvert (cherry picked from commit 35fbcf5af8eae283fcb83f1152ebaecf3e8fecef) --- .../src/realm-settings/DefaultGroupsTab.tsx | 116 ++++++++++-------- .../src/realm-settings/RealmSettingsTabs.tsx | 18 +-- 2 files changed, 74 insertions(+), 60 deletions(-) diff --git a/js/apps/admin-ui/src/realm-settings/DefaultGroupsTab.tsx b/js/apps/admin-ui/src/realm-settings/DefaultGroupsTab.tsx index 71071f02f86..c1f9b0da11d 100644 --- a/js/apps/admin-ui/src/realm-settings/DefaultGroupsTab.tsx +++ b/js/apps/admin-ui/src/realm-settings/DefaultGroupsTab.tsx @@ -31,6 +31,7 @@ import { useRealm } from "../context/realm-context/RealmContext"; import { toUserFederation } from "../user-federation/routes/UserFederation"; import { useFetch } from "../utils/useFetch"; import useToggle from "../utils/useToggle"; +import { useAccess } from "../context/access/Access"; export const DefaultsGroupsTab = () => { const { adminClient } = useAdminClient(); @@ -50,6 +51,9 @@ export const DefaultsGroupsTab = () => { const { addAlert, addError } = useAlerts(); const { enabled } = useHelp(); + const { hasAccess } = useAccess(); + const canAddOrRemoveGroups = hasAccess("view-users", "manage-realm"); + useFetch( () => adminClient.realms.getDefaultGroups({ realm }), (groups) => { @@ -160,59 +164,65 @@ export const DefaultsGroupsTab = () => { ariaLabelKey="defaultGroups" searchPlaceholderKey="searchForGroups" toolbarItem={ - <> - - - - - ( - - - - )} - isOpen={isKebabOpen} - shouldFocusToggleOnSelect - > - - { - toggleRemoveDialog(); - toggleKebab(); - }} - > - {t("remove")} - - - - - + canAddOrRemoveGroups && ( + <> + + + + + ( + + + + )} + isOpen={isKebabOpen} + shouldFocusToggleOnSelect + > + + { + toggleRemoveDialog(); + toggleKebab(); + }} + > + {t("remove")} + + + + + + ) + } + actions={ + canAddOrRemoveGroups + ? [ + { + title: t("remove"), + onRowClick: (group) => { + setSelectedRows([group]); + toggleRemoveDialog(); + return Promise.resolve(false); + }, + } as Action, + ] + : [] } - actions={[ - { - title: t("remove"), - onRowClick: (group) => { - setSelectedRows([group]); - toggleRemoveDialog(); - return Promise.resolve(false); - }, - } as Action, - ]} columns={[ { name: "name", @@ -239,7 +249,7 @@ export const DefaultsGroupsTab = () => { Add groups... } - primaryActionText={t("addGroups")} + primaryActionText={canAddOrRemoveGroups ? t("addGroups") : ""} onPrimaryAction={toggleGroupPicker} /> } diff --git a/js/apps/admin-ui/src/realm-settings/RealmSettingsTabs.tsx b/js/apps/admin-ui/src/realm-settings/RealmSettingsTabs.tsx index 5e630de9563..db0bfa98e07 100644 --- a/js/apps/admin-ui/src/realm-settings/RealmSettingsTabs.tsx +++ b/js/apps/admin-ui/src/realm-settings/RealmSettingsTabs.tsx @@ -296,6 +296,8 @@ export const RealmSettingsTabs = () => { const { hasAccess, hasSomeAccess } = useAccess(); const canViewOrManageEvents = hasAccess("view-realm") && hasSomeAccess("view-events", "manage-events"); + const canViewUserRegistration = + hasAccess("view-realm") && hasSomeAccess("view-clients", "manage-clients"); const useClientPoliciesTab = (tab: ClientPoliciesTab) => useRoutableTab( @@ -458,13 +460,15 @@ export const RealmSettingsTabs = () => { > - {t("userRegistration")}} - data-testid="rs-userRegistration-tab" - {...userRegistrationTab} - > - - + {canViewUserRegistration && ( + {t("userRegistration")}} + data-testid="rs-userRegistration-tab" + {...userRegistrationTab} + > + + + )} From db95afd73cc8587382d5133d5162ee7c288d7bd7 Mon Sep 17 00:00:00 2001 From: Michal Hajas Date: Fri, 16 Aug 2024 12:57:07 +0200 Subject: [PATCH 099/103] Set clientId if it is not set in the entity Closes #32195 Signed-off-by: Michal Hajas (cherry picked from commit 6a9245546e92a05c00410a8d7ac5897f3261a116) --- .../sessions/infinispan/PersistentUserSessionProvider.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/PersistentUserSessionProvider.java b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/PersistentUserSessionProvider.java index af1ff90c04b..e0c450f6600 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/PersistentUserSessionProvider.java +++ b/model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/PersistentUserSessionProvider.java @@ -1017,9 +1017,13 @@ private void processEntryFromCache(SessionEntityWrapper sessi // ignoring old and unknown realm found in the session return; } - sessionEntityWrapper.getEntity().getAuthenticatedClientSessions().forEach((k, uuid) -> { + sessionEntityWrapper.getEntity().getAuthenticatedClientSessions().forEach((clientId, uuid) -> { SessionEntityWrapper clientSession = clientSessionCache.get(uuid); if (clientSession != null) { + // This is necessary because client sessions created by a KC version < 22 do not have clientId set within the entity. + if (clientSession.getEntity().getClientId() == null) { + clientSession.getEntity().setClientId(clientId); + } clientSession.getEntity().setUserSessionId(sessionEntityWrapper.getEntity().getId()); MergedUpdate merged = MergedUpdate.computeUpdate(Collections.singletonList(Tasks.addIfAbsentSync()), clientSession, 1, 1); clientSessionPerformer.registerChange(Map.entry(uuid, new SessionUpdatesList<>(realm, clientSession)), merged); From 7bf8841e31315924c6d77f15d12a074802b5fd22 Mon Sep 17 00:00:00 2001 From: Ricardo Martin Date: Fri, 16 Aug 2024 17:23:40 +0200 Subject: [PATCH 100/103] better unset check (#32062) (#32207) * better unset check fixes: #32059 Signed-off-by: Erik Jan de Wit * better explanation Signed-off-by: Erik Jan de Wit * fix min value Signed-off-by: Erik Jan de Wit * Steal some code from `react-hook-form` Signed-off-by: Jon Koops --------- Signed-off-by: Erik Jan de Wit Signed-off-by: Jon Koops Co-authored-by: Jon Koops (cherry picked from commit 862854bc2915516a1d7a9b3874c39bdfc48f8422) Co-authored-by: Erik Jan de Wit --- .../admin/messages/messages_en.properties | 2 +- .../initial-access/CreateInitialAccessToken.tsx | 4 +++- .../ui-shared/src/controls/NumberControl.tsx | 12 ++++++++---- js/libs/ui-shared/src/utils/getRuleValue.ts | 17 +++++++++++++++++ 4 files changed, 29 insertions(+), 6 deletions(-) create mode 100644 js/libs/ui-shared/src/utils/getRuleValue.ts diff --git a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties index 2dadc40c1c4..099c853f918 100644 --- a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties +++ b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties @@ -2767,7 +2767,7 @@ javaKeystore=java-keystore updatedUserProfileSuccess=User Profile configuration has been saved deleteProviderMapper=Delete mapper? clientsPermissionsHint=Fine grained permissions for administrators that want to manage this client or apply roles defined by this client. -lookAroundHelp=How far around should the server look just in case the token generator and server are out of time sync or counter sync? +lookAroundHelp=How far around (extra token periods or counts) should the server look just in case the token generator and server are out of time sync or counter sync? usersLeft_one={{count}} user left the group sync-keycloak-groups-to-ldap=Sync Keycloak groups to LDAP saveError=User federation provider could not be saved\: {{error}} diff --git a/js/apps/admin-ui/src/clients/initial-access/CreateInitialAccessToken.tsx b/js/apps/admin-ui/src/clients/initial-access/CreateInitialAccessToken.tsx index 1fe3b80b753..a7e2dc1125f 100644 --- a/js/apps/admin-ui/src/clients/initial-access/CreateInitialAccessToken.tsx +++ b/js/apps/admin-ui/src/clients/initial-access/CreateInitialAccessToken.tsx @@ -85,9 +85,11 @@ export default function CreateInitialAccessToken() { label={t("count")} labelIcon={t("countHelp")} controller={{ + rules: { + min: 1, + }, defaultValue: 1, }} - min={1} />