8000 Added support for reloadable ssl configuration by Hakky54 · Pull Request #54327 · keycloak/keycloak · GitHub
[go: up one dir, main page]

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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,8 @@
<!-- webauthn support -->
<webauthn4j.version>0.30.3.RELEASE</webauthn4j.version>

<ayza.version>10.1.0</ayza.version>

<!-- Used to test SAML Galleon feature-pack layers discovery -->
<version.org.wildfly.glow>1.5.2.Final</version.org.wildfly.glow>

Expand Down Expand Up @@ -1238,6 +1240,11 @@
<artifactId>webauthn4j-util</artifactId>
<version>${webauthn4j.version}</version>
</dependency>
<dependency>
<groupId>io.github.hakky54</groupId>
<artifactId>ayza</artifactId>
<version>${ayza.version}</version>
</dependency>

<!-- used in server-dist build while provisioning the distribution -->
<dependency>
Expand Down
4 changes: 4 additions & 0 deletions quarkus/runtime/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,10 @@
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>io.github.hakky54</groupId>
<artifactId>ayza</artifactId>
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of introducing arbitrary libraries, we should leverage the Quarkus TLS Registry.

@Hakky54 Hakky54 Oct 26, 2026 •
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. I added indeed the ayza library and the main reason is that it provides flexible tls configuration. The quarkus tls registry is powerfull and provides by default ssl reloading for the default configuration. However, as far as I noticed in the source code of the client side the ssl configuration in keycloak is already custom as it is being configured programatically as shown here: https://github.com/keycloak/keycloak/pull/54327/changes#diff-4ea37268beba58c59898db2471806ff05624476d6ef95396357d2e8f4844a54b

In that referenced file different paths are being considered while building the ssl configuration for example trust all option, or configure trustoptions only if it is present and the same goes for the keyoptions. It made sense to extend on that config and therefor I added the ayza library. Next to that, I need to admit, that I am the maintainer of the Ayza library. It provides reloadable ssl configuration and that made it also more convenient to use. But if you don't prefer it, thats ok then I can remove it. Feel free to share your thoughts.

Next to that I also noticed that there was the following PR: #52520 based on the tls registry. This pull request should achieve the same with less and more maintainable code. However I only worked on the client side, the server side still needs to be done. This is more a WIP PR to gather early feedback

</dependency>
<dependency>
<groupId>com.webauthn4j</groupId>
<artifactId>webauthn4j-core</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
package org.keycloak.quarkus.runtime.httpclient;

import java.io.ByteArrayOutputStream;
import java.security.KeyStore;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import io.vertx.core.net.KeyCertOptions;

import org.keycloak.Config;
import org.keycloak.common.Profile;
import org.keycloak.common.enums.HostnameVerificationPolicy;
import org.keycloak.common.util.EnvUtil;
import org.keycloak.common.util.KeystoreUtil;
import org.keycloak.connections.httpclient.DefaultHttpClientFactory;
import org.keycloak.connections.httpclient.HttpClientFactory;
import org.keycloak.connections.httpclient.HttpClientProvider;
import org.keycloak.connections.httpclient.ProxyMappings;
Expand All @@ -18,13 +20,16 @@
import org.keycloak.provider.EnvironmentDependentProviderFactory;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.provider.ProviderConfigurationBuilder;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.tls.CertificateReloadScheduler;
import org.keycloak.tls.SslReloadService;
import org.keycloak.truststore.FileTruststoreProviderFactory;
import org.keycloak.truststore.TruststoreProvider;

import io.quarkus.arc.Arc;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.net.KeyStoreOptions;
import io.vertx.core.net.TrustOptions;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
import org.jboss.logging.Logger;
Expand All @@ -39,6 +44,7 @@ public class VertxHttpClientFactory implements HttpClientFactory, EnvironmentDep

private volatile WebClient webClient;
private volatile HttpClient httpClient;
private SslReloadService sslReloadService;
private Config.Scope config;
private long maxConsumedResponseSize;
private long socketTimeoutMs;
Expand Down Expand Up @@ -79,11 +85,14 @@ public void postInit(KeycloakSessionFactory factory) {
backoffMultiplier = Double.parseDouble(config.get("backoff-multiplier", "2.0"));
useJitter = config.getBoolean("use-jitter", true);
jitterFactor = Double.parseDouble(config.get("jitter-factor", "0.5"));

sslReloadService = new SslReloadService();
}

@Override
public void close() {
if (sslReloadService != null) {
sslReloadService.close();
}
try {
if (webClient != null) {
webClient.close();
Expand Down Expand Up @@ -158,13 +167,24 @@ private void configureTls(KeycloakSession session, WebClientOptions options) {
options.setTrustAll(true);
options.setVerifyHost(false);
} else {
Supplier<KeyStore> truststoreSupplier = () -> {
ProviderFactory<TruststoreProvider> providerFactory = session.getKeycloakSessionFactory().getProviderFactory(TruststoreProvider.class);
if (providerFactory instanceof FileTruststoreProviderFactory) {
FileTruststoreProviderFactory factory = (FileTruststoreProviderFactory) providerFactory;
factory.reInit();
return factory.create(session).getTruststore();
}
return providerFactory.create(session).getTruststore();
};
sslReloadService.setTrustMaterial(truststoreSupplier);

TruststoreProvider truststoreProvider = session.getProvider(TruststoreProvider.class);
if (truststoreProvider == null || truststoreProvider.getTruststore() == null) {
logger.warn("TruststoreProvider is disabled");
} else {
HostnameVerificationPolicy policy = truststoreProvider.getPolicy();
options.setVerifyHost(policy != HostnameVerificationPolicy.ANY);
options.setTrustOptions(keystoreToOptions(truststoreProvider.getTruststore(), null));
options.setTrustOptions(TrustOptions.wrap(sslReloadService.getTrustManager()));
options.setSsl(true);
}
}
Expand All @@ -174,28 +194,18 @@ private void configureTls(KeycloakSession session, WebClientOptions options) {
clientKeystore = EnvUtil.replace(clientKeystore);
String clientKeystorePassword = config.get("client-keystore-password");
try {
KeyStore ks = KeystoreUtil.loadKeyStore(clientKeystore, clientKeystorePassword);
options.setKeyCertOptions(keystoreToOptions(ks, config.get("client-key-password", clientKeystorePassword)));
sslReloadService.setIdentityMaterial(clientKeystore, clientKeystorePassword, clientKeystorePassword);

options.setKeyCertOptions(KeyCertOptions.wrap(sslReloadService.getKeyManager()));
options.setSsl(true);
logger.debug("Client keystore configured for mutual TLS");
} catch (Exception e) {
throw new RuntimeException("Failed to load client keystore: " + clientKeystore, e);
}
}
}

private KeyStoreOptions keystoreToOptions(KeyStore keyStore, String password) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
char[] pw = password != null ? password.toCharArray() : new char[0];
keyStore.store(baos, pw);
return new KeyStoreOptions()
.setType(keyStore.getType())
.setValue(Buffer.buffer(baos.toByteArray()))
.setPassword(password != null ? password : "");
} catch (Exception e) {
throw new RuntimeException("Failed to serialize keystore", e);
}
String reloadPeriodValue = config.get(DefaultHttpClientFactory.CLIENT_SSL_RELOAD_PERIOD, DefaultHttpClientFactory.DEFAULT_CLIENT_KEYSTORE_RELOAD_PERIOD);
CertificateReloadScheduler.parsePeriod(reloadPeriodValue).ifPresent(sslReloadService::scheduleReload);
}

private void configureProxy() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,7 @@
* @author <a href="mailto:mstrukel@redhat.com">Marko Strukelj</a>
*/
public interface TruststoreProviderFactory extends ProviderFactory<TruststoreProvider> {

void reInit();

}
4 changes: 4 additions & 0 deletions services/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,10 @@
<groupId>com.webauthn4j</groupId>
<artifactId>webauthn4j-core</artifactId>
</dependency>
<dependency>
<groupId>io.github.hakky54</groupId>
<artifactId>ayza</artifactId>
</dependency>
<dependency>
<groupId>com.github.ua-parser</groupId>
<artifactId>uap-java</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,19 @@
import java.security.KeyStore;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import org.keycloak.Config;
import org.keycloak.common.Profile;
import org.keycloak.common.util.EnvUtil;
import org.keycloak.common.util.KeystoreUtil;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.provider.EnvironmentDependentProviderFactory;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.provider.ProviderConfigurationBuilder;
import org.keycloak.tls.CertificateReloadScheduler;
import org.keycloak.tls.SslReloadService;
import org.keycloak.truststore.FileTruststoreProviderFactory;
import org.keycloak.truststore.TruststoreProvider;

import org.apache.http.HttpEntity;
Expand Down Expand Up @@ -69,8 +72,11 @@ public class DefaultHttpClientFactory implements HttpClientFactory, EnvironmentD
private static final String NO_PROXY = "no_proxy";
public static final String MAX_CONSUMED_RESPONSE_SIZE = "max-consumed-response-size";
public static final String ALLOW_REDIRECTS = "allow-redirects";
public static final String CLIENT_SSL_RELOAD_PERIOD = "client-ssl-reload-period";
public static final String DEFAULT_CLIENT_SSL_RELOAD_PERIOD = "12h";

private volatile CloseableHttpClient httpClient;
private final SslReloadService sslReloadService = new SslReloadService();
private Config.Scope config;

private BasicResponseHandler stringResponseHandler;
Expand Down Expand Up @@ -154,6 +160,7 @@ public long getMaxConsumedResponseSize() {

@Override
public void close() {
sslReloadService.close();
try {
if (httpClient != null) {
httpClient.close();
Expand Down Expand Up @@ -230,11 +237,12 @@ private void lazyInit(KeycloakSession session) {
logger.warn("TruststoreProvider is disabled");
} else {
builder.hostnameVerification(truststoreProvider.getPolicy());
try {
builder.trustStore(truststoreProvider.getTruststore());
} catch (Exception e) {
throw new RuntimeException("Failed to load truststore", e);
}
Supplier<KeyStore> truststoreSupplier = () -> {
FileTruststoreProviderFactory factory = (FileTruststoreProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(TruststoreProvider.class);
factory.reInit();
return factory.create(session).getTruststore();
Comment on lines +241 to +243
};
sslReloadService.setTrustMaterial(truststoreSupplier);
}

if (disableTrustManager) {
Expand All @@ -249,13 +257,19 @@ private void lazyInit(KeycloakSession session) {
if (clientKeystore != null) {
clientKeystore = EnvUtil.replace(clientKeystore);
try {
KeyStore clientCertKeystore = KeystoreUtil.loadKeyStore(clientKeystore, clientKeystorePassword);
builder.keyStore(clientCertKeystore, clientPrivateKeyPassword);
sslReloadService.setIdentityMaterial(clientKeystore, clientKeystorePassword, clientPrivateKeyPassword);
} catch (Exception e) {
throw new RuntimeException("Failed to load keystore", e);
}
}

if (sslReloadService.isSslMaterialPresent()) {
builder.sslContext(sslReloadService.getSslContext());

String reloadPeriodValue = config.get(CLIENT_SSL_RELOAD_PERIOD, DEFAULT_CLIENT_SSL_RELOAD_PERIOD);
CertificateReloadScheduler.parsePeriod(reloadPeriodValue).ifPresent(sslReloadService::scheduleReload);
}

// Configure retry behavior
configureRetries(builder);

Expand Down Expand Up @@ -401,6 +415,12 @@ public List<ProviderConfigProperty> getConfigMetadata() {
.defaultValue(-1L)
.add()
.property()
.name(CLIENT_SSL_RELOAD_PERIOD)
.type("string")
.helpText("Interval on which to reload the client key store. " + "May be an ISO 8601 duration value, an integer number of seconds, or an integer followed by one of [ms, h, m, s, d]. Use -1 to disable.")
.defaultValue(DEFAULT_CLIENT_SSL_RELOAD_PERIOD)
.add()
.property()
.name("disable-trust-manager")
.type("boolean")
.helpText("Disable trust management and hostname verification. NOTE this is a security hole, so only set this option if you cannot or do not want to verify the identity of the host you are communicating with.")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright 2026 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.tls;

import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.keycloak.common.util.DurationConverter;

import org.jboss.logging.Logger;

public final class CertificateReloadScheduler {

private static final Logger log = Logger.getLogger(CertificateReloadScheduler.class);

private static ScheduledExecutorService executor;

private CertificateReloadScheduler() {
}

public static Optional<Duration> parsePeriod(String value) {
if (value == null || value.isBlank() || "-1".equals(value.trim())) {
return Optional.empty();
}
Duration period = DurationConverter.parseDuration(value.trim());
if (period == null || period.isZero() || period.isNegative()) {
return Optional.empty();
}
return Optional.of(period);
}

public static ScheduledFuture<?> schedule(Duration period, Runnable task) {
long millis = period.toMillis();
log.debugf("Scheduling reload of certificates every %s", period);
return getExecutor().scheduleWithFixedDelay(() -> {
try {
task.run();
} catch (Exception e) {
log.warnf(e, "Failed to reload certificates, the previously loaded certificates will be used");
}
}, millis, millis, TimeUnit.MILLISECONDS);
}

private static synchronized ScheduledExecutorService getExecutor() {
if (executor == null) {
executor = Executors.newSingleThreadScheduledExecutor(runnable -> {
Thread thread = new Thread(runnable, "keycloak-certificate-reloader");
thread.setDaemon(true);
return thread;
});
}
return executor;
}
}
Loading
Loading
0