From 59d67ed285c2ee924e4145ba657a71be229533ca Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 01:08:40 +0300 Subject: [PATCH 01/53] IGNITE-29212 Reload HTTP REST certificates from the Jetty configuration The reload command and the hourly hot reload check now reload the TLS factory of the Jetty HTTPS connector. The whole reload runs under the factory's lock. If loading fails, the factory gets its previous context back, so new connections never see a factory without keys. Hot reload runs for every factory without settings. A certificate is due before it expires by a third of its lifetime, but by no more than 7 days. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/restapi.adoc | 12 + docs/_docs/security/ssl-tls.adoc | 51 ++- docs/_docs/tools/control-script.adoc | 5 +- .../processors/ssl/HotReloadTime.java | 84 +++++ .../ignite/ssl/AbstractSslContextFactory.java | 108 +----- .../management/ssl/SslReloadTask.java | 14 +- .../processors/ssl/ReloadableSslFactory.java | 34 ++ .../processors/ssl/SslFactoryRegistry.java | 80 ++-- .../ssl/SslFactoryRegistryTest.java | 134 +++---- .../ssl/SslCertificateHotReloadTest.java | 10 +- .../ssl/SslContextFactoryHotReloadTest.java | 115 ++---- modules/rest-http/pom.xml | 7 + .../http/jetty/GridJettyRestProtocol.java | 15 +- .../http/jetty/ReloadableJettySslFactory.java | 145 ++++++++ .../protocols/http/jetty/GridRestSuite.java | 3 +- .../http/jetty/JettyRestHttpsReloadTest.java | 343 ++++++++++++++++++ .../resources/META-INF/jetty/https-source.xml | 33 ++ .../test/resources/META-INF/jetty/https.xml | 37 ++ 18 files changed, 885 insertions(+), 345 deletions(-) create mode 100644 modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/HotReloadTime.java create mode 100644 modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java create mode 100644 modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java create mode 100644 modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java create mode 100644 modules/rest-http/src/test/resources/META-INF/jetty/https-source.xml create mode 100644 modules/rest-http/src/test/resources/META-INF/jetty/https.xml diff --git a/docs/_docs/restapi.adoc b/docs/_docs/restapi.adoc index 88022e86fd65d..c25c17fe27477 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -104,6 +104,18 @@ NOTE: Ignite uses Jetty 12. Custom Jetty XML configurations created for earlier include::code-snippets/xml/jetty.xml[tags=, indent=0] ---- +=== HTTPS + +Configure the HTTPS connector, its SSL context factory, and its key and trust stores in the Jetty XML file set by `setJettyPath(String)`. +Both the standard Jetty factory and custom subclasses of `SslContextFactory.Server` work. + +After you replace the stores, run the link:tools/control-script#reloading-tls-certificates[`--ssl reload` command]. +The node also reloads the stores automatically before its certificates expire, as described in link:security/ssl-tls#automatic-certificate-hot-reload[Automatic Certificate Hot Reload]. +Each reload asks the Jetty factory to load its stores again. +New connections use the replacement certificates; established connections stay open. +If loading fails, the endpoint keeps its current keys and trust settings, and new connections keep working with them. +Correct the stores and run the command again. + === Security When link:security/authentication[authentication] is configured in the cluster, all applications that use REST API request authentication by providing security credentials. diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index 56d809c4f9d6c..fc55d76703391 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -160,7 +160,12 @@ include::{javaFile}[tag=disable-validation,indent=0] You can replace certificate files and reload them without restarting nodes that use `SslContextFactory`. The link:tools/control-script#reloading-tls-certificates[`--ssl reload` command] updates TCP transports on all server and thick-client nodes. -It does not reload TLS for the HTTP REST endpoint (Jetty) or external client applications. +It also reloads the link:restapi#https[HTTP REST endpoint] when its Jetty connector uses HTTPS. +External client applications reload their certificates separately. + +Follow the trust-first order below even if you do not plan to run the command. +<> is always on, so a node can load a replaced key store by itself within an hour once its current certificates are due. +If a peer does not trust the new certificate yet, its new connections to that node fail. . Back up the key and trust store files before replacing them. Keep their configured paths, store types, and passwords unchanged; changing node configuration requires a restart. @@ -182,29 +187,22 @@ Check the affected node's log for error details. Correct the failed store and run the command again. To restore the previous certificates, restore the backed-up files and reload again while peers still trust those certificates. -Custom factories must extend javadoc:org.apache.ignite.ssl.AbstractSslContextFactory[]. +Custom factories for discovery, communication, client connector, and binary REST must extend javadoc:org.apache.ignite.ssl.AbstractSslContextFactory[]. They must reread key and trust data from their sources on reload and supply the updated context for new connections. -If any factory on a node has another type, the command reports it as unsupported and reloads nothing on that node. +If any of these transports uses another type of factory, the command reports it as unsupported and reloads nothing on that node. For these factories, follow the same trust-first sequence and restart affected nodes one at a time instead of running reload. If you configured `trustManagers` directly, the command reuses them instead of reloading a trust store. == Automatic Certificate Hot Reload Automatic hot reload lets nodes load replacement certificates without a reload command. +It is always on and needs no configuration. You must supply the replacements: Ignite reads them from the configured source and does not issue certificates. -Hot reload covers the same TCP transports as <>. -It does not update the HTTP REST endpoint or external client applications. - -=== Enable Hot Reload +Hot reload covers the same transports as <>, including the HTTP REST endpoint. +It does not update external client applications. -Enable hot reload on each configured factory before starting the node: - -[source,java] ----- -factory.setHotReloadEnabled(true); ----- +=== Supply Replacements -Changing this setting requires a node restart. The key store must contain a private key with an X.509 certificate chain. A chain contains the key's certificate and the certificates of its issuers. Ignite ignores keys without such a chain, as TLS does. @@ -220,19 +218,19 @@ Ignite loads the replacements automatically when hot reload is due; no reload co === When Hot Reload Runs -At startup, Ignite checks each factory with hot reload enabled. +At startup, Ignite checks each factory. After it finishes checking all factories, it waits one hour before checking them again. A slow certificate source can therefore delay a factory's next check by more than an hour. -For each factory, hot reload becomes due `hotReloadBeforeExpiryMs` before the earliest certificate expiry in its private key chains. -This includes issuing certificates. The default lead time is 7 days. +Each certificate in the private key chains, including issuing certificates, becomes due before it expires by a third of its lifetime, but by no more than 7 days. +For example, a certificate valid for 24 hours is due 8 hours before it expires, and a certificate valid for 90 days is due 7 days before. +A factory is due when its first certificate is due. +For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded. The first check at or after that date attempts a reload, including the startup check. -Allow enough time before expiry to supply the replacements, wait through the one-hour interval and load the stores. -Keep the lead time shorter than the lifetime of the replacement certificates, or they will already be due when loaded. -See link:{javadoc_base_url}/org/apache/ignite/ssl/AbstractSslContextFactory.html#getHotReloadTime()[getHotReloadTime(), window=_blank] for the calculation. +Supply the replacements before the current certificates are due, so that the next check loads them. If the loaded certificates are still due for hot reload, Ignite records a failed hot reload attempt even though it installed them. -This can happen when the certificates have not changed, only the trust store changed, or the replacements expire within `hotReloadBeforeExpiryMs`. +This can happen when the certificates have not changed, only the trust store changed, or the replacements are already due when loaded. The loaded context remains in use until a later reload replaces it. After a manual reload, the next hourly check uses the loaded certificates. @@ -243,6 +241,7 @@ To confirm a replacement, open a new TLS connection to each affected endpoint an === Check Failures and Recover If loading the stores or creating the TLS context fails, Ignite keeps the current certificates and retries on the next check, even after they expire. +The HTTP REST endpoint keeps its current keys and trust settings in the same way. Keeping expired certificates does not extend their validity, so new connections may fail until a valid replacement is available. If the replacements appear after hot reload is due, the next retry loads them. @@ -259,7 +258,7 @@ To recover without waiting for the next retry: . Check the command result and verify a new connection with the replacement certificates. *What happens to automatic hot reload.* -If enabled, automatic hot reload continues after manual reload, as described in <>. +Automatic hot reload continues after manual reload, as described in <>. A failed automatic attempt does not undo the manual reload. *If the command cannot connect.* @@ -304,14 +303,6 @@ Limit request duration in custom sources: a blocked load delays other hot reload |The protocol for secure transport. https://docs.oracle.com/en/java/javase/11/docs/specs/security/standard-names.html#sslcontext-algorithms[Supported algorithms,window=_blank]. |`TLS` -|`hotReloadEnabled` -|Enables automatic certificate hot reload. See <>. -|`false` - -|`hotReloadBeforeExpiryMs` -|How long before the certificates expire hot reload becomes due, in milliseconds. See <>. -|`604800000` (7 days) - |`trustStoreFilePath` |The path to the trust store file. |`N/A` diff --git a/docs/_docs/tools/control-script.adoc b/docs/_docs/tools/control-script.adoc index 54fff9048bea8..a1cd83e7d68cb 100644 --- a/docs/_docs/tools/control-script.adoc +++ b/docs/_docs/tools/control-script.adoc @@ -163,9 +163,8 @@ Enable it in the configuration (`IgniteConfiguration#setClientConnectorConfigura == Reloading TLS Certificates Use `--ssl reload` to load replaced key and trust stores on all server and thick-client nodes in the current topology. -It reloads discovery, communication, client connector, and binary REST transports that started with TLS. +It reloads discovery, communication, client connector, binary REST, and the link:restapi#https[HTTP REST endpoint] when they use TLS. New connections use the replacement context; established connections stay open. -The command does not reload TLS for the HTTP REST endpoint (Jetty). Follow link:security/ssl-tls#upgrading-certificates[Upgrading Certificates] to prepare peer trust, replace the files, and verify the result. Add the <> required by your cluster: @@ -190,7 +189,7 @@ When security is enabled, logs identify the initiator by login and subject ID. This is the control-script user, or the node receiving a JMX call. The report lists every target node, even if none of its TCP transports use TLS. -Each node first checks that all registered factories extend `AbstractSslContextFactory`. +Each node first checks that the factories of discovery, communication, client connector, and binary REST extend `AbstractSslContextFactory`. If any factory is unsupported, that node reloads none of its factories. Otherwise, it reloads them until the first failure and reports the error. Other nodes continue independently. diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/HotReloadTime.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/HotReloadTime.java new file mode 100644 index 0000000000000..fb102ba628e6a --- /dev/null +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/HotReloadTime.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.apache.ignite.internal.processors.ssl; + +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Enumeration; + +import static java.util.concurrent.TimeUnit.DAYS; + +/** Time when the certificates of a key store are due for hot reload. */ +public final class HotReloadTime { + /** Longest lead time before a certificate expires. */ + private static final long MAX_LEAD_MS = DAYS.toMillis(7); + + /** */ + private HotReloadTime() { + // No-op. + } + + /** + * A certificate is due before it expires by a third of its lifetime, but by no more than 7 days. + * The key store is due when the first certificate in its private key chains is due, including issuing certificates. + * Keys without an X.509 certificate chain are ignored, as TLS cannot use them. + * + * @param store Loaded key store. + * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the store has no private key + * with an X.509 certificate chain. + * @throws GeneralSecurityException If the key store cannot be read. + */ + public static long of(KeyStore store) throws GeneralSecurityException { + long earliest = Long.MAX_VALUE; + + for (Enumeration aliases = store.aliases(); aliases.hasMoreElements(); ) { + String alias = aliases.nextElement(); + + if (store.isKeyEntry(alias)) + earliest = Math.min(earliest, chainTime(store.getCertificateChain(alias))); + } + + return earliest == Long.MAX_VALUE ? 0 : earliest; + } + + /** + * @param chain Certificate chain of a key entry, or {@code null} if the entry has none. + * @return Time when the first certificate in the chain is due, or {@link Long#MAX_VALUE} if there is no chain + * or it holds a certificate other than X.509, as TLS ignores such keys. + */ + private static long chainTime(Certificate[] chain) { + long time = Long.MAX_VALUE; + + if (chain == null) + return time; + + for (Certificate cert : chain) { + if (!(cert instanceof X509Certificate x509)) + return Long.MAX_VALUE; + + long notAfter = x509.getNotAfter().getTime(); + long lifetime = notAfter - x509.getNotBefore().getTime(); + + time = Math.min(time, notAfter - Math.min(MAX_LEAD_MS, lifetime / 3)); + } + + return time; + } +} diff --git a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java index 5f0b0447a4feb..d2b723d3b2c3b 100644 --- a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java @@ -21,10 +21,6 @@ import java.security.KeyManagementException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.Enumeration; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.cache.configuration.Factory; import javax.net.ssl.KeyManager; @@ -34,6 +30,7 @@ import javax.net.ssl.SSLParameters; import javax.net.ssl.TrustManager; import org.apache.ignite.IgniteException; +import org.apache.ignite.internal.processors.ssl.HotReloadTime; import org.apache.ignite.internal.util.typedef.internal.A; /** @@ -46,9 +43,6 @@ public abstract class AbstractSslContextFactory implements Factory { /** Default SSL protocol. */ public static final String DFLT_SSL_PROTOCOL = "TLS"; - /** Default lead time for certificate hot reload: 7 days. */ - public static final long DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS = TimeUnit.DAYS.toMillis(7); - /** SSL protocol. */ protected String proto = DFLT_SSL_PROTOCOL; @@ -62,65 +56,23 @@ public abstract class AbstractSslContextFactory implements Factory { protected final AtomicReference sslCtx = new AtomicReference<>(); /** */ - private boolean hotReloadEnabled; - - /** */ - private volatile long hotReloadBeforeExpiryMs = DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; + private transient volatile long hotReloadTime; /** */ - private transient volatile long earliestExpiry; - - /** */ - private transient long pendingExpiry; - - /** - * Automatic hot reload takes its date from the key store that the factory passes to - * {@link #createKeyManagers(KeyManagerFactory, KeyStore, char[])}. - * - * @return Whether automatic certificate hot reload is enabled. Defaults to {@code false}. - */ - public boolean isHotReloadEnabled() { - return hotReloadEnabled; - } - - /** - * @param enabled Whether automatic certificate hot reload is enabled. Changes require a node restart. - */ - public void setHotReloadEnabled(boolean enabled) { - hotReloadEnabled = enabled; - } - - /** - * @return How long before the certificates expire hot reload becomes due, in milliseconds. - * Defaults to {@link #DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. - */ - public long getHotReloadBeforeExpiryMs() { - return hotReloadBeforeExpiryMs; - } - - /** - * @param millis How long before the certificates expire hot reload becomes due, in milliseconds. Must be positive. - */ - public void setHotReloadBeforeExpiryMs(long millis) { - A.ensure(millis > 0, "millis > 0"); - - hotReloadBeforeExpiryMs = millis; - } + private transient long pendingHotReloadTime; /** * The hot reload time is calculated from the key store passed to * {@link #createKeyManagers(KeyManagerFactory, KeyStore, char[])} during the last successful load. - * It comes {@link #getHotReloadBeforeExpiryMs()} before the earliest expiry among the chains of the private keys. - * A chain expires when any certificate in it expires. + * Each certificate in the chains of the private keys is due before it expires by a third of its lifetime, + * but by no more than 7 days. The factory is due when its first certificate is due. * Keys without an X.509 certificate chain are ignored, as TLS cannot use them. * * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the certificates have not been loaded yet * or the last successful load supplied no key store or no private key with an X.509 chain. */ public long getHotReloadTime() { - long expiry = earliestExpiry; - - return expiry == 0 ? 0 : expiry - hotReloadBeforeExpiryMs; + return hotReloadTime; } /** @@ -188,7 +140,7 @@ public void setProtocols(String... protocols) { private SSLContext createSslContext() throws SSLException { checkParameters(); - pendingExpiry = 0; + pendingHotReloadTime = 0; KeyManager[] keyMgrs = createKeyManagers(); @@ -211,7 +163,7 @@ private SSLContext createSslContext() throws SSLException { ctx.init(keyMgrs, trustMgrs, null); - earliestExpiry = pendingExpiry; + hotReloadTime = pendingHotReloadTime; return ctx; } @@ -260,53 +212,11 @@ protected final synchronized KeyManager[] createKeyManagers(KeyManagerFactory ke throws GeneralSecurityException { keyMgrFactory.init(store, pwd); - pendingExpiry = keyChainsExpiry(store); + pendingHotReloadTime = HotReloadTime.of(store); return keyMgrFactory.getKeyManagers(); } - /** - * @param store Loaded key store. - * @return Earliest certificate expiry in the private key chains, or {@code 0} if the store has no private key - * with an X.509 certificate chain. - * @throws GeneralSecurityException If the key store cannot be read. - */ - private static long keyChainsExpiry(KeyStore store) throws GeneralSecurityException { - long earliest = Long.MAX_VALUE; - - for (Enumeration aliases = store.aliases(); aliases.hasMoreElements(); ) { - String alias = aliases.nextElement(); - - if (!store.isKeyEntry(alias)) - continue; - - earliest = Math.min(earliest, chainExpiry(store.getCertificateChain(alias))); - } - - return earliest == Long.MAX_VALUE ? 0 : earliest; - } - - /** - * @param chain Certificate chain of a key entry, or {@code null} if the entry has none. - * @return Earliest expiry in the chain, or {@link Long#MAX_VALUE} if there is no chain or it holds a certificate other - * than X.509, as TLS ignores such keys. - */ - private static long chainExpiry(Certificate[] chain) { - long expiry = Long.MAX_VALUE; - - if (chain == null) - return expiry; - - for (Certificate cert : chain) { - if (!(cert instanceof X509Certificate x509)) - return Long.MAX_VALUE; - - expiry = Math.min(expiry, x509.getNotAfter().getTime()); - } - - return expiry; - } - /** * @return Created Trust Managers. * @throws SSLException If Trust Managers could not be created. diff --git a/modules/core/src/main/java/org/apache/ignite/internal/management/ssl/SslReloadTask.java b/modules/core/src/main/java/org/apache/ignite/internal/management/ssl/SslReloadTask.java index 116a8ade16929..2ad637d3952ca 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/management/ssl/SslReloadTask.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/management/ssl/SslReloadTask.java @@ -24,21 +24,19 @@ import java.util.Map; import java.util.Map.Entry; import java.util.UUID; -import javax.cache.configuration.Factory; -import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.cluster.ClusterTopologyException; import org.apache.ignite.compute.ComputeJob; import org.apache.ignite.compute.ComputeJobResult; import org.apache.ignite.internal.management.api.NoArg; +import org.apache.ignite.internal.processors.ssl.SslFactoryRegistry; import org.apache.ignite.internal.processors.task.GridInternal; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.visor.VisorJob; import org.apache.ignite.internal.visor.VisorMultiNodeTask; import org.apache.ignite.internal.visor.VisorTaskArgument; import org.apache.ignite.plugin.security.SecuritySubject; -import org.apache.ignite.ssl.AbstractSslContextFactory; import static java.util.stream.Collectors.joining; @@ -118,7 +116,7 @@ private SslReloadJob(NoArg arg, boolean debug) { /** {@inheritDoc} */ @Override protected String run(NoArg arg) { - List, String>> factories = ignite.context().ssl().factories(); + List> factories = ignite.context().ssl().factories(); UUID nodeId = ignite.localNode().id(); String initiator = ""; @@ -136,8 +134,8 @@ private SslReloadJob(NoArg arg, boolean debug) { return report; } - for (Entry, String> entry : factories) { - if (!(entry.getKey() instanceof AbstractSslContextFactory)) { + for (Entry entry : factories) { + if (!SslFactoryRegistry.supportsReload(entry.getKey())) { String report = entry.getValue() + ": unsupported: " + entry.getKey().getClass().getName(); ignite.log().warning("TLS reload: " + nodeId + ": " + report + initiator); @@ -148,11 +146,11 @@ private SslReloadJob(NoArg arg, boolean debug) { List reports = new ArrayList<>(); - for (Entry, String> entry : factories) { + for (Entry entry : factories) { String transports = entry.getValue(); try { - ignite.context().ssl().reload((AbstractSslContextFactory)entry.getKey()); + ignite.context().ssl().reload(entry.getKey()); } catch (Exception e) { ignite.log().warning("TLS reload: " + nodeId + ": " + transports + ": failed" + initiator, e); diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java new file mode 100644 index 0000000000000..fa2261ba3b9d5 --- /dev/null +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.apache.ignite.internal.processors.ssl; + +/** TLS factory of a transport that does not use an Ignite SSL context factory, such as HTTP REST with Jetty. */ +public interface ReloadableSslFactory { + /** + * Loads the keys and trust settings again for new connections. If loading fails, new connections keep the previous ones. + * + * @throws org.apache.ignite.IgniteException If loading fails. + */ + public void reload(); + + /** + * @return Time when the certificates of the last successful load are due for hot reload, as calculated by + * {@link HotReloadTime#of}, or {@code 0} if they give none. + */ + public long hotReloadTime(); +} diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index b23a170f33d93..a1cc0e0cd4364 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -34,7 +34,6 @@ import org.apache.ignite.internal.processors.metric.MetricRegistryImpl; import org.apache.ignite.internal.thread.context.function.OperationContextAwareRunnable; import org.apache.ignite.ssl.AbstractSslContextFactory; -import org.jetbrains.annotations.Nullable; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MILLISECONDS; @@ -63,7 +62,17 @@ public SslFactoryRegistry(GridKernalContext ctx) { } /** */ - public synchronized void register(String transport, Factory factory) { + public void register(String transport, Factory factory) { + add(transport, factory); + } + + /** */ + public void register(String transport, ReloadableSslFactory factory) { + add(transport, factory); + } + + /** */ + private synchronized void add(String transport, Object factory) { for (int i = 0; i < factories.size(); i++) { RegisteredFactory registered = factories.get(i); @@ -78,8 +87,8 @@ public synchronized void register(String transport, Factory factory) } /** @return Registered factories in registration order, each with its transports joined by commas. */ - public List, String>> factories() { - List, String>> res = new ArrayList<>(factories.size()); + public List> factories() { + List> res = new ArrayList<>(factories.size()); for (RegisteredFactory registered : factories) res.add(Map.entry(registered.factory, registered.transports)); @@ -100,10 +109,8 @@ public List, String>> factories() { boolean hotReload = false; for (RegisteredFactory registered : factories) { - AbstractSslContextFactory sslFactory = registered.hotReloadFactory(); - - if (sslFactory != null) { - registered.logHotReloadTime(sslFactory.getHotReloadTime()); + if (supportsReload(registered.factory)) { + registered.logHotReloadTime(registered.hotReloadTime()); hotReload = true; } @@ -128,13 +135,13 @@ private long consecutiveHotReloadFailures() { return sum; } - /** Runs the hourly check of the factories with hot reload enabled. */ + /** Runs the hourly check of the factories that support reload. */ private void checkFactories() { if (log.isDebugEnabled()) log.debug("TLS hot reload check started"); for (RegisteredFactory registered : factories) { - if (registered.hotReloadFactory() != null) + if (supportsReload(registered.factory)) registered.check(); } } @@ -146,22 +153,29 @@ private void checkFactories() { } /** - * Reloads a registered factory. For a factory with hot reload enabled, waits for its running check and resets its failure - * count. + * Reloads a registered factory. Waits for its running check and resets its failure count. * - * @param factory Registered factory to reload. + * @param factory Registered factory that supports reload. */ - public void reload(AbstractSslContextFactory factory) { + public void reload(Object factory) { for (RegisteredFactory registered : factories) { if (registered.factory == factory) registered.reload(); } } + /** + * @param factory Registered factory. + * @return Whether the registry can reload the factory. + */ + public static boolean supportsReload(Object factory) { + return factory instanceof AbstractSslContextFactory || factory instanceof ReloadableSslFactory; + } + /** Registered factory with its transports and hot reload state. The hourly check and manual reload hold its monitor. */ private class RegisteredFactory { /** */ - private final Factory factory; + private final Object factory; /** */ private final String transports; @@ -170,14 +184,24 @@ private class RegisteredFactory { private final AtomicInteger failures = new AtomicInteger(); /** */ - private RegisteredFactory(Factory factory, String transports) { + private RegisteredFactory(Object factory, String transports) { this.factory = factory; this.transports = transports; } - /** @return The factory if hot reload is enabled for it, {@code null} otherwise. */ - @Nullable private AbstractSslContextFactory hotReloadFactory() { - return factory instanceof AbstractSslContextFactory sslFactory && sslFactory.isHotReloadEnabled() ? sslFactory : null; + /** Loads the factory again. If loading fails, it keeps its previous context. */ + private void load() { + if (factory instanceof ReloadableSslFactory reloadable) + reloadable.reload(); + else + ((AbstractSslContextFactory)factory).init(); + } + + /** @return Hot reload time of the certificates that the factory loaded last. */ + private long hotReloadTime() { + return factory instanceof ReloadableSslFactory reloadable + ? reloadable.hotReloadTime() + : ((AbstractSslContextFactory)factory).getHotReloadTime(); } /** @@ -210,9 +234,7 @@ else if (log.isDebugEnabled()) * @throws IgniteException If the reload fails or leaves certificates that are still due. */ private void reloadIfDue() { - AbstractSslContextFactory sslFactory = (AbstractSslContextFactory)factory; - - if (!due(sslFactory.getHotReloadTime())) { + if (!due(hotReloadTime())) { failures.set(0); return; @@ -223,9 +245,9 @@ private void reloadIfDue() { if (log.isInfoEnabled()) log.info("TLS hot reload started [transports=" + transports + ']'); - sslFactory.init(); + load(); - long hotReloadTime = sslFactory.getHotReloadTime(); + long hotReloadTime = hotReloadTime(); if (due(hotReloadTime)) { throw new IgniteException("Loaded certificates are still due for hot reload [hotReloadTime=" @@ -249,15 +271,11 @@ private static boolean due(long hotReloadTime) { private synchronized void reload() { manualReloadAttempts.incrementAndGet(); - ((AbstractSslContextFactory)factory).init(); + load(); - AbstractSslContextFactory sslFactory = hotReloadFactory(); - - if (sslFactory != null) { - failures.set(0); + failures.set(0); - logHotReloadTime(sslFactory.getHotReloadTime()); - } + logHotReloadTime(hotReloadTime()); } /** */ diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index aa1e81d26cc48..047d27c18e6ab 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -38,7 +38,6 @@ import javax.net.ssl.TrustManager; import org.apache.ignite.IgniteException; import org.apache.ignite.internal.GridKernalContext; -import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.processors.metric.GridMetricManager; import org.apache.ignite.internal.processors.metric.MetricRegistryImpl; import org.apache.ignite.internal.thread.context.OperationContext; @@ -77,6 +76,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -184,20 +184,41 @@ public void testFactoriesAreGroupedInRegistrationOrder() { } /** - * Given: a factory with hot reload disabled and valid certificates. + * Given: a transport registers a factory that only creates contexts and cannot reload them. * When: the registry starts. * Then: no hot reload thread starts, and the failure metric reads zero. */ @Test - public void testDisabledFactoryDoesNotStartHotReload() throws Exception { - writeFreshCertificates(keys); - registerTransport("communication", factory(keys)); + public void testFactoryWithoutReloadDoesNotStartHotReload() { + registry.register("communication", () -> null); registry.onKernalStart(true); executorFactory.verifyNoInteractions(); assertEquals(0, failures()); } + /** + * Given: HTTP REST registers a factory that is not an Ignite SSL context factory, with certificates due for hot reload. + * When: the hourly check runs, and then a manual reload runs. + * Then: the registry reloads the factory each time and counts one automatic and one manual attempt. + */ + @Test + public void testReloadableFactoryIsHotReloadedAndReloadedManually() { + ReloadableSslFactory rest = mock(ReloadableSslFactory.class); + + when(rest.hotReloadTime()).thenReturn(due(), due(), at(DAYS.toHours(30))); + + registry.register("HTTP REST", rest); + registry.onKernalStart(true); + check.run(); + registry.reload(rest); + + verify(rest, times(2)).reload(); + assertEquals(1, metric("AutomaticHotReloadAttempts")); + assertEquals(1, metric("ManualReloadAttempts")); + assertEquals(0, failures()); + } + /** * Given: communication and discovery share a factory, and the client connector has an equal factory for the same file. * When: the key store is replaced and the hourly check runs. @@ -209,8 +230,6 @@ public void testEachFactoryInstanceReloadsOnce() throws Exception { SslContextFactory clientConnector = factory(keys, new KeyStorePathFactory()); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); - clientConnector.setHotReloadEnabled(true); registerTransport("communication", communication); registerTransport("discovery", communication); registerTransport("client connector", clientConnector); @@ -237,8 +256,6 @@ public void testManualReloadLoadsOnlyItsFactoryInstance() throws Exception { SslContextFactory clientConnector = factory(keys, new KeyStorePathFactory()); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); - clientConnector.setHotReloadEnabled(true); registerTransport("communication", communication); registerTransport("client connector", clientConnector); registry.onKernalStart(true); @@ -253,7 +270,7 @@ public void testManualReloadLoadsOnlyItsFactoryInstance() throws Exception { } /** - * Given: hot reload is enabled, and the key store holds only a CA certificate. + * Given: the key store holds only a CA certificate. * When: the registry starts and the hourly check runs, then the operator puts a key store with a private key in place * and reloads it. * Then: the registry logs that hot reload will not run, and the check makes no attempt. @@ -265,7 +282,6 @@ public void testStoreWithoutPrivateKeyIsReportedUntilKeysAreReloaded() throws Ex SslContextFactory communication = factory(keys); save(authority.trustStore(), keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); registry.onKernalStart(true); check.run(); @@ -282,7 +298,7 @@ public void testStoreWithoutPrivateKeyIsReportedUntilKeysAreReloaded() throws Ex } /** - * Given: hot reload is enabled for due certificates, and the key store file is deleted after start. + * Given: the loaded certificates are due for hot reload, and the key store file is deleted after start. * When: the hourly check runs three times. * Then: the check runs at start and then every hour, and each run counts one more failed attempt. */ @@ -291,7 +307,6 @@ public void testHotReloadIsCheckedEveryHourFromStart() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); registry.onKernalStart(true); Files.delete(keys); @@ -317,7 +332,7 @@ public void testHotReloadDoesNotInheritStartupContext() throws Exception { OperationContextAttribute reqId = OperationContextAttribute.newInstance(); CompletableFuture reloadReqId = new CompletableFuture<>(); - enableHotReload(factory, due()); + loaded(factory, due()); doAnswer(call -> { reloadReqId.complete(OperationContext.get(reqId)); @@ -344,10 +359,9 @@ public void testErrorFromOneFactoryDoesNotStopCheck() throws Exception { List logged = captureLog(); SslContextFactory clientConnector = factory(keys); - enableHotReload(factory, due()); + loaded(factory, due()); doThrow(new NoClassDefFoundError("Key store provider")).when(factory).init(); writeDueCertificates(keys); - clientConnector.setHotReloadEnabled(true); registry.register("communication", factory); registerTransport("client connector", clientConnector); registry.onKernalStart(true); @@ -361,7 +375,7 @@ public void testErrorFromOneFactoryDoesNotStopCheck() throws Exception { } /** - * Given: hot reload is enabled for due certificates, and the key store file is deleted after start. + * Given: the loaded certificates are due for hot reload, and the key store file is deleted after start. * When: one automatic attempt fails, and the next one loads fresh certificates. * Then: the log shows when the loaded certificates are due for hot reload, and the start and result of each attempt. */ @@ -371,7 +385,6 @@ public void testLogShowsDueTimeStartAndResultOfAttempts() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); registry.onKernalStart(true); @@ -397,7 +410,7 @@ public void testLogShowsDueTimeStartAndResultOfAttempts() throws Exception { } /** - * Given: hot reload is enabled for due certificates, and the key store file is deleted after start. + * Given: the loaded certificates are due for hot reload, and the key store file is deleted after start. * When: one check fails, the source then gets certificates due for hot reload in 23 days, the next check loads them, * and the check runs again. * Then: both attempts are counted, the success resets the failure count, and the last check makes no attempt. @@ -407,7 +420,6 @@ public void testSuccessResetsFailuresAndLaterChecksWait() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); registry.onKernalStart(true); Files.delete(keys); @@ -438,7 +450,6 @@ public void testCheckResetsFailuresWhenFactoryIsNoLongerDue() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); registry.onKernalStart(true); check.run(); @@ -454,7 +465,7 @@ public void testCheckResetsFailuresWhenFactoryIsNoLongerDue() throws Exception { } /** - * Given: a factory with hot reload enabled is registered, and the registry has not started yet. + * Given: a factory is registered, and the registry has not started yet. * When: the key store is replaced, and a manual reload runs. * Then: the factory loads the new certificates. */ @@ -463,7 +474,6 @@ public void testManualReloadBeforeStartLoadsFactory() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); long prevTime = communication.getHotReloadTime(); @@ -475,12 +485,12 @@ public void testManualReloadBeforeStartLoadsFactory() throws Exception { } /** - * Given: a factory with hot reload disabled. + * Given: a factory with certificates that are not due for hot reload. * When: a manual reload succeeds, and a second one fails because the key store file is deleted. * Then: both count as manual attempts, and none counts as automatic. */ @Test - public void testManualReloadWithoutHotReloadCountsAppliedAndFailedLoads() throws Exception { + public void testManualReloadCountsAppliedAndFailedLoads() throws Exception { SslContextFactory communication = factory(keys); writeFreshCertificates(keys); @@ -506,8 +516,7 @@ public void testManualReloadWithoutHotReloadCountsAppliedAndFailedLoads() throws public void testScheduledReloadUsesCustomFactoryKeyStoreAndPassword() throws Exception { SourceSslContextFactory custom = new SourceSslContextFactory(); - custom.setKeys(authority.keyStore("node", at(-1), at(10)), PASSWORD); - custom.setHotReloadEnabled(true); + custom.setKeys(authority.keyStore("node", at(-30), at(10)), PASSWORD); SSLContext initCtx = custom.create(); @@ -524,11 +533,11 @@ public void testScheduledReloadUsesCustomFactoryKeyStoreAndPassword() throws Exc long expiry = ((X509Certificate)replacement.getCertificate("node")).getNotAfter().getTime(); - assertEquals(expiry - custom.getHotReloadBeforeExpiryMs(), custom.getHotReloadTime()); + assertEquals(expiry - DAYS.toMillis(7), custom.getHotReloadTime()); } /** - * Given: hot reload is enabled for a custom factory that has loaded a key store with due certificates. + * Given: a custom factory has loaded a key store with due certificates. * When: a manual reload creates the context without a key store, and the scheduled check runs. * Then: the factory has no hot reload date, and the check makes no attempt. */ @@ -537,7 +546,6 @@ public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { SourceSslContextFactory custom = new SourceSslContextFactory(); custom.setKeys(authority.keyStore("node", at(-1), at(10)), PASSWORD); - custom.setHotReloadEnabled(true); custom.create(); assertTrue(custom.getHotReloadTime() > 0); @@ -579,7 +587,6 @@ public void testFailedManualReloadKeepsFailures() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); registry.onKernalStart(true); Files.delete(keys); @@ -591,48 +598,6 @@ public void testFailedManualReloadKeepsFailures() throws Exception { assertEquals(1, failures()); } - /** - * Given: communication only reloads manually, and the client connector is due for hot reload. - * When: the hourly check runs while communication is waiting for its certificate source. - * Then: the client connector loads its replacement before the manual reload finishes. - */ - @Test - public void testManualOnlyFactoryDoesNotDelayHotReload() throws Exception { - SslContextFactory clientConnector = factory(keys); - CountDownLatch manualStarted = new CountDownLatch(1); - CountDownLatch finishManual = new CountDownLatch(1); - - doAnswer(call -> { - manualStarted.countDown(); - finishManual.await(); - - return null; - }).when(factory).init(); - - writeDueCertificates(keys); - clientConnector.setHotReloadEnabled(true); - registry.register("communication", factory); - registerTransport("client connector", clientConnector); - registry.onKernalStart(true); - - long prevTime = clientConnector.getHotReloadTime(); - - writeFreshCertificates(keys); - - IgniteInternalFuture manual = runAsync(() -> registry.reload(factory)); - - try { - assertTrue(manualStarted.await(TIMEOUT_MS, MILLISECONDS)); - runAsync(check).get(TIMEOUT_MS); - - assertTrue(clientConnector.getHotReloadTime() > prevTime); - } - finally { - finishManual.countDown(); - manual.get(TIMEOUT_MS); - } - } - /** * Given: an automatic attempt has started, failed to load a missing key store file, and pauses at its stop check * before it counts the failure. @@ -646,7 +611,6 @@ public void testManualReloadWaitsForRunningAttempt() throws Exception { CountDownLatch resumeAttempt = new CountDownLatch(1); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); registry.onKernalStart(true); Files.delete(keys); @@ -705,8 +669,6 @@ public void testManualReloadResetsOnlyItsFactoryFailures() throws Exception { writeFreshCertificates(keys); writeDueCertificates(clientKeys); - communication.setHotReloadEnabled(true); - clientConnector.setHotReloadEnabled(true); registerTransport("communication", communication); registerTransport("client connector", clientConnector); registry.onKernalStart(true); @@ -743,7 +705,7 @@ public void testStopInterruptsActiveAttemptWithoutWaitingForIt() throws Exceptio CountDownLatch attemptInterrupted = new CountDownLatch(1); CountDownLatch allowCompletion = new CountDownLatch(1); - enableHotReload(factory, due()); + loaded(factory, due()); doAnswer(call -> { attemptStarted.countDown(); @@ -784,7 +746,7 @@ public void testStopInterruptsActiveAttemptWithoutWaitingForIt() throws Exceptio public void testAttemptFailingDuringStopIsNotCounted() { List logged = captureLog(true); - enableHotReload(factory, due()); + loaded(factory, due()); doAnswer(call -> { when(executor.isShutdown()).thenReturn(true); @@ -811,8 +773,8 @@ public void testStopDuringCheckSkipsRemainingFactories() { SslContextFactory clientConnector = mock(SslContextFactory.class); AtomicInteger loads = new AtomicInteger(); - enableHotReload(factory, due()); - enableHotReload(clientConnector, due()); + loaded(factory, due()); + loaded(clientConnector, due()); for (SslContextFactory sslFactory : List.of(factory, clientConnector)) { doAnswer(call -> { @@ -874,14 +836,12 @@ private long metric(String name) { } /** - * Makes the factory mock look like a factory with hot reload enabled and loaded certificates with the given date. - * The mock returns {@code true} from {@code isHotReloadEnabled()} and the date from {@code getHotReloadTime()}. + * Makes the factory mock look like a factory that has loaded certificates with the given hot reload date. * * @param factory Factory mock. * @param hotReloadTime Hot reload time of the loaded certificates. */ - private static void enableHotReload(SslContextFactory factory, long hotReloadTime) { - when(factory.isHotReloadEnabled()).thenReturn(true); + private static void loaded(SslContextFactory factory, long hotReloadTime) { when(factory.getHotReloadTime()).thenReturn(hotReloadTime); } @@ -891,7 +851,7 @@ private static long due() { } /** - * Creates a factory with hot reload disabled that reads its key store from the given file. + * Creates a factory that reads its key store from the given file. * The factory trusts the test CA through the trust store file from the setup. */ private SslContextFactory factory(Path keyStore) { @@ -909,7 +869,7 @@ private SslContextFactory factory(Path keyStore, SslContextFactory sslFactory) { } /** - * Writes a key store that is already due for hot reload with the default lead time. + * Writes a key store that is already due for hot reload. * Its certificate expires in 10 hours. */ private void writeDueCertificates(Path keyStore) throws Exception { @@ -917,7 +877,7 @@ private void writeDueCertificates(Path keyStore) throws Exception { } /** - * Writes a key store that is due for hot reload in 23 days with the default lead time. + * Writes a key store that is due for hot reload in 23 days. * Its certificate became valid an hour ago and expires in 30 days. */ private void writeFreshCertificates(Path keyStore) throws Exception { diff --git a/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java b/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java index 98e0e0bb7d315..458c0965f46a9 100644 --- a/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java +++ b/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java @@ -66,8 +66,6 @@ public void testNodeHotReloadsCertificatesForNewConnections() throws Exception { SslContextFactory serverFactory = configure(new SslContextFactory(), keys, trust); - serverFactory.setHotReloadEnabled(true); - SSLContext initCtx = serverFactory.create(); assertTrue("Hot reload must be due at startup", serverFactory.getHotReloadTime() < now); @@ -97,7 +95,7 @@ public void testNodeHotReloadsCertificatesForNewConnections() throws Exception { } /** - * Given: a node with hot reload enabled starts with expired certificates, so hot reload stays due. + * Given: a node starts with expired certificates, so hot reload stays due. * When: the automatic attempt reloads the same certificates. * Then: the node counts the failure and logs the transport and the reason. */ @@ -121,8 +119,6 @@ public void testNodeReportsHotReloadFailureForExpiredCertificates() throws Excep SslContextFactory serverFactory = configure(new SslContextFactory(), keys, trust); - serverFactory.setHotReloadEnabled(true); - IgniteEx node = startGrid(0, cfg -> { cfg.setGridLogger(nodeLog).setClientConnectorConfiguration(sslClientConnector(serverFactory)); }); @@ -139,7 +135,7 @@ public void testNodeReportsHotReloadFailureForExpiredCertificates() throws Excep } /** - * Given: a node with hot reload enabled runs its hot reload thread. + * Given: a node with a TLS transport runs its hot reload thread. * When: the node stops. * Then: the hot reload thread ends. */ @@ -157,8 +153,6 @@ public void testNodeStopEndsHotReloadThread() throws Exception { SslContextFactory serverFactory = configure(new SslContextFactory(), keys, trust); - serverFactory.setHotReloadEnabled(true); - IgniteEx node = startGrid(0, cfg -> { cfg.setClientConnectorConfiguration(sslClientConnector(serverFactory)); }); diff --git a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java index ee4120e4100e6..a5042cd4aa187 100644 --- a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java +++ b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java @@ -43,7 +43,6 @@ import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.apache.ignite.ssl.SslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD; import static org.apache.ignite.ssl.TestCertificateAuthority.merge; import static org.apache.ignite.ssl.TestCertificateAuthority.save; @@ -84,69 +83,41 @@ public void setUp() throws Exception { } /** - * Given: a key store with only a CA certificate and the default hot reload setting. + * Given: a key store with only a CA certificate. * When: the factory loads the store. - * Then: the load succeeds with hot reload disabled and no scheduled reload date. + * Then: the load succeeds, and the factory has no hot reload date. */ @Test - public void testDefaultSettingsAcceptStoreWithoutPrivateKeys() throws Exception { + public void testStoreWithOnlyCaCertificateHasNoHotReloadDate() throws Exception { InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.trustStore()); - assertFalse(factory.isHotReloadEnabled()); assertNotNull(factory.create()); assertEquals(0, factory.getHotReloadTime()); } /** - * Given: a factory has loaded a certificate that expires in 10 days. - * When: the application increases the lead time from the default of 7 days to 14 days before starting the node. - * Then: the same certificate is already due for hot reload. + * Given: a certificate valid for 24 hours and a certificate valid for 90 days, both issued by a CA valid for 2 years. + * When: the factory loads each of them. + * Then: hot reload is due 8 hours, a third of the lifetime, before the first one expires, and 7 days before the + * second one expires, as a third of 90 days exceeds 7 days. */ @Test - public void testHotReloadTimeUsesCurrentLeadTime() throws Exception { - Path keys = tmp.newFile("keys.jks").toPath(); - - save(authority.keyStore("node", at(-1), at(DAYS.toHours(10))), keys); - - SslContextFactory factory = new SslContextFactory(); - - factory.setKeyStoreFilePath(keys.toString()); - factory.setKeyStorePassword(PASSWORD); - factory.setTrustManagers(SslContextFactory.getDisabledTrustManager()); - factory.create(); - - assertEquals(at(DAYS.toHours(3)), factory.getHotReloadTime()); - - factory.setHotReloadBeforeExpiryMs(DAYS.toMillis(14)); - - assertEquals(at(-DAYS.toHours(4)), factory.getHotReloadTime()); + public void testHotReloadLeadIsThirdOfLifetimeUpToSevenDays() throws Exception { + assertHotReloadTime(at(4), authority.keyStore("node", at(-12), at(12))); + assertHotReloadTime(at(DAYS.toHours(30 - 7)), authority.keyStore("node", at(-DAYS.toHours(60)), at(DAYS.toHours(30)))); } /** - * Given: a factory with the default lead time. - * When: the application sets a zero or negative lead time. - * Then: the setter rejects it and keeps the default. + * Given: key stores in which the certificate due first was issued 30 hours ago and expires in 15 hours. + * In one of them, that certificate is the issuer of a key certificate that is due later. + * Other entries are a chain that is due later, a secret key and a key with a certificate chain that is not X.509. + * When: the factory loads each key store. + * Then: hot reload is due now, a third of the 45-hour lifetime before that certificate expires. */ @Test - public void testNonPositiveHotReloadBeforeExpiryMsIsRejected() { - SslContextFactory factory = new SslContextFactory(); - - assertThrows(IllegalArgumentException.class, () -> factory.setHotReloadBeforeExpiryMs(0)); - assertThrows(IllegalArgumentException.class, () -> factory.setHotReloadBeforeExpiryMs(-1)); - assertEquals(DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS, factory.getHotReloadBeforeExpiryMs()); - } - - /** - * Given: key stores in which the chain that expires first has 15 hours left. - * In one of them, that chain gets its expiry from an issuer that expires before the key certificate. - * Other entries are a chain that expires later, a secret key and a key with a certificate chain that is not X.509. - * When: the factory loads each key store with hot reload enabled. - * Then: hot reload is due now, 15 hours before the chain that expires first. - */ - @Test - public void testHotReloadTimeComesFromEarliestExpiringChain() throws Exception { - TestCertificateAuthority shortIssuer = new TestCertificateAuthority("short-issuer", now - DAYS.toMillis(365), at(15)); - KeyStore node = authority.keyStore("node", at(-85), at(15)); + public void testHotReloadTimeComesFromCertificateDueFirst() throws Exception { + TestCertificateAuthority shortIssuer = new TestCertificateAuthority("short-issuer", at(-30), at(15)); + KeyStore node = authority.keyStore("node", at(-30), at(15)); KeyStore withUnusableKeys = KeyStore.getInstance("JCEKS"); withUnusableKeys.load(null, PASSWORD); @@ -155,15 +126,15 @@ public void testHotReloadTimeComesFromEarliestExpiringChain() throws Exception { withUnusableKeys.setKeyEntry("other", node.getKey("node", PASSWORD), PASSWORD, new Certificate[] {new OtherCertificate(node.getCertificate("node").getPublicKey())}); - assertHotReloadIsDueNow(node); - assertHotReloadIsDueNow(shortIssuer.keyStore("node", at(-85), at(100))); - assertHotReloadIsDueNow(merge(authority.keyStore("first", at(-85), at(15)), authority.keyStore("second", at(-200), at(100)))); - assertHotReloadIsDueNow(merge(authority.keyStore("first", at(-200), at(100)), authority.keyStore("second", at(-85), at(15)))); - assertHotReloadIsDueNow(withUnusableKeys); + assertHotReloadTime(now, node); + assertHotReloadTime(now, shortIssuer.keyStore("node", at(-60), at(100))); + assertHotReloadTime(now, merge(authority.keyStore("first", at(-30), at(15)), authority.keyStore("second", at(-100), at(200)))); + assertHotReloadTime(now, merge(authority.keyStore("first", at(-100), at(200)), authority.keyStore("second", at(-30), at(15)))); + assertHotReloadTime(now, withUnusableKeys); } /** - * Given: a factory with hot reload enabled and an in-memory key store that counts its reads. + * Given: a factory and an in-memory key store that counts its reads. * When: the factory loads its certificates. * Then: it reads the key store once, so the hot reload date matches the loaded key managers. */ @@ -171,26 +142,25 @@ public void testHotReloadTimeComesFromEarliestExpiringChain() throws Exception { public void testLoadReadsKeyStoreOnce() throws Exception { InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.keyStore("node", at(-85), at(15))); - factory.setHotReloadEnabled(true); factory.create(); assertEquals(1, factory.keyStoreLoads); } /** - * Given: the issuer expired an hour ago, and the key certificate becomes valid in 99 hours. - * When: the factory loads the chain for the first time with hot reload enabled. - * Then: the load succeeds, and hot reload has been due since 15 hours before the issuer expired. + * Given: the issuer was valid for 99 hours and expired an hour ago, and the key certificate becomes valid in 99 hours. + * When: the factory loads the chain for the first time. + * Then: the load succeeds, and hot reload has been due since 33 hours, a third of the issuer's lifetime, before + * the issuer expired. */ @Test public void testFirstLoadAcceptsChainOutsideValidityPeriod() throws Exception { TestCertificateAuthority expiredIssuer = new TestCertificateAuthority("expired-issuer", at(-100), at(-1)); InMemorySslContextFactory factory = new InMemorySslContextFactory(expiredIssuer.keyStore("node", at(99), at(199))); - factory.setHotReloadEnabled(true); factory.create(); - assertEquals(at(-16), factory.getHotReloadTime()); + assertEquals(at(-34), factory.getHotReloadTime()); } /** @@ -207,8 +177,6 @@ public void testStoreWithoutPrivateKeyLoadsWithoutHotReloadDate() throws Excepti InMemorySslContextFactory factory = new InMemorySslContextFactory(store); - factory.setHotReloadEnabled(true); - assertNotNull(factory.create()); assertEquals(0, factory.getHotReloadTime()); } @@ -300,15 +268,14 @@ public void testReloadRecoversAfterFailedTrustStoreLoad() throws Exception { save(authority.trustStore(), trust); - InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.keyStore("node", at(-90), at(10))); + InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.keyStore("node", at(-80), at(10))); factory.useTrustStore(trust.toString()); - factory.setHotReloadEnabled(true); SSLContext ctx = factory.create(); long hotReloadTime = factory.getHotReloadTime(); - factory.keyStore = authority.keyStore("node", at(-1), at(99)); + factory.keyStore = authority.keyStore("node", at(-1), at(101)); Files.delete(trust); IgniteException err = assertThrows(IgniteException.class, factory::init); @@ -321,7 +288,7 @@ public void testReloadRecoversAfterFailedTrustStoreLoad() throws Exception { factory.init(); assertNotSame(ctx, factory.create()); - assertEquals(at(84), factory.getHotReloadTime()); + assertEquals(at(67), factory.getHotReloadTime()); } /** @@ -366,30 +333,28 @@ public void testHotReloadTimeRemainsReadableDuringLoad() throws Exception { } /** - * Creates a factory with hot reload enabled that has loaded certificates due for hot reload 5 hours ago. - * It reads both stores from memory. The certificates expire in 10 hours. + * Creates a factory that has loaded certificates due for hot reload 20 hours ago. + * It reads both stores from memory. The certificates were issued 80 hours ago and expire in 10 hours. */ private InMemorySslContextFactory dueFactory() throws Exception { - InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.keyStore("node", at(-90), at(10))); + InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.keyStore("node", at(-80), at(10))); factory.trustStore = authority.trustStore(); factory.useTrustStore("memory-trust"); - factory.setHotReloadEnabled(true); factory.create(); - assertEquals(at(-5), factory.getHotReloadTime()); + assertEquals(at(-20), factory.getHotReloadTime()); return factory; } - /** */ - private void assertHotReloadIsDueNow(KeyStore keys) { + /** Checks the hot reload time of a factory that has loaded the given key store. */ + private static void assertHotReloadTime(long expected, KeyStore keys) { InMemorySslContextFactory factory = new InMemorySslContextFactory(keys); - factory.setHotReloadEnabled(true); factory.create(); - assertEquals(now, factory.getHotReloadTime()); + assertEquals(expected, factory.getHotReloadTime()); } /** @@ -438,7 +403,6 @@ private long at(long hours) { * A factory that reads its key store from a field instead of a file and counts the reads. * Tests change the field to put new certificates into the source. * By default the factory trusts all peers. Tests can configure a trust store from memory or a file. - * Hot reload is due 15 hours before expiry, so the tests count certificate dates in hours. */ private static class InMemorySslContextFactory extends SslContextFactory { /** */ @@ -460,7 +424,6 @@ private InMemorySslContextFactory(KeyStore keyStore) { setKeyStoreFilePath("memory"); setKeyStorePassword(PASSWORD); setTrustManagers(getDisabledTrustManager()); - setHotReloadBeforeExpiryMs(HOURS.toMillis(15)); } /** Selects the trust store that supplies the factory's trust managers. */ diff --git a/modules/rest-http/pom.xml b/modules/rest-http/pom.xml index ab1babea78989..8e4285478ef08 100644 --- a/modules/rest-http/pom.xml +++ b/modules/rest-http/pom.xml @@ -121,6 +121,13 @@ test + + org.bouncycastle + bcpkix-jdk18on + ${bouncycastle.version} + test + + ${project.groupId} ignite-tools diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java index 5bdad0701d9f7..7edc067fd42db 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java @@ -23,6 +23,7 @@ import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; +import java.security.GeneralSecurityException; import java.util.Collection; import java.util.EnumSet; import java.util.HashSet; @@ -173,11 +174,21 @@ else if (log.isDebugEnabled()) connector.setPort(port); if (startJetty()) { + SslConnectionFactory tls = connector.getConnectionFactory(SslConnectionFactory.class); + + if (tls != null) { + try { + ctx.ssl().register("HTTP REST", new ReloadableJettySslFactory(tls.getSslContextFactory())); + } + catch (GeneralSecurityException e) { + throw new IgniteCheckedException("Failed to read the key store of the HTTPS connector.", e); + } + } + if (log.isInfoEnabled()) { log.info(startInfo()); - boolean isSsl = connector.getConnectionFactory(SslConnectionFactory.class) != null; - String proto = isSsl ? "https" : "http"; + String proto = tls == null ? "http" : "https"; log.info("HTTP REST protocol address: " + proto + "://" + host + ":" + port + "/"); } diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java new file mode 100644 index 0000000000000..d5976c0307a55 --- /dev/null +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -0,0 +1,145 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.apache.ignite.internal.processors.rest.protocols.http.jetty; + +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import javax.net.ssl.SSLContext; +import org.apache.ignite.IgniteException; +import org.apache.ignite.internal.processors.ssl.HotReloadTime; +import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.jetbrains.annotations.Nullable; + +/** + * TLS factory of the Jetty HTTPS connector. A failed reload leaves the previous keys and trust settings in use. + *

+ * Jetty clears the TLS state of its factory before it loads the replacement, and new connections take that state under + * the factory's lock. Jetty lets callers hold this lock only inside {@link SslContextFactory#reload}. So the whole reload + * runs inside an outer {@code reload()} call, and new connections wait for it to finish: they get either the replacement + * or the previous context, never a factory without keys. + */ +class ReloadableJettySslFactory implements ReloadableSslFactory { + /** */ + private final SslContextFactory factory; + + /** */ + private volatile long hotReloadTime; + + /** + * @param factory Started TLS factory of the HTTPS connector. + * @throws GeneralSecurityException If the loaded key store cannot be read. + */ + ReloadableJettySslFactory(SslContextFactory factory) throws GeneralSecurityException { + this.factory = factory; + + hotReloadTime = hotReloadTime(factory); + } + + /** {@inheritDoc} */ + @Override public void reload() { + try { + factory.reload(this::reloadLocked); + } + catch (ReloadDone done) { + if (done.err != null) + throw new IgniteException(done.err); + } + catch (Exception e) { + throw new IgniteException(e); + } + } + + /** {@inheritDoc} */ + @Override public long hotReloadTime() { + return hotReloadTime; + } + + /** + * Reloads the factory while the outer reload holds its lock. If loading fails, gives the factory its previous context + * back. Always throws {@link ReloadDone}, so that the outer reload does not unload and load the factory again. + */ + private void reloadLocked(SslContextFactory f) { + SSLContext prev = activeContext(f); + + try { + f.reload(ignored -> {}); + + hotReloadTime = hotReloadTime(f); + } + catch (Exception e) { + if (prev != null) + restore(f, prev, e); + + throw new ReloadDone(e); + } + + throw new ReloadDone(null); + } + + /** + * @return Context that new connections get, or {@code null} if a failed reload outside Ignite, such as one by Jetty's + * {@code KeyStoreScanner}, has left the factory without one. + */ + @Nullable private static SSLContext activeContext(SslContextFactory f) { + try { + return f.getSslContext(); + } + catch (IllegalStateException ignored) { + return null; + } + } + + /** Makes the factory install the given context. A preset context makes it skip its key and trust stores. */ + private static void restore(SslContextFactory f, SSLContext ctx, Exception err) { + f.setSslContext(ctx); + + try { + f.reload(ignored -> {}); + } + catch (Exception e) { + err.addSuppressed(e); + } + finally { + f.setSslContext(null); + } + } + + /** @return Hot reload time of the key store that the factory has loaded. */ + private static long hotReloadTime(SslContextFactory f) throws GeneralSecurityException { + KeyStore store = f.getKeyStore(); + + return store == null ? 0 : HotReloadTime.of(store); + } + + /** Ends the outer reload. */ + private static class ReloadDone extends RuntimeException { + /** */ + private static final long serialVersionUID = 0L; + + /** Load failure, or {@code null} if the factory has the replacement. */ + @Nullable private final Exception err; + + /** */ + private ReloadDone(@Nullable Exception err) { + super(null, null, false, false); + + this.err = err; + } + } +} diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridRestSuite.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridRestSuite.java index 564edd21074a7..1d6358f982331 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridRestSuite.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridRestSuite.java @@ -26,7 +26,8 @@ @Suite.SuiteClasses({ RestProcessorAuthorizationTest.class, RestSetupSimpleTest.class, - IgniteRestExtensionTest.class + IgniteRestExtensionTest.class, + JettyRestHttpsReloadTest.class }) public class GridRestSuite { } diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java new file mode 100644 index 0000000000000..91154191b7087 --- /dev/null +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -0,0 +1,343 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.apache.ignite.internal.processors.rest.protocols.http.jetty; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.cert.Certificate; +import java.util.Deque; +import java.util.List; +import java.util.concurrent.ConcurrentLinkedDeque; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; +import org.apache.ignite.IgniteException; +import org.apache.ignite.configuration.ConnectorConfiguration; +import org.apache.ignite.configuration.IgniteConfiguration; +import org.apache.ignite.internal.IgniteEx; +import org.apache.ignite.internal.management.api.CommandInvoker; +import org.apache.ignite.internal.management.api.NoArg; +import org.apache.ignite.internal.management.ssl.SslReloadCommand; +import org.apache.ignite.spi.metric.LongMetric; +import org.apache.ignite.ssl.TestCertificateAuthority; +import org.apache.ignite.testframework.junits.WithSystemProperty; +import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; +import org.eclipse.jetty.util.resource.Resource; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import static java.util.concurrent.TimeUnit.DAYS; +import static java.util.concurrent.TimeUnit.HOURS; +import static org.apache.ignite.IgniteSystemProperties.IGNITE_JETTY_PORT; +import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REST_JETTY_PORT; +import static org.apache.ignite.internal.processors.rest.protocols.http.jetty.GridJettyRestProtocol.DFLT_JETTY_PORT; +import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD; +import static org.apache.ignite.ssl.TestCertificateAuthority.save; +import static org.apache.ignite.testframework.GridTestUtils.assertThrows; +import static org.apache.ignite.testframework.GridTestUtils.assertThrowsAnyCause; +import static org.apache.ignite.testframework.GridTestUtils.waitForCondition; + +/** + * TLS reload of the HTTP REST connector configured in Jetty XML. The standard Jetty factory reads its key store from a file + * ({@code jetty/https.xml}). The custom factory ({@code jetty/https-source.xml}) takes its key stores from {@link SourceSslContextFactory}. + */ +@WithSystemProperty(key = IGNITE_JETTY_PORT, value = DFLT_JETTY_PORT) +public class JettyRestHttpsReloadTest extends GridCommonAbstractTest { + /** Path read by the HTTPS connector in {@code jetty/https.xml}. */ + private static final String KEY_STORE_PATH = "ignite.test.JettyRestHttpsReloadTest.keyStorePath"; + + /** Host name in the server certificates and the HTTPS requests. */ + private static final String HOST = "localhost"; + + /** Upper bound for waiting for an event that must happen. */ + private static final long TIMEOUT_MS = 30_000; + + /** */ + @Rule public TemporaryFolder tmp = new TemporaryFolder(); + + /** Current time rounded down to seconds, the precision of certificate dates. */ + private final long now = System.currentTimeMillis() / 1_000 * 1_000; + + /** Issuer of all server certificates, which the HTTPS clients trust. */ + private TestCertificateAuthority ca; + + /** {@inheritDoc} */ + @Override protected void beforeTest() throws Exception { + super.beforeTest(); + + ca = new TestCertificateAuthority("ca", now - DAYS.toMillis(1), now + DAYS.toMillis(365)); + } + + /** {@inheritDoc} */ + @Override protected void afterTest() throws Exception { + stopAllGrids(); + SourceSslContextFactory.supply(); + + super.afterTest(); + } + + /** + * Given: HTTPS serves certificate A from a key store file of the standard Jetty factory. + * When: the file gets certificate B, and the operator runs the reload command. + * Then: the command reports HTTP REST as reloaded, and a new client sees B. + */ + @Test + @WithSystemProperty(key = KEY_STORE_PATH, value = "") + public void testReloadCommandAppliesReplacementKeyStore() throws Exception { + KeyStore a = fresh(); + KeyStore b = fresh(); + Path keys = keyStoreFile(a); + + IgniteEx node = startGrid(jettyConfig("jetty/https.xml")); + + assertEquals(a.getCertificate(HOST), serverCertificate(node)); + + save(b, keys); + + assertTrue(reload(node).contains(": HTTP REST: reloaded")); + assertEquals(b.getCertificate(HOST), serverCertificate(node)); + } + + /** + * Given: HTTPS serves certificate A from a key store file of the standard Jetty factory. + * When: the file becomes unreadable and the operator runs the reload command, then the file gets certificate B and + * the operator runs the command again. + * Then: the first command reports the node and the cause, and a new client still sees A. After the second command, + * a new client sees B. + */ + @Test + @WithSystemProperty(key = KEY_STORE_PATH, value = "") + public void testFailedReloadKeepsLastWorkingKeys() throws Exception { + KeyStore a = fresh(); + KeyStore b = fresh(); + Path keys = keyStoreFile(a); + + IgniteEx node = startGrid(jettyConfig("jetty/https.xml")); + + Files.writeString(keys, "not a key store"); + + assertThrowsAnyCause(log, () -> reload(node), IgniteException.class, node.localNode().id() + ": failed: HTTP REST: "); + assertEquals(a.getCertificate(HOST), serverCertificate(node)); + + save(b, keys); + reload(node); + + assertEquals(b.getCertificate(HOST), serverCertificate(node)); + } + + /** + * Given: a custom Jetty factory starts with certificate A, which is due for hot reload, and its source then supplies B. + * When: the node runs its hot reload check at startup, then the source fails and the operator runs the reload command. + * Then: a new client sees B after the check. The command fails, and a new client still sees B. + */ + @Test + public void testHotReloadedKeysSurviveFailedManualReload() throws Exception { + KeyStore a = due(); + KeyStore b = fresh(); + + SourceSslContextFactory.supply(a, b); + + IgniteEx node = startGrid(jettyConfig("jetty/https-source.xml")); + Certificate replacement = b.getCertificate(HOST); + + assertTrue(waitForCondition(() -> { + try { + return replacement.equals(serverCertificate(node)); + } + catch (Exception e) { + throw new AssertionError(e); + } + }, TIMEOUT_MS)); + + SourceSslContextFactory.supply(new IOException("Source is unavailable")); + + assertThrowsAnyCause(log, () -> reload(node), IgniteException.class, "Source is unavailable"); + assertEquals(b.getCertificate(HOST), serverCertificate(node)); + } + + /** + * Given: a custom Jetty factory starts with certificate A, which is due for hot reload, and its source then fails. + * When: the node runs its hot reload check at startup. + * Then: the node counts the failed attempt, and a new client still sees A. + */ + @Test + public void testFailedHotReloadKeepsLastWorkingKeys() throws Exception { + KeyStore a = due(); + + SourceSslContextFactory.supply(a, new IOException("Source is unavailable")); + + IgniteEx node = startGrid(jettyConfig("jetty/https-source.xml")); + LongMetric failures = node.context().metric().registry("ssl").findMetric("ConsecutiveHotReloadFailures"); + + assertTrue(waitForCondition(() -> failures.value() == 1, TIMEOUT_MS)); + assertEquals(a.getCertificate(HOST), serverCertificate(node)); + } + + /** + * Given: a custom Jetty factory has loaded certificate A, which was issued 20 hours ago and expires in an hour. + * When: it reloads certificate B, valid for 30 days, and then its source fails. + * Then: the hot reload date is 6 hours ago for A and 23 days ahead for B, and the failed reload keeps B's date. + */ + @Test + public void testHotReloadTimeFollowsLoadedKeys() throws Exception { + SourceSslContextFactory.supply(due(), fresh(), new IOException("Source is unavailable")); + + SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); + + jettyFactory.start(); + + try { + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + + assertEquals(now - HOURS.toMillis(6), factory.hotReloadTime()); + + factory.reload(); + + assertEquals(now + DAYS.toMillis(23), factory.hotReloadTime()); + assertThrows(log, factory::reload, IgniteException.class, "Source is unavailable"); + assertEquals(now + DAYS.toMillis(23), factory.hotReloadTime()); + } + finally { + jettyFactory.stop(); + } + } + + /** + * Given: a reload that Ignite did not start, such as one by Jetty's {@code KeyStoreScanner}, has failed and left + * the custom Jetty factory without keys. + * When: the source supplies certificate B, and Ignite reloads the factory. + * Then: the factory has keys again and serves B. + */ + @Test + public void testReloadRestoresFactoryLeftWithoutKeys() throws Exception { + KeyStore b = fresh(); + + SourceSslContextFactory.supply(fresh(), new IOException("Source is unavailable")); + + SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); + + jettyFactory.start(); + + try { + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + + assertThrows(log, () -> jettyFactory.reload(f -> { }), Exception.class, "Source is unavailable"); + assertThrows(log, () -> jettyFactory.getSslContext(), IllegalStateException.class, null); + + SourceSslContextFactory.supply(b); + factory.reload(); + + assertEquals(b.getCertificate(HOST), jettyFactory.getKeyStore().getCertificate(HOST)); + assertNotNull(jettyFactory.getSslContext()); + } + finally { + jettyFactory.stop(); + } + } + + /** @return Key store with a server certificate valid for 30 days, which is not due for hot reload. */ + private KeyStore fresh() throws Exception { + return ca.keyStore(HOST, now - HOURS.toMillis(1), now + DAYS.toMillis(30)); + } + + /** @return Key store with a server certificate that expires in an hour, so it is due for hot reload. */ + private KeyStore due() throws Exception { + return ca.keyStore(HOST, now - HOURS.toMillis(20), now + HOURS.toMillis(1)); + } + + /** Writes the key store to a file and points {@code jetty/https.xml} at it. */ + private Path keyStoreFile(KeyStore store) throws Exception { + Path keys = tmp.newFile("server.jks").toPath(); + + save(store, keys); + System.setProperty(KEY_STORE_PATH, keys.toString()); + + return keys; + } + + /** @return Node configuration with HTTP REST configured by the given Jetty XML file. */ + private IgniteConfiguration jettyConfig(String jettyPath) throws Exception { + return getConfiguration().setConnectorConfiguration(new ConnectorConfiguration().setJettyPath(jettyPath)); + } + + /** Runs the reload command on the node and returns its report. */ + private static String reload(IgniteEx node) throws Exception { + return new CommandInvoker<>(new SslReloadCommand(), new NoArg(), node).invoke(line -> { }); + } + + /** Returns the certificate that the REST endpoint presents to a new client that trusts the test CA. */ + private Certificate serverCertificate(IgniteEx node) throws Exception { + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + + tmf.init(ca.trustStore()); + + SSLContext client = SSLContext.getInstance("TLS"); + + client.init(null, tmf.getTrustManagers(), null); + + int port = node.localNode().attribute(ATTR_REST_JETTY_PORT); + HttpRequest req = HttpRequest.newBuilder(URI.create("https://" + HOST + ':' + port + "/ignite?cmd=version")).build(); + HttpResponse res = HttpClient.newBuilder().sslContext(client).build().send(req, HttpResponse.BodyHandlers.discarding()); + + assertEquals(200, res.statusCode()); + + return res.sslSession().orElseThrow().getPeerCertificates()[0]; + } + + /** + * Custom Jetty factory that takes its key stores from a source in memory instead of a file. + * Each load takes the next key store or throws the next exception that the test supplied. The last one repeats. + */ + public static class SourceSslContextFactory extends SslContextFactory.Server { + /** */ + private static final Deque LOADS = new ConcurrentLinkedDeque<>(); + + /** Replaces what the next loads take: key stores and exceptions, in order. */ + private static void supply(Object... loads) { + LOADS.clear(); + LOADS.addAll(List.of(loads)); + } + + /** Gives the factory an empty trust store, so that Jetty loads the key store instead of starting without keys. */ + public SourceSslContextFactory() throws Exception { + KeyStore trust = KeyStore.getInstance("PKCS12"); + + trust.load(null, null); + + setTrustStore(trust); + setKeyStorePassword(new String(PASSWORD)); + } + + /** {@inheritDoc} */ + @Override protected KeyStore loadKeyStore(Resource rsrc) throws Exception { + Object load = LOADS.size() > 1 ? LOADS.poll() : LOADS.peek(); + + if (load instanceof Exception e) + throw e; + + return (KeyStore)load; + } + } +} diff --git a/modules/rest-http/src/test/resources/META-INF/jetty/https-source.xml b/modules/rest-http/src/test/resources/META-INF/jetty/https-source.xml new file mode 100644 index 0000000000000..0796c19bfe577 --- /dev/null +++ b/modules/rest-http/src/test/resources/META-INF/jetty/https-source.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + diff --git a/modules/rest-http/src/test/resources/META-INF/jetty/https.xml b/modules/rest-http/src/test/resources/META-INF/jetty/https.xml new file mode 100644 index 0000000000000..45cff6a2b27e6 --- /dev/null +++ b/modules/rest-http/src/test/resources/META-INF/jetty/https.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + JKS + 123456 + + + + + + From 53781dc71c22dce9d66e9c40ea3d05e8cd789654 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 01:43:40 +0300 Subject: [PATCH 02/53] IGNITE-29212 Keep SNI selection after a failed HTTPS reload A failed reload now makes the Jetty factory load its previous key and trust stores from memory. Giving it back the previous SSLContext skipped Jetty's SNI tables, so with sniRequired every handshake failed. The reload holds the factory's lock through unload(...), so a custom reload(...) runs once per successful reload. The hot reload date is read from the keys that new connections use, so it follows replacements that the factory installed by itself. Co-Authored-By: Claude Opus 5.5 --- .../http/jetty/GridJettyRestProtocol.java | 11 +- .../http/jetty/ReloadableJettySslFactory.java | 120 ++++++++------- .../http/jetty/JettyRestHttpsReloadTest.java | 139 ++++++++++++++++-- .../test/resources/META-INF/jetty/https.xml | 1 + 4 files changed, 195 insertions(+), 76 deletions(-) diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java index 7edc067fd42db..e17200801825d 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java @@ -23,7 +23,6 @@ import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; -import java.security.GeneralSecurityException; import java.util.Collection; import java.util.EnumSet; import java.util.HashSet; @@ -176,14 +175,8 @@ else if (log.isDebugEnabled()) if (startJetty()) { SslConnectionFactory tls = connector.getConnectionFactory(SslConnectionFactory.class); - if (tls != null) { - try { - ctx.ssl().register("HTTP REST", new ReloadableJettySslFactory(tls.getSslContextFactory())); - } - catch (GeneralSecurityException e) { - throw new IgniteCheckedException("Failed to read the key store of the HTTPS connector.", e); - } - } + if (tls != null) + ctx.ssl().register("HTTP REST", new ReloadableJettySslFactory(tls.getSslContextFactory())); if (log.isInfoEnabled()) { log.info(startInfo()); diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index d5976c0307a55..f630f32295bdc 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -19,7 +19,7 @@ import java.security.GeneralSecurityException; import java.security.KeyStore; -import javax.net.ssl.SSLContext; +import java.util.function.Consumer; import org.apache.ignite.IgniteException; import org.apache.ignite.internal.processors.ssl.HotReloadTime; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; @@ -29,62 +29,69 @@ /** * TLS factory of the Jetty HTTPS connector. A failed reload leaves the previous keys and trust settings in use. *

- * Jetty clears the TLS state of its factory before it loads the replacement, and new connections take that state under - * the factory's lock. Jetty lets callers hold this lock only inside {@link SslContextFactory#reload}. So the whole reload - * runs inside an outer {@code reload()} call, and new connections wait for it to finish: they get either the replacement - * or the previous context, never a factory without keys. + * Before Jetty loads the replacement, it clears the TLS state of its factory, including the certificates that it selects + * by SNI host name. New connections take that state under the factory's lock. Jetty lets callers hold this lock only + * inside {@link SslContextFactory#unload(Consumer)} and {@link SslContextFactory#reload(Consumer)}, so the reload runs + * inside {@code unload(...)}. If loading fails, the factory loads its previous key and trust stores from memory before + * the lock is released. New connections wait and then get either the replacement or the previous keys. The next reload + * reads the factory's sources again, so stores that were set on the factory directly are not kept. */ class ReloadableJettySslFactory implements ReloadableSslFactory { /** */ private final SslContextFactory factory; - /** */ + /** Hot reload time of the last keys that the factory had. */ private volatile long hotReloadTime; - /** - * @param factory Started TLS factory of the HTTPS connector. - * @throws GeneralSecurityException If the loaded key store cannot be read. - */ - ReloadableJettySslFactory(SslContextFactory factory) throws GeneralSecurityException { + /** @param factory Started TLS factory of the HTTPS connector. */ + ReloadableJettySslFactory(SslContextFactory factory) { this.factory = factory; - - hotReloadTime = hotReloadTime(factory); } /** {@inheritDoc} */ @Override public void reload() { try { - factory.reload(this::reloadLocked); + factory.unload(this::reloadLocked); } catch (ReloadDone done) { if (done.err != null) throw new IgniteException(done.err); } - catch (Exception e) { - throw new IgniteException(e); - } } - /** {@inheritDoc} */ + /** + * Reads the date from the keys that new connections use, including keys that the factory loaded without Ignite, + * such as by Jetty's {@code KeyStoreScanner}. + */ @Override public long hotReloadTime() { + try { + KeyStore store = factory.getKeyStore(); + + hotReloadTime = store == null ? 0 : HotReloadTime.of(store); + } + catch (IllegalStateException ignored) { + // A failed reload without Ignite has left the factory without keys, so the date of its last keys stays. + } + catch (GeneralSecurityException e) { + throw new IgniteException(e); + } + return hotReloadTime; } /** - * Reloads the factory while the outer reload holds its lock. If loading fails, gives the factory its previous context - * back. Always throws {@link ReloadDone}, so that the outer reload does not unload and load the factory again. + * Reloads the factory while {@code unload(...)} holds its lock. If loading fails, the factory loads its previous stores. + * Always throws {@link ReloadDone}, so that {@code unload(...)} does not unload the factory. */ private void reloadLocked(SslContextFactory f) { - SSLContext prev = activeContext(f); + Stores prev = Stores.of(f); try { f.reload(ignored -> {}); - - hotReloadTime = hotReloadTime(f); } catch (Exception e) { if (prev != null) - restore(f, prev, e); + prev.restore(f, e); throw new ReloadDone(e); } @@ -92,42 +99,49 @@ private void reloadLocked(SslContextFactory f) { throw new ReloadDone(null); } - /** - * @return Context that new connections get, or {@code null} if a failed reload outside Ignite, such as one by Jetty's - * {@code KeyStoreScanner}, has left the factory without one. - */ - @Nullable private static SSLContext activeContext(SslContextFactory f) { - try { - return f.getSslContext(); - } - catch (IllegalStateException ignored) { - return null; - } - } + /** Key and trust stores that a factory has loaded. */ + private static class Stores { + /** */ + private final KeyStore keyStore; - /** Makes the factory install the given context. A preset context makes it skip its key and trust stores. */ - private static void restore(SslContextFactory f, SSLContext ctx, Exception err) { - f.setSslContext(ctx); + /** */ + private final KeyStore trustStore; - try { - f.reload(ignored -> {}); - } - catch (Exception e) { - err.addSuppressed(e); - } - finally { - f.setSslContext(null); + /** */ + private Stores(KeyStore keyStore, KeyStore trustStore) { + this.keyStore = keyStore; + this.trustStore = trustStore; } - } - /** @return Hot reload time of the key store that the factory has loaded. */ - private static long hotReloadTime(SslContextFactory f) throws GeneralSecurityException { - KeyStore store = f.getKeyStore(); + /** @return Stores of the factory, or {@code null} if a failed reload without Ignite has left it without keys. */ + @Nullable private static Stores of(SslContextFactory f) { + try { + return new Stores(f.getKeyStore(), f.getTrustStore()); + } + catch (IllegalStateException ignored) { + return null; + } + } - return store == null ? 0 : HotReloadTime.of(store); + /** Makes the factory load these stores instead of reading its sources. Its next reload reads its sources again. */ + private void restore(SslContextFactory f, Exception err) { + f.setKeyStore(keyStore); + f.setTrustStore(trustStore); + + try { + f.reload(ignored -> {}); + } + catch (Exception e) { + err.addSuppressed(e); + } + finally { + f.setKeyStore(null); + f.setTrustStore(null); + } + } } - /** Ends the outer reload. */ + /** Ends {@code unload(...)} without unloading the factory. */ private static class ReloadDone extends RuntimeException { /** */ private static final long serialVersionUID = 0L; diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index 91154191b7087..f43ec9e3f5f7d 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -18,10 +18,6 @@ package org.apache.ignite.internal.processors.rest.protocols.http.jetty; import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyStore; @@ -29,7 +25,12 @@ import java.util.Deque; import java.util.List; import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import javax.net.ssl.SNIHostName; import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManagerFactory; import org.apache.ignite.IgniteException; import org.apache.ignite.configuration.ConnectorConfiguration; @@ -61,7 +62,8 @@ /** * TLS reload of the HTTP REST connector configured in Jetty XML. The standard Jetty factory reads its key store from a file - * ({@code jetty/https.xml}). The custom factory ({@code jetty/https-source.xml}) takes its key stores from {@link SourceSslContextFactory}. + * and requires an SNI host name ({@code jetty/https.xml}). The custom factory ({@code jetty/https-source.xml}) takes its + * key stores from {@link SourceSslContextFactory}. */ @WithSystemProperty(key = IGNITE_JETTY_PORT, value = DFLT_JETTY_PORT) public class JettyRestHttpsReloadTest extends GridCommonAbstractTest { @@ -121,11 +123,12 @@ public void testReloadCommandAppliesReplacementKeyStore() throws Exception { } /** - * Given: HTTPS serves certificate A from a key store file of the standard Jetty factory. + * Given: HTTPS serves certificate A from a key store file of the standard Jetty factory, which selects certificates + * by SNI host name. * When: the file becomes unreadable and the operator runs the reload command, then the file gets certificate B and * the operator runs the command again. - * Then: the first command reports the node and the cause, and a new client still sees A. After the second command, - * a new client sees B. + * Then: the first command reports the node and the cause, and a new client that sends the host name still sees A. + * After the second command, a new client sees B. */ @Test @WithSystemProperty(key = KEY_STORE_PATH, value = "") @@ -228,7 +231,7 @@ public void testHotReloadTimeFollowsLoadedKeys() throws Exception { * Given: a reload that Ignite did not start, such as one by Jetty's {@code KeyStoreScanner}, has failed and left * the custom Jetty factory without keys. * When: the source supplies certificate B, and Ignite reloads the factory. - * Then: the factory has keys again and serves B. + * Then: until the reload, the hot reload date of the last keys stays. After it, the factory has keys again and serves B. */ @Test public void testReloadRestoresFactoryLeftWithoutKeys() throws Exception { @@ -242,9 +245,11 @@ public void testReloadRestoresFactoryLeftWithoutKeys() throws Exception { try { ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + long hotReloadTime = factory.hotReloadTime(); assertThrows(log, () -> jettyFactory.reload(f -> { }), Exception.class, "Source is unavailable"); assertThrows(log, () -> jettyFactory.getSslContext(), IllegalStateException.class, null); + assertEquals(hotReloadTime, factory.hotReloadTime()); SourceSslContextFactory.supply(b); factory.reload(); @@ -257,6 +262,105 @@ public void testReloadRestoresFactoryLeftWithoutKeys() throws Exception { } } + /** + * Given: a Jetty factory serves certificate A, valid for 30 days. + * When: the factory replaces it without Ignite with certificate B, which was issued 20 hours ago and expires in an hour. + * Then: the hot reload date changes from 23 days ahead to 6 hours ago. + */ + @Test + public void testHotReloadTimeFollowsReplacementWithoutIgnite() throws Exception { + KeyStore b = due(); + SslContextFactory.Server jettyFactory = keyStoreFactory(fresh()); + + jettyFactory.start(); + + try { + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + + assertEquals(now + DAYS.toMillis(23), factory.hotReloadTime()); + + jettyFactory.reload(f -> f.setKeyStore(b)); + + assertEquals(now - HOURS.toMillis(6), factory.hotReloadTime()); + } + finally { + jettyFactory.stop(); + } + } + + /** + * Given: a Jetty factory reads its trust store from a file, and its source has set certificate B on it directly. + * When: the trust store file becomes unreadable and Ignite reloads the factory. + * Then: the reload fails, and the factory keeps serving B. + */ + @Test + public void testFailedTrustStoreLoadKeepsLastWorkingKeys() throws Exception { + KeyStore b = fresh(); + Path trust = tmp.newFile("trust.jks").toPath(); + SslContextFactory.Server jettyFactory = keyStoreFactory(fresh()); + + save(ca.trustStore(), trust); + jettyFactory.setTrustStorePath(trust.toString()); + jettyFactory.setTrustStoreType("JKS"); + jettyFactory.setTrustStorePassword(new String(PASSWORD)); + jettyFactory.start(); + + try { + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + + jettyFactory.reload(f -> f.setKeyStore(b)); + Files.writeString(trust, "not a trust store"); + + assertThrows(log, factory::reload, IgniteException.class, null); + assertEquals(b.getCertificate(HOST), jettyFactory.getKeyStore().getCertificate(HOST)); + } + finally { + jettyFactory.stop(); + } + } + + /** + * Given: a custom Jetty factory that would ask its source for keys each time its reload method runs. + * When: Ignite reloads the factory successfully. + * Then: the reload method runs once. + */ + @Test + public void testReloadCallsFactoryReloadOnce() throws Exception { + AtomicInteger reloads = new AtomicInteger(); + + SslContextFactory.Server jettyFactory = new SslContextFactory.Server() { + /** {@inheritDoc} */ + @Override public void reload(Consumer consumer) throws Exception { + reloads.incrementAndGet(); + + super.reload(consumer); + } + }; + + jettyFactory.setKeyStore(fresh()); + jettyFactory.setKeyStorePassword(new String(PASSWORD)); + jettyFactory.start(); + + try { + new ReloadableJettySslFactory(jettyFactory).reload(); + + assertEquals(1, reloads.get()); + } + finally { + jettyFactory.stop(); + } + } + + /** @return Standard Jetty factory with a key store set on it directly, as a source that delivers keys does. */ + private static SslContextFactory.Server keyStoreFactory(KeyStore keys) { + SslContextFactory.Server factory = new SslContextFactory.Server(); + + factory.setKeyStore(keys); + factory.setKeyStorePassword(new String(PASSWORD)); + + return factory; + } + /** @return Key store with a server certificate valid for 30 days, which is not due for hot reload. */ private KeyStore fresh() throws Exception { return ca.keyStore(HOST, now - HOURS.toMillis(1), now + DAYS.toMillis(30)); @@ -287,7 +391,10 @@ private static String reload(IgniteEx node) throws Exception { return new CommandInvoker<>(new SslReloadCommand(), new NoArg(), node).invoke(line -> { }); } - /** Returns the certificate that the REST endpoint presents to a new client that trusts the test CA. */ + /** + * Returns the certificate that the REST endpoint presents to a new client that trusts the test CA and sends + * the host name. The JDK sends no SNI host name for {@code localhost} by itself, so the client sets it. + */ private Certificate serverCertificate(IgniteEx node) throws Exception { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); @@ -298,12 +405,16 @@ private Certificate serverCertificate(IgniteEx node) throws Exception { client.init(null, tmf.getTrustManagers(), null); int port = node.localNode().attribute(ATTR_REST_JETTY_PORT); - HttpRequest req = HttpRequest.newBuilder(URI.create("https://" + HOST + ':' + port + "/ignite?cmd=version")).build(); - HttpResponse res = HttpClient.newBuilder().sslContext(client).build().send(req, HttpResponse.BodyHandlers.discarding()); - assertEquals(200, res.statusCode()); + try (SSLSocket sock = (SSLSocket)client.getSocketFactory().createSocket(HOST, port)) { + SSLParameters params = sock.getSSLParameters(); + + params.setServerNames(List.of(new SNIHostName(HOST))); + sock.setSSLParameters(params); + sock.startHandshake(); - return res.sslSession().orElseThrow().getPeerCertificates()[0]; + return sock.getSession().getPeerCertificates()[0]; + } } /** diff --git a/modules/rest-http/src/test/resources/META-INF/jetty/https.xml b/modules/rest-http/src/test/resources/META-INF/jetty/https.xml index 45cff6a2b27e6..ef5bf2bac4c45 100644 --- a/modules/rest-http/src/test/resources/META-INF/jetty/https.xml +++ b/modules/rest-http/src/test/resources/META-INF/jetty/https.xml @@ -29,6 +29,7 @@ JKS 123456 + true From 0e366a19fb47b528d20194f74aec5b972d5505e3 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 01:51:49 +0300 Subject: [PATCH 03/53] IGNITE-29212 Simplify the Jetty factory adapter and its tests The adapter no longer caches the hot reload date or handles a factory that a reload outside Ignite left without keys: the date is read from the factory, and such a factory is reported as a failure. The stores to restore are plain local variables. The tests drop the node-level check of a failed hot reload, which runs the same code as a failed manual reload, and merge the two hot reload date tests. Co-Authored-By: Claude Opus 5.5 --- .../http/jetty/ReloadableJettySslFactory.java | 76 +++--------- .../http/jetty/JettyRestHttpsReloadTest.java | 114 +++--------------- 2 files changed, 36 insertions(+), 154 deletions(-) diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index f630f32295bdc..dfd420f74982c 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -40,9 +40,6 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { /** */ private final SslContextFactory factory; - /** Hot reload time of the last keys that the factory had. */ - private volatile long hotReloadTime; - /** @param factory Started TLS factory of the HTTPS connector. */ ReloadableJettySslFactory(SslContextFactory factory) { this.factory = factory; @@ -51,7 +48,7 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { /** {@inheritDoc} */ @Override public void reload() { try { - factory.unload(this::reloadLocked); + factory.unload(ReloadableJettySslFactory::reloadLocked); } catch (ReloadDone done) { if (done.err != null) @@ -59,39 +56,31 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { } } - /** - * Reads the date from the keys that new connections use, including keys that the factory loaded without Ignite, - * such as by Jetty's {@code KeyStoreScanner}. - */ + /** Reads the date from the keys that new connections use, including keys that the factory loaded without Ignite. */ @Override public long hotReloadTime() { - try { - KeyStore store = factory.getKeyStore(); + KeyStore store = factory.getKeyStore(); - hotReloadTime = store == null ? 0 : HotReloadTime.of(store); - } - catch (IllegalStateException ignored) { - // A failed reload without Ignite has left the factory without keys, so the date of its last keys stays. + try { + return store == null ? 0 : HotReloadTime.of(store); } catch (GeneralSecurityException e) { throw new IgniteException(e); } - - return hotReloadTime; } /** * Reloads the factory while {@code unload(...)} holds its lock. If loading fails, the factory loads its previous stores. * Always throws {@link ReloadDone}, so that {@code unload(...)} does not unload the factory. */ - private void reloadLocked(SslContextFactory f) { - Stores prev = Stores.of(f); + private static void reloadLocked(SslContextFactory f) { + KeyStore keyStore = f.getKeyStore(); + KeyStore trustStore = f.getTrustStore(); try { f.reload(ignored -> {}); } catch (Exception e) { - if (prev != null) - prev.restore(f, e); + restore(f, keyStore, trustStore, e); throw new ReloadDone(e); } @@ -99,45 +88,20 @@ private void reloadLocked(SslContextFactory f) { throw new ReloadDone(null); } - /** Key and trust stores that a factory has loaded. */ - private static class Stores { - /** */ - private final KeyStore keyStore; - - /** */ - private final KeyStore trustStore; + /** Makes the factory load the given stores instead of reading its sources. Its next reload reads its sources again. */ + private static void restore(SslContextFactory f, KeyStore keyStore, KeyStore trustStore, Exception err) { + f.setKeyStore(keyStore); + f.setTrustStore(trustStore); - /** */ - private Stores(KeyStore keyStore, KeyStore trustStore) { - this.keyStore = keyStore; - this.trustStore = trustStore; + try { + f.reload(ignored -> {}); } - - /** @return Stores of the factory, or {@code null} if a failed reload without Ignite has left it without keys. */ - @Nullable private static Stores of(SslContextFactory f) { - try { - return new Stores(f.getKeyStore(), f.getTrustStore()); - } - catch (IllegalStateException ignored) { - return null; - } + catch (Exception e) { + err.addSuppressed(e); } - - /** Makes the factory load these stores instead of reading its sources. Its next reload reads its sources again. */ - private void restore(SslContextFactory f, Exception err) { - f.setKeyStore(keyStore); - f.setTrustStore(trustStore); - - try { - f.reload(ignored -> {}); - } - catch (Exception e) { - err.addSuppressed(e); - } - finally { - f.setKeyStore(null); - f.setTrustStore(null); - } + finally { + f.setKeyStore(null); + f.setTrustStore(null); } } diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index f43ec9e3f5f7d..d95c49a399e9e 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -39,7 +39,6 @@ import org.apache.ignite.internal.management.api.CommandInvoker; import org.apache.ignite.internal.management.api.NoArg; import org.apache.ignite.internal.management.ssl.SslReloadCommand; -import org.apache.ignite.spi.metric.LongMetric; import org.apache.ignite.ssl.TestCertificateAuthority; import org.apache.ignite.testframework.junits.WithSystemProperty; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; @@ -181,31 +180,14 @@ public void testHotReloadedKeysSurviveFailedManualReload() throws Exception { } /** - * Given: a custom Jetty factory starts with certificate A, which is due for hot reload, and its source then fails. - * When: the node runs its hot reload check at startup. - * Then: the node counts the failed attempt, and a new client still sees A. + * Given: a custom Jetty factory has loaded certificate A, valid for 30 days. + * When: the factory reloads by itself and gets certificate B, which was issued 20 hours ago and expires in an hour. + * Then its source fails, and Ignite reloads the factory. + * Then: the hot reload date is 23 days ahead for A and 6 hours ago for B, and the failed reload keeps B's date. */ @Test - public void testFailedHotReloadKeepsLastWorkingKeys() throws Exception { - KeyStore a = due(); - - SourceSslContextFactory.supply(a, new IOException("Source is unavailable")); - - IgniteEx node = startGrid(jettyConfig("jetty/https-source.xml")); - LongMetric failures = node.context().metric().registry("ssl").findMetric("ConsecutiveHotReloadFailures"); - - assertTrue(waitForCondition(() -> failures.value() == 1, TIMEOUT_MS)); - assertEquals(a.getCertificate(HOST), serverCertificate(node)); - } - - /** - * Given: a custom Jetty factory has loaded certificate A, which was issued 20 hours ago and expires in an hour. - * When: it reloads certificate B, valid for 30 days, and then its source fails. - * Then: the hot reload date is 6 hours ago for A and 23 days ahead for B, and the failed reload keeps B's date. - */ - @Test - public void testHotReloadTimeFollowsLoadedKeys() throws Exception { - SourceSslContextFactory.supply(due(), fresh(), new IOException("Source is unavailable")); + public void testHotReloadTimeFollowsKeysInUse() throws Exception { + SourceSslContextFactory.supply(fresh(), due(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); @@ -214,74 +196,13 @@ public void testHotReloadTimeFollowsLoadedKeys() throws Exception { try { ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); - assertEquals(now - HOURS.toMillis(6), factory.hotReloadTime()); - - factory.reload(); - - assertEquals(now + DAYS.toMillis(23), factory.hotReloadTime()); - assertThrows(log, factory::reload, IgniteException.class, "Source is unavailable"); assertEquals(now + DAYS.toMillis(23), factory.hotReloadTime()); - } - finally { - jettyFactory.stop(); - } - } - /** - * Given: a reload that Ignite did not start, such as one by Jetty's {@code KeyStoreScanner}, has failed and left - * the custom Jetty factory without keys. - * When: the source supplies certificate B, and Ignite reloads the factory. - * Then: until the reload, the hot reload date of the last keys stays. After it, the factory has keys again and serves B. - */ - @Test - public void testReloadRestoresFactoryLeftWithoutKeys() throws Exception { - KeyStore b = fresh(); - - SourceSslContextFactory.supply(fresh(), new IOException("Source is unavailable")); - - SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - - jettyFactory.start(); - - try { - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); - long hotReloadTime = factory.hotReloadTime(); - - assertThrows(log, () -> jettyFactory.reload(f -> { }), Exception.class, "Source is unavailable"); - assertThrows(log, () -> jettyFactory.getSslContext(), IllegalStateException.class, null); - assertEquals(hotReloadTime, factory.hotReloadTime()); - - SourceSslContextFactory.supply(b); - factory.reload(); - - assertEquals(b.getCertificate(HOST), jettyFactory.getKeyStore().getCertificate(HOST)); - assertNotNull(jettyFactory.getSslContext()); - } - finally { - jettyFactory.stop(); - } - } - - /** - * Given: a Jetty factory serves certificate A, valid for 30 days. - * When: the factory replaces it without Ignite with certificate B, which was issued 20 hours ago and expires in an hour. - * Then: the hot reload date changes from 23 days ahead to 6 hours ago. - */ - @Test - public void testHotReloadTimeFollowsReplacementWithoutIgnite() throws Exception { - KeyStore b = due(); - SslContextFactory.Server jettyFactory = keyStoreFactory(fresh()); - - jettyFactory.start(); - - try { - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); - - assertEquals(now + DAYS.toMillis(23), factory.hotReloadTime()); - - jettyFactory.reload(f -> f.setKeyStore(b)); + jettyFactory.reload(f -> { }); assertEquals(now - HOURS.toMillis(6), factory.hotReloadTime()); + assertThrows(log, factory::reload, IgniteException.class, "Source is unavailable"); + assertEquals(now - HOURS.toMillis(6), factory.hotReloadTime()); } finally { jettyFactory.stop(); @@ -289,15 +210,15 @@ public void testHotReloadTimeFollowsReplacementWithoutIgnite() throws Exception } /** - * Given: a Jetty factory reads its trust store from a file, and its source has set certificate B on it directly. + * Given: a Jetty factory serves certificate A and reads its trust store from a file. * When: the trust store file becomes unreadable and Ignite reloads the factory. - * Then: the reload fails, and the factory keeps serving B. + * Then: the reload fails, and the factory keeps serving A. */ @Test public void testFailedTrustStoreLoadKeepsLastWorkingKeys() throws Exception { - KeyStore b = fresh(); + KeyStore a = fresh(); Path trust = tmp.newFile("trust.jks").toPath(); - SslContextFactory.Server jettyFactory = keyStoreFactory(fresh()); + SslContextFactory.Server jettyFactory = keyStoreFactory(a); save(ca.trustStore(), trust); jettyFactory.setTrustStorePath(trust.toString()); @@ -306,13 +227,10 @@ public void testFailedTrustStoreLoadKeepsLastWorkingKeys() throws Exception { jettyFactory.start(); try { - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); - - jettyFactory.reload(f -> f.setKeyStore(b)); Files.writeString(trust, "not a trust store"); - assertThrows(log, factory::reload, IgniteException.class, null); - assertEquals(b.getCertificate(HOST), jettyFactory.getKeyStore().getCertificate(HOST)); + assertThrows(log, new ReloadableJettySslFactory(jettyFactory)::reload, IgniteException.class, null); + assertEquals(a.getCertificate(HOST), jettyFactory.getKeyStore().getCertificate(HOST)); } finally { jettyFactory.stop(); @@ -351,7 +269,7 @@ public void testReloadCallsFactoryReloadOnce() throws Exception { } } - /** @return Standard Jetty factory with a key store set on it directly, as a source that delivers keys does. */ + /** @return Standard Jetty factory with the key store set on it directly. */ private static SslContextFactory.Server keyStoreFactory(KeyStore keys) { SslContextFactory.Server factory = new SslContextFactory.Server(); From 0d0d87163fe19faea7c7015accf3ce39965e31cd Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 01:59:47 +0300 Subject: [PATCH 04/53] IGNITE-29212 Keep reload operations on the registry's entries Each registered factory gets its reload operations when it is registered: an Ignite factory through a small adapter, the Jetty factory as is. The hourly check and the reload command use these entries, so the registry no longer checks factory types in several places, and the command no longer passes factories back for a lookup. Co-Authored-By: Claude Opus 5.5 --- .../management/ssl/SslReloadTask.java | 17 ++- .../processors/ssl/SslFactoryRegistry.java | 110 ++++++++---------- .../ssl/SslFactoryRegistryTest.java | 42 ++++--- 3 files changed, 86 insertions(+), 83 deletions(-) diff --git a/modules/core/src/main/java/org/apache/ignite/internal/management/ssl/SslReloadTask.java b/modules/core/src/main/java/org/apache/ignite/internal/management/ssl/SslReloadTask.java index 2ad637d3952ca..7ab71ce0e185d 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/management/ssl/SslReloadTask.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/management/ssl/SslReloadTask.java @@ -22,7 +22,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.UUID; import org.apache.ignite.IgniteException; import org.apache.ignite.cluster.ClusterNode; @@ -30,7 +29,7 @@ import org.apache.ignite.compute.ComputeJob; import org.apache.ignite.compute.ComputeJobResult; import org.apache.ignite.internal.management.api.NoArg; -import org.apache.ignite.internal.processors.ssl.SslFactoryRegistry; +import org.apache.ignite.internal.processors.ssl.SslFactoryRegistry.RegisteredFactory; import org.apache.ignite.internal.processors.task.GridInternal; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.visor.VisorJob; @@ -116,7 +115,7 @@ private SslReloadJob(NoArg arg, boolean debug) { /** {@inheritDoc} */ @Override protected String run(NoArg arg) { - List> factories = ignite.context().ssl().factories(); + List factories = ignite.context().ssl().factories(); UUID nodeId = ignite.localNode().id(); String initiator = ""; @@ -134,9 +133,9 @@ private SslReloadJob(NoArg arg, boolean debug) { return report; } - for (Entry entry : factories) { - if (!SslFactoryRegistry.supportsReload(entry.getKey())) { - String report = entry.getValue() + ": unsupported: " + entry.getKey().getClass().getName(); + for (RegisteredFactory registered : factories) { + if (!registered.supportsReload()) { + String report = registered.transports() + ": unsupported: " + registered.factory().getClass().getName(); ignite.log().warning("TLS reload: " + nodeId + ": " + report + initiator); @@ -146,11 +145,11 @@ private SslReloadJob(NoArg arg, boolean debug) { List reports = new ArrayList<>(); - for (Entry entry : factories) { - String transports = entry.getValue(); + for (RegisteredFactory registered : factories) { + String transports = registered.transports(); try { - ignite.context().ssl().reload(entry.getKey()); + registered.reload(); } catch (Exception e) { ignite.log().warning("TLS reload: " + nodeId + ": " + transports + ": failed" + initiator, e); diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index a1cc0e0cd4364..c310e7cf2ccda 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -17,11 +17,8 @@ package org.apache.ignite.internal.processors.ssl; -import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.Map; -import java.util.Map.Entry; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicInteger; @@ -34,6 +31,7 @@ import org.apache.ignite.internal.processors.metric.MetricRegistryImpl; import org.apache.ignite.internal.thread.context.function.OperationContextAwareRunnable; import org.apache.ignite.ssl.AbstractSslContextFactory; +import org.jetbrains.annotations.Nullable; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MILLISECONDS; @@ -61,39 +59,47 @@ public SslFactoryRegistry(GridKernalContext ctx) { super(ctx); } - /** */ + /** + * Registers the factory of an Ignite transport. The registry can reload the factory if it extends + * {@link AbstractSslContextFactory}. + */ public void register(String transport, Factory factory) { - add(transport, factory); + add(transport, factory, factory instanceof AbstractSslContextFactory sslFactory ? new ReloadableSslFactory() { + /** {@inheritDoc} */ + @Override public void reload() { + sslFactory.init(); + } + + /** {@inheritDoc} */ + @Override public long hotReloadTime() { + return sslFactory.getHotReloadTime(); + } + } : null); } /** */ public void register(String transport, ReloadableSslFactory factory) { - add(transport, factory); + add(transport, factory, factory); } /** */ - private synchronized void add(String transport, Object factory) { + private synchronized void add(String transport, Object factory, @Nullable ReloadableSslFactory reloadable) { for (int i = 0; i < factories.size(); i++) { RegisteredFactory registered = factories.get(i); if (registered.factory == factory) { - factories.set(i, new RegisteredFactory(factory, registered.transports + ", " + transport)); + factories.set(i, new RegisteredFactory(factory, reloadable, registered.transports + ", " + transport)); return; } } - factories.add(new RegisteredFactory(factory, transport)); + factories.add(new RegisteredFactory(factory, reloadable, transport)); } - /** @return Registered factories in registration order, each with its transports joined by commas. */ - public List> factories() { - List> res = new ArrayList<>(factories.size()); - - for (RegisteredFactory registered : factories) - res.add(Map.entry(registered.factory, registered.transports)); - - return res; + /** @return Registered factories in registration order. */ + public List factories() { + return List.copyOf(factories); } /** {@inheritDoc} */ @@ -109,8 +115,8 @@ public List> factories() { boolean hotReload = false; for (RegisteredFactory registered : factories) { - if (supportsReload(registered.factory)) { - registered.logHotReloadTime(registered.hotReloadTime()); + if (registered.supportsReload()) { + registered.logHotReloadTime(registered.reloadable.hotReloadTime()); hotReload = true; } @@ -141,7 +147,7 @@ private void checkFactories() { log.debug("TLS hot reload check started"); for (RegisteredFactory registered : factories) { - if (supportsReload(registered.factory)) + if (registered.supportsReload()) registered.check(); } } @@ -152,31 +158,14 @@ private void checkFactories() { executor.shutdownNow(); } - /** - * Reloads a registered factory. Waits for its running check and resets its failure count. - * - * @param factory Registered factory that supports reload. - */ - public void reload(Object factory) { - for (RegisteredFactory registered : factories) { - if (registered.factory == factory) - registered.reload(); - } - } - - /** - * @param factory Registered factory. - * @return Whether the registry can reload the factory. - */ - public static boolean supportsReload(Object factory) { - return factory instanceof AbstractSslContextFactory || factory instanceof ReloadableSslFactory; - } - /** Registered factory with its transports and hot reload state. The hourly check and manual reload hold its monitor. */ - private class RegisteredFactory { + public class RegisteredFactory { /** */ private final Object factory; + /** Reload operations of the factory, or {@code null} if the registry cannot reload it. */ + @Nullable private final ReloadableSslFactory reloadable; + /** */ private final String transports; @@ -184,24 +173,25 @@ private class RegisteredFactory { private final AtomicInteger failures = new AtomicInteger(); /** */ - private RegisteredFactory(Object factory, String transports) { + private RegisteredFactory(Object factory, @Nullable ReloadableSslFactory reloadable, String transports) { this.factory = factory; + this.reloadable = reloadable; this.transports = transports; } - /** Loads the factory again. If loading fails, it keeps its previous context. */ - private void load() { - if (factory instanceof ReloadableSslFactory reloadable) - reloadable.reload(); - else - ((AbstractSslContextFactory)factory).init(); + /** @return The factory that the transports registered. */ + public Object factory() { + return factory; } - /** @return Hot reload time of the certificates that the factory loaded last. */ - private long hotReloadTime() { - return factory instanceof ReloadableSslFactory reloadable - ? reloadable.hotReloadTime() - : ((AbstractSslContextFactory)factory).getHotReloadTime(); + /** @return Transports that use the factory, joined by commas. */ + public String transports() { + return transports; + } + + /** @return Whether the registry can reload the factory. */ + public boolean supportsReload() { + return reloadable != null; } /** @@ -234,7 +224,7 @@ else if (log.isDebugEnabled()) * @throws IgniteException If the reload fails or leaves certificates that are still due. */ private void reloadIfDue() { - if (!due(hotReloadTime())) { + if (!due(reloadable.hotReloadTime())) { failures.set(0); return; @@ -245,9 +235,9 @@ private void reloadIfDue() { if (log.isInfoEnabled()) log.info("TLS hot reload started [transports=" + transports + ']'); - load(); + reloadable.reload(); - long hotReloadTime = hotReloadTime(); + long hotReloadTime = reloadable.hotReloadTime(); if (due(hotReloadTime)) { throw new IgniteException("Loaded certificates are still due for hot reload [hotReloadTime=" @@ -267,15 +257,15 @@ private static boolean due(long hotReloadTime) { return hotReloadTime != 0 && hotReloadTime <= System.currentTimeMillis(); } - /** */ - private synchronized void reload() { + /** Reloads a factory that supports reload. Waits for its running check and resets its failure count. */ + public synchronized void reload() { manualReloadAttempts.incrementAndGet(); - load(); + reloadable.reload(); failures.set(0); - logHotReloadTime(hotReloadTime()); + logHotReloadTime(reloadable.hotReloadTime()); } /** */ diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index 047d27c18e6ab..1ed1d3952298f 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -40,6 +40,7 @@ import org.apache.ignite.internal.GridKernalContext; import org.apache.ignite.internal.processors.metric.GridMetricManager; import org.apache.ignite.internal.processors.metric.MetricRegistryImpl; +import org.apache.ignite.internal.processors.ssl.SslFactoryRegistry.RegisteredFactory; import org.apache.ignite.internal.thread.context.OperationContext; import org.apache.ignite.internal.thread.context.OperationContextAttribute; import org.apache.ignite.internal.thread.context.Scope; @@ -179,8 +180,13 @@ public void testFactoriesAreGroupedInRegistrationOrder() { registry.register("client connector", clientConnector); registry.register("discovery", factory); - assertEquals(List.of(Map.entry(factory, "communication, discovery"), - Map.entry(clientConnector, "client connector")), registry.factories()); + List> registered = new ArrayList<>(); + + for (RegisteredFactory f : registry.factories()) + registered.add(Map.entry(f.factory(), f.transports())); + + assertEquals(List.of(Map.entry(factory, "communication, discovery"), Map.entry(clientConnector, "client connector")), + registered); } /** @@ -211,7 +217,7 @@ public void testReloadableFactoryIsHotReloadedAndReloadedManually() { registry.register("HTTP REST", rest); registry.onKernalStart(true); check.run(); - registry.reload(rest); + reload(rest); verify(rest, times(2)).reload(); assertEquals(1, metric("AutomaticHotReloadAttempts")); @@ -263,7 +269,7 @@ public void testManualReloadLoadsOnlyItsFactoryInstance() throws Exception { long prevTime = communication.getHotReloadTime(); writeFreshCertificates(keys); - registry.reload(clientConnector); + reload(clientConnector); assertTrue(clientConnector.getHotReloadTime() > prevTime); assertEquals(prevTime, communication.getHotReloadTime()); @@ -291,7 +297,7 @@ public void testStoreWithoutPrivateKeyIsReportedUntilKeysAreReloaded() throws Ex assertEquals(0, metric("AutomaticHotReloadAttempts")); writeFreshCertificates(keys); - registry.reload(communication); + reload(communication); assertEquals("TLS hot reload due [transports=communication, hotReloadTime=" + new Date(communication.getHotReloadTime()) + ']', logged.get(logged.size() - 1)); @@ -479,7 +485,7 @@ public void testManualReloadBeforeStartLoadsFactory() throws Exception { long prevTime = communication.getHotReloadTime(); writeFreshCertificates(keys); - registry.reload(communication); + reload(communication); assertTrue(communication.getHotReloadTime() > prevTime); } @@ -496,13 +502,13 @@ public void testManualReloadCountsAppliedAndFailedLoads() throws Exception { writeFreshCertificates(keys); registerTransport("communication", communication); registry.onKernalStart(true); - registry.reload(communication); + reload(communication); assertEquals(1, metric("ManualReloadAttempts")); Files.delete(keys); - assertThrows(IgniteException.class, () -> registry.reload(communication)); + assertThrows(IgniteException.class, () -> reload(communication)); assertEquals(2, metric("ManualReloadAttempts")); assertEquals(0, metric("AutomaticHotReloadAttempts")); } @@ -554,7 +560,7 @@ public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { registry.onKernalStart(true); custom.setKeys(null, null); - registry.reload(custom); + reload(custom); check.run(); assertEquals(0, custom.getHotReloadTime()); @@ -572,7 +578,7 @@ public void testManualReloadSupportsAbstractFactory() throws Exception { registry.register("client connector", factory); registry.onKernalStart(true); - registry.reload(factory); + reload(factory); verify(factory).init(); } @@ -592,7 +598,7 @@ public void testFailedManualReloadKeepsFailures() throws Exception { Files.delete(keys); check.run(); - IgniteException err = assertThrows(IgniteException.class, () -> registry.reload(communication)); + IgniteException err = assertThrows(IgniteException.class, () -> reload(communication)); assertTrue(X.hasCause(err, "key store file was not found", SSLException.class)); assertEquals(1, failures()); @@ -626,7 +632,7 @@ public void testManualReloadWaitsForRunningAttempt() throws Exception { }); GridTestThread attempt = new GridTestThread(check); - GridTestThread manualReload = new GridTestThread(() -> registry.reload(communication)); + GridTestThread manualReload = new GridTestThread(() -> reload(communication)); attempt.start(); @@ -677,7 +683,7 @@ public void testManualReloadResetsOnlyItsFactoryFailures() throws Exception { assertEquals(1, failures()); writeDueCertificates(keys); - registry.reload(communication); + reload(communication); assertEquals(1, failures()); @@ -686,7 +692,7 @@ public void testManualReloadResetsOnlyItsFactoryFailures() throws Exception { assertEquals(3, failures()); writeFreshCertificates(clientKeys); - registry.reload(clientConnector); + reload(clientConnector); assertEquals(1, failures()); } @@ -819,6 +825,14 @@ private List captureLog(boolean debug) { return logged; } + /** Reloads the registered factory, as the reload command does. */ + private void reload(Object factory) { + for (RegisteredFactory registered : registry.factories()) { + if (registered.factory() == factory) + registered.reload(); + } + } + /** Loads a file-backed factory before registration, as the TCP transports do during startup. */ private void registerTransport(String transport, SslContextFactory factory) { factory.create(); From f609943b9d21cdd805f4988e8a698a094c458cc1 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 02:03:22 +0300 Subject: [PATCH 05/53] IGNITE-29212 Describe ReloadableSslFactory for all factories and tidy the HTTPS test ReloadableSslFactory now serves every registered factory, so its javadoc no longer limits it to non-Ignite factories, and the date it returns is the one of the keys that new connections use. A factory registered by a second transport keeps its reload operations. The metrics page no longer mentions hot reload configuration. The HTTPS test explains why it sets IGNITE_JETTY_PORT and builds its only standalone factory inline. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/monitoring-metrics/new-metrics.adoc | 2 +- .../processors/ssl/ReloadableSslFactory.java | 4 ++-- .../processors/ssl/SslFactoryRegistry.java | 4 ++-- .../http/jetty/JettyRestHttpsReloadTest.java | 17 +++++------------ 4 files changed, 10 insertions(+), 17 deletions(-) diff --git a/docs/_docs/monitoring-metrics/new-metrics.adoc b/docs/_docs/monitoring-metrics/new-metrics.adoc index 3d6c6085234db..fcabdbee44356 100644 --- a/docs/_docs/monitoring-metrics/new-metrics.adoc +++ b/docs/_docs/monitoring-metrics/new-metrics.adoc @@ -445,7 +445,7 @@ Register name: `ssl` |AutomaticHotReloadAttempts | long | Number of automatic hot reload attempts. |=== -See link:security/ssl-tls#automatic-certificate-hot-reload[Automatic Certificate Hot Reload] for configuration and recovery. +See link:security/ssl-tls#automatic-certificate-hot-reload[Automatic Certificate Hot Reload] for when it runs and how to recover. == Communication Connection Pool diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index fa2261ba3b9d5..dce32b951cadc 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -17,7 +17,7 @@ package org.apache.ignite.internal.processors.ssl; -/** TLS factory of a transport that does not use an Ignite SSL context factory, such as HTTP REST with Jetty. */ +/** Operations that the SSL factory registry uses to reload a TLS factory on request and before its certificates expire. */ public interface ReloadableSslFactory { /** * Loads the keys and trust settings again for new connections. If loading fails, new connections keep the previous ones. @@ -27,7 +27,7 @@ public interface ReloadableSslFactory { public void reload(); /** - * @return Time when the certificates of the last successful load are due for hot reload, as calculated by + * @return Time when the certificates that new connections use are due for hot reload, as calculated by * {@link HotReloadTime#of}, or {@code 0} if they give none. */ public long hotReloadTime(); diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index c310e7cf2ccda..7e3f53dfea375 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -77,7 +77,7 @@ public void register(String transport, Factory factory) { } : null); } - /** */ + /** Registers the TLS factory of a transport that does not use an Ignite SSL context factory, such as HTTP REST. */ public void register(String transport, ReloadableSslFactory factory) { add(transport, factory, factory); } @@ -88,7 +88,7 @@ private synchronized void add(String transport, Object factory, @Nullable Reload RegisteredFactory registered = factories.get(i); if (registered.factory == factory) { - factories.set(i, new RegisteredFactory(factory, reloadable, registered.transports + ", " + transport)); + factories.set(i, new RegisteredFactory(factory, registered.reloadable, registered.transports + ", " + transport)); return; } diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index d95c49a399e9e..b4cad6fcb3396 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -62,7 +62,8 @@ /** * TLS reload of the HTTP REST connector configured in Jetty XML. The standard Jetty factory reads its key store from a file * and requires an SNI host name ({@code jetty/https.xml}). The custom factory ({@code jetty/https-source.xml}) takes its - * key stores from {@link SourceSslContextFactory}. + * key stores from {@link SourceSslContextFactory}. The connectors in these files set no port, so the tests set + * {@code IGNITE_JETTY_PORT}; otherwise the node would publish port 0. */ @WithSystemProperty(key = IGNITE_JETTY_PORT, value = DFLT_JETTY_PORT) public class JettyRestHttpsReloadTest extends GridCommonAbstractTest { @@ -218,9 +219,11 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { public void testFailedTrustStoreLoadKeepsLastWorkingKeys() throws Exception { KeyStore a = fresh(); Path trust = tmp.newFile("trust.jks").toPath(); - SslContextFactory.Server jettyFactory = keyStoreFactory(a); + SslContextFactory.Server jettyFactory = new SslContextFactory.Server(); save(ca.trustStore(), trust); + jettyFactory.setKeyStore(a); + jettyFactory.setKeyStorePassword(new String(PASSWORD)); jettyFactory.setTrustStorePath(trust.toString()); jettyFactory.setTrustStoreType("JKS"); jettyFactory.setTrustStorePassword(new String(PASSWORD)); @@ -269,16 +272,6 @@ public void testReloadCallsFactoryReloadOnce() throws Exception { } } - /** @return Standard Jetty factory with the key store set on it directly. */ - private static SslContextFactory.Server keyStoreFactory(KeyStore keys) { - SslContextFactory.Server factory = new SslContextFactory.Server(); - - factory.setKeyStore(keys); - factory.setKeyStorePassword(new String(PASSWORD)); - - return factory; - } - /** @return Key store with a server certificate valid for 30 days, which is not due for hot reload. */ private KeyStore fresh() throws Exception { return ca.keyStore(HOST, now - HOURS.toMillis(1), now + DAYS.toMillis(30)); From f12dafe6d4f1faf3e5cf7c8be887fc85d5c46027 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 14:52:31 +0300 Subject: [PATCH 06/53] IGNITE-29212 Restore the working Jetty TLS context after a failed reload --- .../http/jetty/GridJettyRestProtocol.java | 9 ++-- .../http/jetty/ReloadableJettySslFactory.java | 54 +++++++++++-------- .../http/jetty/JettyRestHttpsReloadTest.java | 41 +++++++++----- parent/pom.xml | 2 +- 4 files changed, 68 insertions(+), 38 deletions(-) diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java index e17200801825d..9b2b937c05a50 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java @@ -169,14 +169,15 @@ else if (log.isDebugEnabled()) int portRange = config().getPortRange(); int lastPort = portRange == 0 ? initPort : initPort + portRange - 1; + SslConnectionFactory tls = connector.getConnectionFactory(SslConnectionFactory.class); + ReloadableJettySslFactory sslFactory = tls == null ? null : new ReloadableJettySslFactory(tls.getSslContextFactory()); + for (port = initPort; port <= lastPort; port++) { connector.setPort(port); if (startJetty()) { - SslConnectionFactory tls = connector.getConnectionFactory(SslConnectionFactory.class); - - if (tls != null) - ctx.ssl().register("HTTP REST", new ReloadableJettySslFactory(tls.getSslContextFactory())); + if (sslFactory != null) + ctx.ssl().register("HTTP REST", sslFactory); if (log.isInfoEnabled()) { log.info(startInfo()); diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index dfd420f74982c..ff38f78a099c5 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -20,6 +20,7 @@ import java.security.GeneralSecurityException; import java.security.KeyStore; import java.util.function.Consumer; +import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; import org.apache.ignite.internal.processors.ssl.HotReloadTime; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; @@ -29,26 +30,27 @@ /** * TLS factory of the Jetty HTTPS connector. A failed reload leaves the previous keys and trust settings in use. *

- * Before Jetty loads the replacement, it clears the TLS state of its factory, including the certificates that it selects - * by SNI host name. New connections take that state under the factory's lock. Jetty lets callers hold this lock only - * inside {@link SslContextFactory#unload(Consumer)} and {@link SslContextFactory#reload(Consumer)}, so the reload runs - * inside {@code unload(...)}. If loading fails, the factory loads its previous key and trust stores from memory before - * the lock is released. New connections wait and then get either the replacement or the previous keys. The next reload - * reads the factory's sources again, so stores that were set on the factory directly are not kept. + * Jetty clears its active context before loading the replacement. Holding its lock through reload and recovery lets + * new connections use the previous context if loading fails. Jetty uses the accompanying key store for SNI. */ class ReloadableJettySslFactory implements ReloadableSslFactory { /** */ private final SslContextFactory factory; - /** @param factory Started TLS factory of the HTTPS connector. */ + /** Objects supplied directly to Jetty. A null store lets the factory read its configured source. */ + private final TlsMaterial configured; + + /** @param factory TLS factory of the HTTPS connector before startup, when its getters expose the configured objects. */ ReloadableJettySslFactory(SslContextFactory factory) { this.factory = factory; + + configured = new TlsMaterial(factory); } /** {@inheritDoc} */ @Override public void reload() { try { - factory.unload(ReloadableJettySslFactory::reloadLocked); + factory.unload(this::reloadLocked); } catch (ReloadDone done) { if (done.err != null) @@ -69,18 +71,17 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { } /** - * Reloads the factory while {@code unload(...)} holds its lock. If loading fails, the factory loads its previous stores. + * Reloads the factory while {@link SslContextFactory#unload(Consumer)} holds its lock. * Always throws {@link ReloadDone}, so that {@code unload(...)} does not unload the factory. */ - private static void reloadLocked(SslContextFactory f) { - KeyStore keyStore = f.getKeyStore(); - KeyStore trustStore = f.getTrustStore(); + private void reloadLocked(SslContextFactory f) { + TlsMaterial prev = new TlsMaterial(f); try { f.reload(ignored -> {}); } catch (Exception e) { - restore(f, keyStore, trustStore, e); + restore(f, prev, e); throw new ReloadDone(e); } @@ -88,20 +89,31 @@ private static void reloadLocked(SslContextFactory f) { throw new ReloadDone(null); } - /** Makes the factory load the given stores instead of reading its sources. Its next reload reads its sources again. */ - private static void restore(SslContextFactory f, KeyStore keyStore, KeyStore trustStore, Exception err) { - f.setKeyStore(keyStore); - f.setTrustStore(trustStore); - + /** Reinstalls the working context, then restores the settings Jetty will use on the next reload. */ + private void restore(SslContextFactory f, TlsMaterial prev, Exception err) { try { - f.reload(ignored -> {}); + f.reload(prev::applyTo); } catch (Exception e) { err.addSuppressed(e); } finally { - f.setKeyStore(null); - f.setTrustStore(null); + configured.applyTo(f); + } + } + + /** The context and stores Jetty uses together for new connections. */ + private record TlsMaterial(SSLContext ctx, KeyStore keyStore, KeyStore trustStore) { + /** */ + TlsMaterial(SslContextFactory factory) { + this(factory.getSslContext(), factory.getKeyStore(), factory.getTrustStore()); + } + + /** */ + private void applyTo(SslContextFactory factory) { + factory.setSslContext(ctx); + factory.setKeyStore(keyStore); + factory.setTrustStore(trustStore); } } diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index b4cad6fcb3396..f947d3143b4c1 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -191,12 +191,11 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { SourceSslContextFactory.supply(fresh(), due(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); jettyFactory.start(); try { - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); - assertEquals(now + DAYS.toMillis(23), factory.hotReloadTime()); jettyFactory.reload(f -> { }); @@ -211,29 +210,44 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { } /** - * Given: a Jetty factory serves certificate A and reads its trust store from a file. - * When: the trust store file becomes unreadable and Ignite reloads the factory. - * Then: the reload fails, and the factory keeps serving A. + * Given: Jetty has keys configured in memory and reads its trust store from a file. + * When: reload fails because the file is corrupt, then the operator replaces it and retries. + * Then: the failed reload keeps the working context. The retry picks up the new trust store with the configured keys. */ @Test - public void testFailedTrustStoreLoadKeepsLastWorkingKeys() throws Exception { - KeyStore a = fresh(); + public void testTrustStoreReloadKeepsConfiguredKeysAfterFailure() throws Exception { + KeyStore keys = fresh(); + KeyStore trusted = ca.trustStore(); Path trust = tmp.newFile("trust.jks").toPath(); SslContextFactory.Server jettyFactory = new SslContextFactory.Server(); - save(ca.trustStore(), trust); - jettyFactory.setKeyStore(a); + save(trusted, trust); + jettyFactory.setKeyStore(keys); jettyFactory.setKeyStorePassword(new String(PASSWORD)); jettyFactory.setTrustStorePath(trust.toString()); jettyFactory.setTrustStoreType("JKS"); jettyFactory.setTrustStorePassword(new String(PASSWORD)); + + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + jettyFactory.start(); try { + SSLContext ctx = jettyFactory.getSslContext(); + Files.writeString(trust, "not a trust store"); - assertThrows(log, new ReloadableJettySslFactory(jettyFactory)::reload, IgniteException.class, null); - assertEquals(a.getCertificate(HOST), jettyFactory.getKeyStore().getCertificate(HOST)); + assertThrows(log, factory::reload, IgniteException.class, null); + assertSame(ctx, jettyFactory.getSslContext()); + + Certificate cert = keys.getCertificate(HOST); + + trusted.setCertificateEntry(HOST, cert); + save(trusted, trust); + factory.reload(); + + assertSame(keys, jettyFactory.getKeyStore()); + assertEquals(cert, jettyFactory.getTrustStore().getCertificate(HOST)); } finally { jettyFactory.stop(); @@ -260,10 +274,13 @@ public void testReloadCallsFactoryReloadOnce() throws Exception { jettyFactory.setKeyStore(fresh()); jettyFactory.setKeyStorePassword(new String(PASSWORD)); + + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + jettyFactory.start(); try { - new ReloadableJettySslFactory(jettyFactory).reload(); + factory.reload(); assertEquals(1, reloads.get()); } diff --git a/parent/pom.xml b/parent/pom.xml index 04629ecb634ce..46cb1de7fe40b 100644 --- a/parent/pom.xml +++ b/parent/pom.xml @@ -89,7 +89,7 @@ 1.0.0 3.6.3.Final 26.1.0 - 12.1.14 + 12.1.15 6.1.0 1.37 3.30.17 From 091d20048cc31ccfaf53a3dccb688eaad0521cbc Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 15:28:51 +0300 Subject: [PATCH 07/53] IGNITE-29212 Let Ignite SSL context factories implement ReloadableSslFactory The interface moves to ignite-commons, next to HotReloadTime, and its methods take the names that AbstractSslContextFactory already has: init() and getHotReloadTime(). The factory implements it without new public methods, so the registry needs no adapter. One register(String, Object) method replaces the two overloads, which would be ambiguous for a factory that is both a Factory and a ReloadableSslFactory. Co-Authored-By: Claude Opus 5.5 --- .../processors/ssl/ReloadableSslFactory.java | 10 ++-- .../ignite/ssl/AbstractSslContextFactory.java | 7 +-- .../processors/ssl/SslFactoryRegistry.java | 52 ++++++------------- .../ssl/SslFactoryRegistryTest.java | 9 ++-- .../http/jetty/ReloadableJettySslFactory.java | 4 +- .../http/jetty/JettyRestHttpsReloadTest.java | 14 ++--- 6 files changed, 40 insertions(+), 56 deletions(-) rename modules/{core => commons}/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java (82%) diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java similarity index 82% rename from modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java rename to modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index dce32b951cadc..7890e00be1cb5 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -17,18 +17,20 @@ package org.apache.ignite.internal.processors.ssl; -/** Operations that the SSL factory registry uses to reload a TLS factory on request and before its certificates expire. */ +import org.apache.ignite.IgniteException; + +/** TLS factory that the SSL factory registry can reload on request and before its certificates expire. */ public interface ReloadableSslFactory { /** * Loads the keys and trust settings again for new connections. If loading fails, new connections keep the previous ones. * - * @throws org.apache.ignite.IgniteException If loading fails. + * @throws IgniteException If loading fails. */ - public void reload(); + public void init(); /** * @return Time when the certificates that new connections use are due for hot reload, as calculated by * {@link HotReloadTime#of}, or {@code 0} if they give none. */ - public long hotReloadTime(); + public long getHotReloadTime(); } diff --git a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java index d2b723d3b2c3b..8c07b80d7b1db 100644 --- a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java @@ -31,12 +31,13 @@ import javax.net.ssl.TrustManager; import org.apache.ignite.IgniteException; import org.apache.ignite.internal.processors.ssl.HotReloadTime; +import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; import org.apache.ignite.internal.util.typedef.internal.A; /** * Base class for SSL context factories that cache their {@link SSLContext}. */ -public abstract class AbstractSslContextFactory implements Factory { +public abstract class AbstractSslContextFactory implements Factory, ReloadableSslFactory { /** */ private static final long serialVersionUID = 0L; @@ -71,7 +72,7 @@ public abstract class AbstractSslContextFactory implements Factory { * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the certificates have not been loaded yet * or the last successful load supplied no key store or no private key with an X.509 chain. */ - public long getHotReloadTime() { + @Override public long getHotReloadTime() { return hotReloadTime; } @@ -229,7 +230,7 @@ protected final synchronized KeyManager[] createKeyManagers(KeyManagerFactory ke * * @throws IgniteException If the context cannot be initialized. */ - public final synchronized void init() { + @Override public final synchronized void init() { try { sslCtx.set(createSslContext()); } diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 7e3f53dfea375..7bc3e102106bf 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -23,14 +23,11 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; -import javax.cache.configuration.Factory; -import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; import org.apache.ignite.internal.GridKernalContext; import org.apache.ignite.internal.processors.GridProcessorAdapter; import org.apache.ignite.internal.processors.metric.MetricRegistryImpl; import org.apache.ignite.internal.thread.context.function.OperationContextAwareRunnable; -import org.apache.ignite.ssl.AbstractSslContextFactory; import org.jetbrains.annotations.Nullable; import static java.util.concurrent.TimeUnit.HOURS; @@ -60,41 +57,21 @@ public SslFactoryRegistry(GridKernalContext ctx) { } /** - * Registers the factory of an Ignite transport. The registry can reload the factory if it extends - * {@link AbstractSslContextFactory}. + * @param transport Transport name. + * @param factory TLS factory of the transport. The registry reloads it if it implements {@link ReloadableSslFactory}. */ - public void register(String transport, Factory factory) { - add(transport, factory, factory instanceof AbstractSslContextFactory sslFactory ? new ReloadableSslFactory() { - /** {@inheritDoc} */ - @Override public void reload() { - sslFactory.init(); - } - - /** {@inheritDoc} */ - @Override public long hotReloadTime() { - return sslFactory.getHotReloadTime(); - } - } : null); - } - - /** Registers the TLS factory of a transport that does not use an Ignite SSL context factory, such as HTTP REST. */ - public void register(String transport, ReloadableSslFactory factory) { - add(transport, factory, factory); - } - - /** */ - private synchronized void add(String transport, Object factory, @Nullable ReloadableSslFactory reloadable) { + public synchronized void register(String transport, Object factory) { for (int i = 0; i < factories.size(); i++) { RegisteredFactory registered = factories.get(i); if (registered.factory == factory) { - factories.set(i, new RegisteredFactory(factory, registered.reloadable, registered.transports + ", " + transport)); + factories.set(i, new RegisteredFactory(factory, registered.transports + ", " + transport)); return; } } - factories.add(new RegisteredFactory(factory, reloadable, transport)); + factories.add(new RegisteredFactory(factory, transport)); } /** @return Registered factories in registration order. */ @@ -116,7 +93,7 @@ public List factories() { for (RegisteredFactory registered : factories) { if (registered.supportsReload()) { - registered.logHotReloadTime(registered.reloadable.hotReloadTime()); + registered.logHotReloadTime(registered.reloadable.getHotReloadTime()); hotReload = true; } @@ -163,7 +140,7 @@ public class RegisteredFactory { /** */ private final Object factory; - /** Reload operations of the factory, or {@code null} if the registry cannot reload it. */ + /** The factory if the registry can reload it, {@code null} otherwise. */ @Nullable private final ReloadableSslFactory reloadable; /** */ @@ -173,10 +150,11 @@ public class RegisteredFactory { private final AtomicInteger failures = new AtomicInteger(); /** */ - private RegisteredFactory(Object factory, @Nullable ReloadableSslFactory reloadable, String transports) { + private RegisteredFactory(Object factory, String transports) { this.factory = factory; - this.reloadable = reloadable; this.transports = transports; + + reloadable = factory instanceof ReloadableSslFactory sslFactory ? sslFactory : null; } /** @return The factory that the transports registered. */ @@ -224,7 +202,7 @@ else if (log.isDebugEnabled()) * @throws IgniteException If the reload fails or leaves certificates that are still due. */ private void reloadIfDue() { - if (!due(reloadable.hotReloadTime())) { + if (!due(reloadable.getHotReloadTime())) { failures.set(0); return; @@ -235,9 +213,9 @@ private void reloadIfDue() { if (log.isInfoEnabled()) log.info("TLS hot reload started [transports=" + transports + ']'); - reloadable.reload(); + reloadable.init(); - long hotReloadTime = reloadable.hotReloadTime(); + long hotReloadTime = reloadable.getHotReloadTime(); if (due(hotReloadTime)) { throw new IgniteException("Loaded certificates are still due for hot reload [hotReloadTime=" @@ -261,11 +239,11 @@ private static boolean due(long hotReloadTime) { public synchronized void reload() { manualReloadAttempts.incrementAndGet(); - reloadable.reload(); + reloadable.init(); failures.set(0); - logHotReloadTime(reloadable.hotReloadTime()); + logHotReloadTime(reloadable.getHotReloadTime()); } /** */ diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index 1ed1d3952298f..8a7375d8b2887 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -31,6 +31,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicInteger; +import javax.cache.configuration.Factory; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; @@ -196,7 +197,9 @@ public void testFactoriesAreGroupedInRegistrationOrder() { */ @Test public void testFactoryWithoutReloadDoesNotStartHotReload() { - registry.register("communication", () -> null); + Factory createOnly = () -> null; + + registry.register("communication", createOnly); registry.onKernalStart(true); executorFactory.verifyNoInteractions(); @@ -212,14 +215,14 @@ public void testFactoryWithoutReloadDoesNotStartHotReload() { public void testReloadableFactoryIsHotReloadedAndReloadedManually() { ReloadableSslFactory rest = mock(ReloadableSslFactory.class); - when(rest.hotReloadTime()).thenReturn(due(), due(), at(DAYS.toHours(30))); + when(rest.getHotReloadTime()).thenReturn(due(), due(), at(DAYS.toHours(30))); registry.register("HTTP REST", rest); registry.onKernalStart(true); check.run(); reload(rest); - verify(rest, times(2)).reload(); + verify(rest, times(2)).init(); assertEquals(1, metric("AutomaticHotReloadAttempts")); assertEquals(1, metric("ManualReloadAttempts")); assertEquals(0, failures()); diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index ff38f78a099c5..28843db3f329e 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -48,7 +48,7 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { } /** {@inheritDoc} */ - @Override public void reload() { + @Override public void init() { try { factory.unload(this::reloadLocked); } @@ -59,7 +59,7 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { } /** Reads the date from the keys that new connections use, including keys that the factory loaded without Ignite. */ - @Override public long hotReloadTime() { + @Override public long getHotReloadTime() { KeyStore store = factory.getKeyStore(); try { diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index f947d3143b4c1..3b32d2245d4f2 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -196,13 +196,13 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { jettyFactory.start(); try { - assertEquals(now + DAYS.toMillis(23), factory.hotReloadTime()); + assertEquals(now + DAYS.toMillis(23), factory.getHotReloadTime()); jettyFactory.reload(f -> { }); - assertEquals(now - HOURS.toMillis(6), factory.hotReloadTime()); - assertThrows(log, factory::reload, IgniteException.class, "Source is unavailable"); - assertEquals(now - HOURS.toMillis(6), factory.hotReloadTime()); + assertEquals(now - HOURS.toMillis(6), factory.getHotReloadTime()); + assertThrows(log, factory::init, IgniteException.class, "Source is unavailable"); + assertEquals(now - HOURS.toMillis(6), factory.getHotReloadTime()); } finally { jettyFactory.stop(); @@ -237,14 +237,14 @@ public void testTrustStoreReloadKeepsConfiguredKeysAfterFailure() throws Excepti Files.writeString(trust, "not a trust store"); - assertThrows(log, factory::reload, IgniteException.class, null); + assertThrows(log, factory::init, IgniteException.class, null); assertSame(ctx, jettyFactory.getSslContext()); Certificate cert = keys.getCertificate(HOST); trusted.setCertificateEntry(HOST, cert); save(trusted, trust); - factory.reload(); + factory.init(); assertSame(keys, jettyFactory.getKeyStore()); assertEquals(cert, jettyFactory.getTrustStore().getCertificate(HOST)); @@ -280,7 +280,7 @@ public void testReloadCallsFactoryReloadOnce() throws Exception { jettyFactory.start(); try { - factory.reload(); + factory.init(); assertEquals(1, reloads.get()); } From 9bc3e67bb6cc72720b909cb61f5e816788285864 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 15:53:42 +0300 Subject: [PATCH 08/53] IGNITE-29212 Check a factory when it becomes due before the next hourly check With a lead time of a third of the certificate lifetime, a certificate valid for three hours becomes due an hour before it expires, and the hourly check could come only at expiry. The hourly check stays. When a factory's certificates become due before the next hourly check, the registry also checks that factory at that time. A failed attempt is still retried at the next hourly check, so the failure log keeps an exact next attempt. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/security/ssl-tls.adoc | 1 + .../processors/ssl/SslFactoryRegistry.java | 61 ++++++++++++++-- .../ssl/SslFactoryRegistryTest.java | 72 +++++++++++++++++++ 3 files changed, 128 insertions(+), 6 deletions(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index fc55d76703391..10bce3458df3b 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -220,6 +220,7 @@ Ignite loads the replacements automatically when hot reload is due; no reload co At startup, Ignite checks each factory. After it finishes checking all factories, it waits one hour before checking them again. +If a factory becomes due before the next hourly check, Ignite also checks that factory when it becomes due. A slow certificate source can therefore delay a factory's next check by more than an hour. Each certificate in the private key chains, including issuing certificates, becomes due before it expires by a third of its lifetime, but by no more than 7 days. diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 7bc3e102106bf..3e9741f6b416b 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -20,7 +20,9 @@ import java.util.Date; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.ignite.IgniteException; @@ -45,6 +47,9 @@ public class SslFactoryRegistry extends GridProcessorAdapter { /** */ private volatile ScheduledExecutorService executor; + /** */ + private volatile ScheduledFuture hourlyCheck; + /** */ private final AtomicLong manualReloadAttempts = new AtomicLong(); @@ -104,10 +109,17 @@ public List factories() { executor = newSingleThreadScheduledExecutor("ssl-hot-reload", ctx.igniteInstanceName()); - executor.scheduleWithFixedDelay(new OperationContextAwareRunnable(this::checkFactories, null), + hourlyCheck = executor.scheduleWithFixedDelay(new OperationContextAwareRunnable(this::checkFactories, null), 0, CHECK_PERIOD, MILLISECONDS); } + /** @return Delay until the next hourly check in milliseconds, or the full period while the hourly check runs. */ + private long nextHourlyCheckDelay() { + long delay = hourlyCheck.getDelay(MILLISECONDS); + + return delay > 0 ? delay : CHECK_PERIOD; + } + /** @return Sum of consecutive automatic hot reload failures across factories. */ private long consecutiveHotReloadFailures() { long sum = 0; @@ -135,7 +147,7 @@ private void checkFactories() { executor.shutdownNow(); } - /** Registered factory with its transports and hot reload state. The hourly check and manual reload hold its monitor. */ + /** Registered factory with its transports and hot reload state. Its checks and manual reload hold its monitor. */ public class RegisteredFactory { /** */ private final Object factory; @@ -149,6 +161,9 @@ public class RegisteredFactory { /** */ private final AtomicInteger failures = new AtomicInteger(); + /** Check at the hot reload time if it comes before the next hourly check. */ + @Nullable private ScheduledFuture dueCheck; + /** */ private RegisteredFactory(Object factory, String transports) { this.factory = factory; @@ -189,7 +204,7 @@ private synchronized void check() { failures.incrementAndGet(); log.warning("TLS hot reload failed [transports=" + transports + ", nextAttempt=" - + new Date(System.currentTimeMillis() + CHECK_PERIOD) + ']', e); + + new Date(System.currentTimeMillis() + nextHourlyCheckDelay()) + ']', e); } else if (log.isDebugEnabled()) log.debug("TLS hot reload failed during node stop [transports=" + transports + ", err=" + e + ']'); @@ -202,9 +217,13 @@ else if (log.isDebugEnabled()) * @throws IgniteException If the reload fails or leaves certificates that are still due. */ private void reloadIfDue() { - if (!due(reloadable.getHotReloadTime())) { + long hotReloadTime = reloadable.getHotReloadTime(); + + if (!due(hotReloadTime)) { failures.set(0); + scheduleDueCheck(hotReloadTime); + return; } @@ -215,7 +234,7 @@ private void reloadIfDue() { reloadable.init(); - long hotReloadTime = reloadable.getHotReloadTime(); + hotReloadTime = reloadable.getHotReloadTime(); if (due(hotReloadTime)) { throw new IgniteException("Loaded certificates are still due for hot reload [hotReloadTime=" @@ -228,6 +247,31 @@ private void reloadIfDue() { log.info("TLS hot reload succeeded [transports=" + transports + ']'); logHotReloadTime(hotReloadTime); + + scheduleDueCheck(hotReloadTime); + } + + /** + * Schedules a check of this factory at the hot reload time if it comes before the next hourly check. + * The check replaces the one scheduled before. + */ + private void scheduleDueCheck(long hotReloadTime) { + if (dueCheck != null) + dueCheck.cancel(false); + + dueCheck = null; + + long delay = hotReloadTime - System.currentTimeMillis(); + + if (hotReloadTime == 0 || delay >= nextHourlyCheckDelay()) + return; + + try { + dueCheck = executor.schedule(new OperationContextAwareRunnable(this::check, null), delay, MILLISECONDS); + } + catch (RejectedExecutionException ignored) { + // The registry has stopped. + } } /** @return Whether the loaded certificates have a hot reload time, and it has come. */ @@ -243,7 +287,12 @@ public synchronized void reload() { failures.set(0); - logHotReloadTime(reloadable.getHotReloadTime()); + long hotReloadTime = reloadable.getHotReloadTime(); + + logHotReloadTime(hotReloadTime); + + if (hourlyCheck != null) + scheduleDueCheck(hotReloadTime); } /** */ diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index 8a7375d8b2887..f8c6b72afea7c 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -63,6 +63,7 @@ import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.MINUTES; import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD; import static org.apache.ignite.ssl.TestCertificateAuthority.save; import static org.apache.ignite.testframework.GridTestUtils.runAsync; @@ -74,6 +75,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.longThat; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -329,6 +331,61 @@ public void testHotReloadIsCheckedEveryHourFromStart() throws Exception { } } + /** + * Given: communication has certificates that are due for hot reload in 30 minutes, and the client connector has + * certificates that are due in 23 days. + * When: the hourly check runs. + * Then: the registry schedules one more check, of communication, in 30 minutes. + */ + @Test + public void testCheckIsScheduledAtHotReloadTimeBeforeNextHourlyCheck() throws Exception { + Path clientKeys = dir.resolve("client-keys.jks"); + + writeCertificatesDueIn30Minutes(keys); + writeFreshCertificates(clientKeys); + registerTransport("communication", factory(keys)); + registerTransport("client connector", factory(clientKeys)); + registry.onKernalStart(true); + check.run(); + + verify(executor).schedule(any(Runnable.class), longThat(SslFactoryRegistryTest::isAbout30Minutes), eq(MILLISECONDS)); + } + + /** + * Given: the loaded certificates are due for hot reload, and the key store gets certificates that are due in 30 minutes. + * When: the hourly check loads them. + * Then: the registry schedules the next check of the factory in 30 minutes. + */ + @Test + public void testHotReloadSchedulesCheckAtNewHotReloadTime() throws Exception { + writeDueCertificates(keys); + registerTransport("communication", factory(keys)); + registry.onKernalStart(true); + writeCertificatesDueIn30Minutes(keys); + check.run(); + + assertEquals(0, failures()); + verify(executor).schedule(any(Runnable.class), longThat(SslFactoryRegistryTest::isAbout30Minutes), eq(MILLISECONDS)); + } + + /** + * Given: the registry has started, and the key store gets certificates that are due for hot reload in 30 minutes. + * When: a manual reload loads them. + * Then: the registry schedules a check of the factory in 30 minutes. + */ + @Test + public void testManualReloadSchedulesCheckAtHotReloadTime() throws Exception { + SslContextFactory communication = factory(keys); + + writeFreshCertificates(keys); + registerTransport("communication", communication); + registry.onKernalStart(true); + writeCertificatesDueIn30Minutes(keys); + reload(communication); + + verify(executor).schedule(any(Runnable.class), longThat(SslFactoryRegistryTest::isAbout30Minutes), eq(MILLISECONDS)); + } + /** * Given: the registry starts during an operation with a request ID. * When: its worker reloads a factory with due certificates. @@ -893,6 +950,21 @@ private void writeDueCertificates(Path keyStore) throws Exception { save(authority.keyStore("node", at(-90), at(10)), keyStore); } + /** + * Writes a key store whose certificate became valid 30 minutes ago and expires in an hour, so it is due for hot reload + * in 30 minutes, a third of its lifetime before it expires. + */ + private void writeCertificatesDueIn30Minutes(Path keyStore) throws Exception { + long now = System.currentTimeMillis(); + + save(authority.keyStore("node", now - MINUTES.toMillis(30), now + MINUTES.toMillis(60)), keyStore); + } + + /** @return Whether the delay ends within the next 30 minutes, but no more than a minute earlier. */ + private static boolean isAbout30Minutes(long delay) { + return delay > MINUTES.toMillis(29) && delay <= MINUTES.toMillis(30); + } + /** * Writes a key store that is due for hot reload in 23 days. * Its certificate became valid an hour ago and expires in 30 days. From 40111c61de49a80811947ee15536626edae07e29 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 16:04:56 +0300 Subject: [PATCH 09/53] IGNITE-29212 Document overrides of ReloadableSslFactory with inheritDoc The interface now states the hot reload rule and the exception that its implementations may throw, so init() and getHotReloadTime() of AbstractSslContextFactory and of the Jetty adapter inherit their javadoc. The class javadoc of AbstractSslContextFactory keeps the guarantees that only it gives: create() returns the context that init() loaded last, and the date comes from the key store passed to createKeyManagers(). The Jetty adapter wraps the exception of a factory left without keys into IgniteException and documents the case when restoring the previous context fails too. Co-Authored-By: Claude Opus 5.5 --- .../processors/ssl/HotReloadTime.java | 4 +--- .../processors/ssl/ReloadableSslFactory.java | 10 +++++++-- .../ignite/ssl/AbstractSslContextFactory.java | 22 +++++-------------- .../http/jetty/ReloadableJettySslFactory.java | 12 +++++----- 4 files changed, 21 insertions(+), 27 deletions(-) diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/HotReloadTime.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/HotReloadTime.java index fb102ba628e6a..47ab94790a4ff 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/HotReloadTime.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/HotReloadTime.java @@ -36,9 +36,7 @@ private HotReloadTime() { } /** - * A certificate is due before it expires by a third of its lifetime, but by no more than 7 days. - * The key store is due when the first certificate in its private key chains is due, including issuing certificates. - * Keys without an X.509 certificate chain are ignored, as TLS cannot use them. + * Calculates the hot reload time that {@link ReloadableSslFactory#getHotReloadTime()} describes. * * @param store Loaded key store. * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the store has no private key diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index 7890e00be1cb5..040c34b380136 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -29,8 +29,14 @@ public interface ReloadableSslFactory { public void init(); /** - * @return Time when the certificates that new connections use are due for hot reload, as calculated by - * {@link HotReloadTime#of}, or {@code 0} if they give none. + * The hot reload time comes from the certificate chains of the private keys that new connections use. + * Each certificate in these chains is due before it expires by a third of its lifetime, but by no more than 7 days. + * The factory is due when its first certificate is due. Keys without an X.509 certificate chain are ignored, + * as TLS cannot use them. + * + * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the factory gives no private key with + * an X.509 certificate chain. + * @throws IgniteException If the factory cannot give the certificates that new connections use. */ public long getHotReloadTime(); } diff --git a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java index 8c07b80d7b1db..32afd51f86c64 100644 --- a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java @@ -35,7 +35,9 @@ import org.apache.ignite.internal.util.typedef.internal.A; /** - * Base class for SSL context factories that cache their {@link SSLContext}. + * Base class for SSL context factories that cache their {@link SSLContext}. {@link #init()} loads a new context, and + * {@link #create()} returns the last one that it loaded, loading one on the first call. The hot reload time comes from + * the key store that the factory passes to {@link #createKeyManagers(KeyManagerFactory, KeyStore, char[])}. */ public abstract class AbstractSslContextFactory implements Factory, ReloadableSslFactory { /** */ @@ -62,16 +64,7 @@ public abstract class AbstractSslContextFactory implements Factory, /** */ private transient long pendingHotReloadTime; - /** - * The hot reload time is calculated from the key store passed to - * {@link #createKeyManagers(KeyManagerFactory, KeyStore, char[])} during the last successful load. - * Each certificate in the chains of the private keys is due before it expires by a third of its lifetime, - * but by no more than 7 days. The factory is due when its first certificate is due. - * Keys without an X.509 certificate chain are ignored, as TLS cannot use them. - * - * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the certificates have not been loaded yet - * or the last successful load supplied no key store or no private key with an X.509 chain. - */ + /** {@inheritDoc} */ @Override public long getHotReloadTime() { return hotReloadTime; } @@ -224,12 +217,7 @@ protected final synchronized KeyManager[] createKeyManagers(KeyManagerFactory ke */ protected abstract TrustManager[] createTrustManagers() throws SSLException; - /** - * Loads a new SSL context and caches it for the base implementation of {@link #create()}. - * If loading fails, the previously cached context is kept. - * - * @throws IgniteException If the context cannot be initialized. - */ + /** {@inheritDoc} */ @Override public final synchronized void init() { try { sslCtx.set(createSslContext()); diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index 28843db3f329e..e1714ad1ac5a1 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -32,6 +32,8 @@ *

* Jetty clears its active context before loading the replacement. Holding its lock through reload and recovery lets * new connections use the previous context if loading fails. Jetty uses the accompanying key store for SNI. + * If reinstalling the previous context fails too, the factory has no context until the next successful reload, and the + * reload error carries that failure as a suppressed exception. */ class ReloadableJettySslFactory implements ReloadableSslFactory { /** */ @@ -58,15 +60,15 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { } } - /** Reads the date from the keys that new connections use, including keys that the factory loaded without Ignite. */ + /** {@inheritDoc} */ @Override public long getHotReloadTime() { - KeyStore store = factory.getKeyStore(); - try { + KeyStore store = factory.getKeyStore(); + return store == null ? 0 : HotReloadTime.of(store); } - catch (GeneralSecurityException e) { - throw new IgniteException(e); + catch (IllegalStateException | GeneralSecurityException e) { + throw new IgniteException("Failed to read the certificates of the HTTPS connector", e); } } From 10fd2ab3ca04eb51ba37745daf1d26cb296b6a56 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 16:10:18 +0300 Subject: [PATCH 10/53] IGNITE-29212 Keep the hot reload date rule in ReloadableSslFactory The rule moves from the separate HotReloadTime class to a static method of the interface whose getHotReloadTime() describes it, so the contract and its calculation are in one place. It is a static method rather than a default one, and the 7-day limit is not an interface field, so AbstractSslContextFactory gets no new public members. Co-Authored-By: Claude Opus 5.5 --- .../processors/ssl/HotReloadTime.java | 82 ------------------- .../processors/ssl/ReloadableSslFactory.java | 52 ++++++++++++ .../ignite/ssl/AbstractSslContextFactory.java | 3 +- .../http/jetty/ReloadableJettySslFactory.java | 3 +- 4 files changed, 54 insertions(+), 86 deletions(-) delete mode 100644 modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/HotReloadTime.java diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/HotReloadTime.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/HotReloadTime.java deleted file mode 100644 index 47ab94790a4ff..0000000000000 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/HotReloadTime.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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.apache.ignite.internal.processors.ssl; - -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.Enumeration; - -import static java.util.concurrent.TimeUnit.DAYS; - -/** Time when the certificates of a key store are due for hot reload. */ -public final class HotReloadTime { - /** Longest lead time before a certificate expires. */ - private static final long MAX_LEAD_MS = DAYS.toMillis(7); - - /** */ - private HotReloadTime() { - // No-op. - } - - /** - * Calculates the hot reload time that {@link ReloadableSslFactory#getHotReloadTime()} describes. - * - * @param store Loaded key store. - * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the store has no private key - * with an X.509 certificate chain. - * @throws GeneralSecurityException If the key store cannot be read. - */ - public static long of(KeyStore store) throws GeneralSecurityException { - long earliest = Long.MAX_VALUE; - - for (Enumeration aliases = store.aliases(); aliases.hasMoreElements(); ) { - String alias = aliases.nextElement(); - - if (store.isKeyEntry(alias)) - earliest = Math.min(earliest, chainTime(store.getCertificateChain(alias))); - } - - return earliest == Long.MAX_VALUE ? 0 : earliest; - } - - /** - * @param chain Certificate chain of a key entry, or {@code null} if the entry has none. - * @return Time when the first certificate in the chain is due, or {@link Long#MAX_VALUE} if there is no chain - * or it holds a certificate other than X.509, as TLS ignores such keys. - */ - private static long chainTime(Certificate[] chain) { - long time = Long.MAX_VALUE; - - if (chain == null) - return time; - - for (Certificate cert : chain) { - if (!(cert instanceof X509Certificate x509)) - return Long.MAX_VALUE; - - long notAfter = x509.getNotAfter().getTime(); - long lifetime = notAfter - x509.getNotBefore().getTime(); - - time = Math.min(time, notAfter - Math.min(MAX_LEAD_MS, lifetime / 3)); - } - - return time; - } -} diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index 040c34b380136..cad2609968c09 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -17,8 +17,15 @@ package org.apache.ignite.internal.processors.ssl; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Enumeration; import org.apache.ignite.IgniteException; +import static java.util.concurrent.TimeUnit.DAYS; + /** TLS factory that the SSL factory registry can reload on request and before its certificates expire. */ public interface ReloadableSslFactory { /** @@ -39,4 +46,49 @@ public interface ReloadableSslFactory { * @throws IgniteException If the factory cannot give the certificates that new connections use. */ public long getHotReloadTime(); + + /** + * Calculates the hot reload time that {@link #getHotReloadTime()} describes. + * + * @param store Loaded key store. + * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the store has no private key + * with an X.509 certificate chain. + * @throws GeneralSecurityException If the key store cannot be read. + */ + public static long hotReloadTime(KeyStore store) throws GeneralSecurityException { + long earliest = Long.MAX_VALUE; + + for (Enumeration aliases = store.aliases(); aliases.hasMoreElements(); ) { + String alias = aliases.nextElement(); + + if (store.isKeyEntry(alias)) + earliest = Math.min(earliest, chainHotReloadTime(store.getCertificateChain(alias))); + } + + return earliest == Long.MAX_VALUE ? 0 : earliest; + } + + /** + * @param chain Certificate chain of a key entry, or {@code null} if the entry has none. + * @return Time when the first certificate in the chain is due, or {@link Long#MAX_VALUE} if there is no chain + * or it holds a certificate other than X.509, as TLS ignores such keys. + */ + private static long chainHotReloadTime(Certificate[] chain) { + long time = Long.MAX_VALUE; + + if (chain == null) + return time; + + for (Certificate cert : chain) { + if (!(cert instanceof X509Certificate x509)) + return Long.MAX_VALUE; + + long notAfter = x509.getNotAfter().getTime(); + long lifetime = notAfter - x509.getNotBefore().getTime(); + + time = Math.min(time, notAfter - Math.min(DAYS.toMillis(7), lifetime / 3)); + } + + return time; + } } diff --git a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java index 32afd51f86c64..a5c535646263d 100644 --- a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java @@ -30,7 +30,6 @@ import javax.net.ssl.SSLParameters; import javax.net.ssl.TrustManager; import org.apache.ignite.IgniteException; -import org.apache.ignite.internal.processors.ssl.HotReloadTime; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; import org.apache.ignite.internal.util.typedef.internal.A; @@ -206,7 +205,7 @@ protected final synchronized KeyManager[] createKeyManagers(KeyManagerFactory ke throws GeneralSecurityException { keyMgrFactory.init(store, pwd); - pendingHotReloadTime = HotReloadTime.of(store); + pendingHotReloadTime = ReloadableSslFactory.hotReloadTime(store); return keyMgrFactory.getKeyManagers(); } diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index e1714ad1ac5a1..05f50a5fdec85 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -22,7 +22,6 @@ import java.util.function.Consumer; import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; -import org.apache.ignite.internal.processors.ssl.HotReloadTime; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.jetbrains.annotations.Nullable; @@ -65,7 +64,7 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { try { KeyStore store = factory.getKeyStore(); - return store == null ? 0 : HotReloadTime.of(store); + return store == null ? 0 : ReloadableSslFactory.hotReloadTime(store); } catch (IllegalStateException | GeneralSecurityException e) { throw new IgniteException("Failed to read the certificates of the HTTPS connector", e); From 29c9def3c8109a02a226cea0fb94f3ea8ef303ea Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 16:14:17 +0300 Subject: [PATCH 11/53] IGNITE-29212 Separate the hot reload attempt from scheduling the next check reloadIfDue() now only reloads a due factory. check() schedules the next check at the hot reload time after a check that did not fail, and a manual reload does the same, so the schedule is set in two places instead of three. The Jetty adapter asserts that it is created before Jetty starts, when the factory getters return the objects from jetty.xml. Co-Authored-By: Claude Opus 5.5 --- .../processors/ssl/SslFactoryRegistry.java | 26 +++++++------------ .../http/jetty/ReloadableJettySslFactory.java | 2 ++ 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 3e9741f6b416b..2419fb1b4c4ba 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -188,9 +188,9 @@ public boolean supportsReload() { } /** - * Checks the factory unless the registry has stopped. Counts and logs a failed check, so it does not stop - * the other factories or the schedule. A check that fails while the registry stops is logged at debug level - * and not counted. + * Checks the factory unless the registry has stopped, and schedules its next check at the hot reload time if + * it comes before the next hourly check. Counts and logs a failed check, so it does not stop the other factories + * or the schedule. A check that fails while the registry stops is logged at debug level and not counted. */ private synchronized void check() { if (executor.isShutdown()) @@ -198,6 +198,7 @@ private synchronized void check() { try { reloadIfDue(); + scheduleDueCheck(); } catch (Throwable e) { if (!executor.isShutdown()) { @@ -217,13 +218,9 @@ else if (log.isDebugEnabled()) * @throws IgniteException If the reload fails or leaves certificates that are still due. */ private void reloadIfDue() { - long hotReloadTime = reloadable.getHotReloadTime(); - - if (!due(hotReloadTime)) { + if (!due(reloadable.getHotReloadTime())) { failures.set(0); - scheduleDueCheck(hotReloadTime); - return; } @@ -234,7 +231,7 @@ private void reloadIfDue() { reloadable.init(); - hotReloadTime = reloadable.getHotReloadTime(); + long hotReloadTime = reloadable.getHotReloadTime(); if (due(hotReloadTime)) { throw new IgniteException("Loaded certificates are still due for hot reload [hotReloadTime=" @@ -247,20 +244,19 @@ private void reloadIfDue() { log.info("TLS hot reload succeeded [transports=" + transports + ']'); logHotReloadTime(hotReloadTime); - - scheduleDueCheck(hotReloadTime); } /** * Schedules a check of this factory at the hot reload time if it comes before the next hourly check. * The check replaces the one scheduled before. */ - private void scheduleDueCheck(long hotReloadTime) { + private void scheduleDueCheck() { if (dueCheck != null) dueCheck.cancel(false); dueCheck = null; + long hotReloadTime = reloadable.getHotReloadTime(); long delay = hotReloadTime - System.currentTimeMillis(); if (hotReloadTime == 0 || delay >= nextHourlyCheckDelay()) @@ -287,12 +283,10 @@ public synchronized void reload() { failures.set(0); - long hotReloadTime = reloadable.getHotReloadTime(); - - logHotReloadTime(hotReloadTime); + logHotReloadTime(reloadable.getHotReloadTime()); if (hourlyCheck != null) - scheduleDueCheck(hotReloadTime); + scheduleDueCheck(); } /** */ diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index 05f50a5fdec85..2e8a3d25ad64e 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -43,6 +43,8 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { /** @param factory TLS factory of the HTTPS connector before startup, when its getters expose the configured objects. */ ReloadableJettySslFactory(SslContextFactory factory) { + assert !factory.isStarted(); + this.factory = factory; configured = new TlsMaterial(factory); From b32d01f8e554771642c06dfecd1b92786e6471b3 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 16:22:08 +0300 Subject: [PATCH 12/53] IGNITE-29212 Name the registry's check after its role, not its period hourlyCheck becomes periodicCheck, and the javadoc of the registry and its tests says "periodic check" instead of "hourly check". A change of CHECK_PERIOD then needs no renames. The value stays only where it is the point: the constant, the test that pins it, and the user documentation. Co-Authored-By: Claude Opus 5.5 --- .../processors/ssl/SslFactoryRegistry.java | 24 ++++++++--------- .../ssl/SslFactoryRegistryTest.java | 26 +++++++++---------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 2419fb1b4c4ba..1d94bd265be18 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -48,7 +48,7 @@ public class SslFactoryRegistry extends GridProcessorAdapter { private volatile ScheduledExecutorService executor; /** */ - private volatile ScheduledFuture hourlyCheck; + private volatile ScheduledFuture periodicCheck; /** */ private final AtomicLong manualReloadAttempts = new AtomicLong(); @@ -109,13 +109,13 @@ public List factories() { executor = newSingleThreadScheduledExecutor("ssl-hot-reload", ctx.igniteInstanceName()); - hourlyCheck = executor.scheduleWithFixedDelay(new OperationContextAwareRunnable(this::checkFactories, null), + periodicCheck = executor.scheduleWithFixedDelay(new OperationContextAwareRunnable(this::checkFactories, null), 0, CHECK_PERIOD, MILLISECONDS); } - /** @return Delay until the next hourly check in milliseconds, or the full period while the hourly check runs. */ - private long nextHourlyCheckDelay() { - long delay = hourlyCheck.getDelay(MILLISECONDS); + /** @return Delay until the next periodic check in milliseconds, or the full period while the periodic check runs. */ + private long nextPeriodicCheckDelay() { + long delay = periodicCheck.getDelay(MILLISECONDS); return delay > 0 ? delay : CHECK_PERIOD; } @@ -130,7 +130,7 @@ private long consecutiveHotReloadFailures() { return sum; } - /** Runs the hourly check of the factories that support reload. */ + /** Runs the periodic check of the factories that support reload. */ private void checkFactories() { if (log.isDebugEnabled()) log.debug("TLS hot reload check started"); @@ -161,7 +161,7 @@ public class RegisteredFactory { /** */ private final AtomicInteger failures = new AtomicInteger(); - /** Check at the hot reload time if it comes before the next hourly check. */ + /** Check at the hot reload time if it comes before the next periodic check. */ @Nullable private ScheduledFuture dueCheck; /** */ @@ -189,7 +189,7 @@ public boolean supportsReload() { /** * Checks the factory unless the registry has stopped, and schedules its next check at the hot reload time if - * it comes before the next hourly check. Counts and logs a failed check, so it does not stop the other factories + * it comes before the next periodic check. Counts and logs a failed check, so it does not stop the other factories * or the schedule. A check that fails while the registry stops is logged at debug level and not counted. */ private synchronized void check() { @@ -205,7 +205,7 @@ private synchronized void check() { failures.incrementAndGet(); log.warning("TLS hot reload failed [transports=" + transports + ", nextAttempt=" - + new Date(System.currentTimeMillis() + nextHourlyCheckDelay()) + ']', e); + + new Date(System.currentTimeMillis() + nextPeriodicCheckDelay()) + ']', e); } else if (log.isDebugEnabled()) log.debug("TLS hot reload failed during node stop [transports=" + transports + ", err=" + e + ']'); @@ -247,7 +247,7 @@ private void reloadIfDue() { } /** - * Schedules a check of this factory at the hot reload time if it comes before the next hourly check. + * Schedules a check of this factory at the hot reload time if it comes before the next periodic check. * The check replaces the one scheduled before. */ private void scheduleDueCheck() { @@ -259,7 +259,7 @@ private void scheduleDueCheck() { long hotReloadTime = reloadable.getHotReloadTime(); long delay = hotReloadTime - System.currentTimeMillis(); - if (hotReloadTime == 0 || delay >= nextHourlyCheckDelay()) + if (hotReloadTime == 0 || delay >= nextPeriodicCheckDelay()) return; try { @@ -285,7 +285,7 @@ public synchronized void reload() { logHotReloadTime(reloadable.getHotReloadTime()); - if (hourlyCheck != null) + if (periodicCheck != null) scheduleDueCheck(); } diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index f8c6b72afea7c..dcb2cc68baa87 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -86,7 +86,7 @@ /** * A manual reload is {@link SslFactoryRegistry#reload}, which the TLS reload command calls. - * An attempt is an automatic hot reload attempt that the hourly check makes. + * An attempt is an automatic hot reload attempt that the periodic check makes. */ public class SslFactoryRegistryTest { /** Upper bound for waiting for an event that must happen. */ @@ -110,7 +110,7 @@ public class SslFactoryRegistryTest { /** */ private MockedStatic executorFactory; - /** Hourly hot reload check that the registry scheduled. */ + /** Periodic hot reload check that the registry scheduled. */ private Runnable check; /** */ @@ -126,7 +126,7 @@ public class SslFactoryRegistryTest { private TestCertificateAuthority authority; /** - * Each test gets a registry whose hot reload executor records the hourly check instead of running it. + * Each test gets a registry whose hot reload executor records the periodic check instead of running it. * Tests run the check themselves. * The setup also writes the trust store of a test CA to a temporary directory and stubs the node metrics and logger. */ @@ -210,7 +210,7 @@ public void testFactoryWithoutReloadDoesNotStartHotReload() { /** * Given: HTTP REST registers a factory that is not an Ignite SSL context factory, with certificates due for hot reload. - * When: the hourly check runs, and then a manual reload runs. + * When: the periodic check runs, and then a manual reload runs. * Then: the registry reloads the factory each time and counts one automatic and one manual attempt. */ @Test @@ -232,7 +232,7 @@ public void testReloadableFactoryIsHotReloadedAndReloadedManually() { /** * Given: communication and discovery share a factory, and the client connector has an equal factory for the same file. - * When: the key store is replaced and the hourly check runs. + * When: the key store is replaced and the periodic check runs. * Then: each factory instance loads the new certificates once. */ @Test @@ -282,7 +282,7 @@ public void testManualReloadLoadsOnlyItsFactoryInstance() throws Exception { /** * Given: the key store holds only a CA certificate. - * When: the registry starts and the hourly check runs, then the operator puts a key store with a private key in place + * When: the registry starts and the periodic check runs, then the operator puts a key store with a private key in place * and reloads it. * Then: the registry logs that hot reload will not run, and the check makes no attempt. * After the reload, the log shows when hot reload is due. @@ -310,11 +310,11 @@ public void testStoreWithoutPrivateKeyIsReportedUntilKeysAreReloaded() throws Ex /** * Given: the loaded certificates are due for hot reload, and the key store file is deleted after start. - * When: the hourly check runs three times. - * Then: the check runs at start and then every hour, and each run counts one more failed attempt. + * When: the periodic check runs three times. + * Then: the check runs at start and then every check period of an hour, and each run counts one more failed attempt. */ @Test - public void testHotReloadIsCheckedEveryHourFromStart() throws Exception { + public void testHotReloadIsCheckedPeriodicallyFromStart() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); @@ -334,11 +334,11 @@ public void testHotReloadIsCheckedEveryHourFromStart() throws Exception { /** * Given: communication has certificates that are due for hot reload in 30 minutes, and the client connector has * certificates that are due in 23 days. - * When: the hourly check runs. + * When: the periodic check runs. * Then: the registry schedules one more check, of communication, in 30 minutes. */ @Test - public void testCheckIsScheduledAtHotReloadTimeBeforeNextHourlyCheck() throws Exception { + public void testCheckIsScheduledAtHotReloadTimeBeforeNextPeriodicCheck() throws Exception { Path clientKeys = dir.resolve("client-keys.jks"); writeCertificatesDueIn30Minutes(keys); @@ -353,7 +353,7 @@ public void testCheckIsScheduledAtHotReloadTimeBeforeNextHourlyCheck() throws Ex /** * Given: the loaded certificates are due for hot reload, and the key store gets certificates that are due in 30 minutes. - * When: the hourly check loads them. + * When: the periodic check loads them. * Then: the registry schedules the next check of the factory in 30 minutes. */ @Test @@ -416,7 +416,7 @@ public void testHotReloadDoesNotInheritStartupContext() throws Exception { /** * Given: two factories with due certificates, and loading the first one throws an error, * as a missing class of a key store provider does. - * When: the hourly check runs. + * When: the periodic check runs. * Then: the check completes normally, so the executor keeps the schedule. It counts and logs the error * and still reloads the second factory. */ From 949d8debadfefbdf123ca767616eaadc3032b1d2 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 16:31:40 +0300 Subject: [PATCH 13/53] IGNITE-29212 Register SSL context factories with their type ReloadableSslFactory now extends Factory, so register() takes a Factory again instead of an Object, and the registry entry keeps that type. The Jetty adapter returns the context of the HTTPS connector from create(). It is serializable only because Factory is, so its Jetty fields are transient. Co-Authored-By: Claude Opus 5.5 --- .../processors/ssl/ReloadableSslFactory.java | 6 ++++-- .../internal/processors/ssl/SslFactoryRegistry.java | 13 ++++++++----- .../processors/ssl/SslFactoryRegistryTest.java | 2 +- .../http/jetty/ReloadableJettySslFactory.java | 13 +++++++++++-- 4 files changed, 24 insertions(+), 10 deletions(-) diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index cad2609968c09..817bea9985c4f 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -22,12 +22,14 @@ import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Enumeration; +import javax.cache.configuration.Factory; +import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; import static java.util.concurrent.TimeUnit.DAYS; -/** TLS factory that the SSL factory registry can reload on request and before its certificates expire. */ -public interface ReloadableSslFactory { +/** SSL context factory that the SSL factory registry can reload on request and before its certificates expire. */ +public interface ReloadableSslFactory extends Factory { /** * Loads the keys and trust settings again for new connections. If loading fails, new connections keep the previous ones. * diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 1d94bd265be18..7355856021c1e 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -25,6 +25,8 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import javax.cache.configuration.Factory; +import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; import org.apache.ignite.internal.GridKernalContext; import org.apache.ignite.internal.processors.GridProcessorAdapter; @@ -63,9 +65,10 @@ public SslFactoryRegistry(GridKernalContext ctx) { /** * @param transport Transport name. - * @param factory TLS factory of the transport. The registry reloads it if it implements {@link ReloadableSslFactory}. + * @param factory SSL context factory of the transport. The registry reloads it if it implements + * {@link ReloadableSslFactory}. */ - public synchronized void register(String transport, Object factory) { + public synchronized void register(String transport, Factory factory) { for (int i = 0; i < factories.size(); i++) { RegisteredFactory registered = factories.get(i); @@ -150,7 +153,7 @@ private void checkFactories() { /** Registered factory with its transports and hot reload state. Its checks and manual reload hold its monitor. */ public class RegisteredFactory { /** */ - private final Object factory; + private final Factory factory; /** The factory if the registry can reload it, {@code null} otherwise. */ @Nullable private final ReloadableSslFactory reloadable; @@ -165,7 +168,7 @@ public class RegisteredFactory { @Nullable private ScheduledFuture dueCheck; /** */ - private RegisteredFactory(Object factory, String transports) { + private RegisteredFactory(Factory factory, String transports) { this.factory = factory; this.transports = transports; @@ -173,7 +176,7 @@ private RegisteredFactory(Object factory, String transports) { } /** @return The factory that the transports registered. */ - public Object factory() { + public Factory factory() { return factory; } diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index dcb2cc68baa87..b6d05e048ca73 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -886,7 +886,7 @@ private List captureLog(boolean debug) { } /** Reloads the registered factory, as the reload command does. */ - private void reload(Object factory) { + private void reload(Factory factory) { for (RegisteredFactory registered : registry.factories()) { if (registered.factory() == factory) registered.reload(); diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index 2e8a3d25ad64e..f2d364c9733c7 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -20,6 +20,7 @@ import java.security.GeneralSecurityException; import java.security.KeyStore; import java.util.function.Consumer; +import javax.cache.configuration.Factory; import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; @@ -35,11 +36,14 @@ * reload error carries that failure as a suppressed exception. */ class ReloadableJettySslFactory implements ReloadableSslFactory { + /** The adapter is serializable only because {@link Factory} is, and is never serialized. */ + private static final long serialVersionUID = 0L; + /** */ - private final SslContextFactory factory; + private final transient SslContextFactory factory; /** Objects supplied directly to Jetty. A null store lets the factory read its configured source. */ - private final TlsMaterial configured; + private final transient TlsMaterial configured; /** @param factory TLS factory of the HTTPS connector before startup, when its getters expose the configured objects. */ ReloadableJettySslFactory(SslContextFactory factory) { @@ -50,6 +54,11 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { configured = new TlsMaterial(factory); } + /** {@inheritDoc} */ + @Override public SSLContext create() { + return factory.getSslContext(); + } + /** {@inheritDoc} */ @Override public void init() { try { From 58b4ac71810e30b8935381875fd00fc3cc75aa00 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 16:59:25 +0300 Subject: [PATCH 14/53] IGNITE-29212 Give each SSL factory one scheduled check A periodic check of all factories plus a separate check at the hot reload time needed two futures per schedule and a comparison of their delays. Now each factory has one scheduled check: at its hot reload time, but no later than CHECK_PERIOD after the previous one, and CHECK_PERIOD after a failure. A manual reload reschedules the check of its factory. The check is scheduled only after the registry has started, which scheduleCheck() itself verifies, so reload() calls it without a condition. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/security/ssl-tls.adoc | 6 +- .../processors/ssl/SslFactoryRegistry.java | 93 ++++++----- .../ssl/SslFactoryRegistryTest.java | 147 ++++++++++++------ 3 files changed, 149 insertions(+), 97 deletions(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index 10bce3458df3b..30443c8bae313 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -219,9 +219,9 @@ Ignite loads the replacements automatically when hot reload is due; no reload co === When Hot Reload Runs At startup, Ignite checks each factory. -After it finishes checking all factories, it waits one hour before checking them again. -If a factory becomes due before the next hourly check, Ignite also checks that factory when it becomes due. -A slow certificate source can therefore delay a factory's next check by more than an hour. +It checks each factory again when its certificates become due, but no later than an hour after the previous check. +After a failed attempt, it retries an hour later. +All checks run in one thread, so a slow certificate source can delay the checks of other factories. Each certificate in the private key chains, including issuing certificates, becomes due before it expires by a third of its lifetime, but by no more than 7 days. For example, a certificate valid for 24 hours is due 8 hours before it expires, and a certificate valid for 90 days is due 7 days before. diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 7355856021c1e..477e5f00b72ab 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -40,7 +40,7 @@ /** SSL factories used by running transports. */ public class SslFactoryRegistry extends GridProcessorAdapter { - /** */ + /** Longest interval between two checks of a factory, and the delay of a retry after a failed check. */ private static final long CHECK_PERIOD = HOURS.toMillis(1); /** */ @@ -49,9 +49,6 @@ public class SslFactoryRegistry extends GridProcessorAdapter { /** */ private volatile ScheduledExecutorService executor; - /** */ - private volatile ScheduledFuture periodicCheck; - /** */ private final AtomicLong manualReloadAttempts = new AtomicLong(); @@ -112,15 +109,10 @@ public List factories() { executor = newSingleThreadScheduledExecutor("ssl-hot-reload", ctx.igniteInstanceName()); - periodicCheck = executor.scheduleWithFixedDelay(new OperationContextAwareRunnable(this::checkFactories, null), - 0, CHECK_PERIOD, MILLISECONDS); - } - - /** @return Delay until the next periodic check in milliseconds, or the full period while the periodic check runs. */ - private long nextPeriodicCheckDelay() { - long delay = periodicCheck.getDelay(MILLISECONDS); - - return delay > 0 ? delay : CHECK_PERIOD; + for (RegisteredFactory registered : factories) { + if (registered.supportsReload()) + registered.scheduleCheck(0); + } } /** @return Sum of consecutive automatic hot reload failures across factories. */ @@ -133,17 +125,6 @@ private long consecutiveHotReloadFailures() { return sum; } - /** Runs the periodic check of the factories that support reload. */ - private void checkFactories() { - if (log.isDebugEnabled()) - log.debug("TLS hot reload check started"); - - for (RegisteredFactory registered : factories) { - if (registered.supportsReload()) - registered.check(); - } - } - /** {@inheritDoc} */ @Override public void onKernalStop(boolean cancel) { if (executor != null) @@ -164,8 +145,8 @@ public class RegisteredFactory { /** */ private final AtomicInteger failures = new AtomicInteger(); - /** Check at the hot reload time if it comes before the next periodic check. */ - @Nullable private ScheduledFuture dueCheck; + /** */ + @Nullable private ScheduledFuture nextCheck; /** */ private RegisteredFactory(Factory factory, String transports) { @@ -191,28 +172,41 @@ public boolean supportsReload() { } /** - * Checks the factory unless the registry has stopped, and schedules its next check at the hot reload time if - * it comes before the next periodic check. Counts and logs a failed check, so it does not stop the other factories - * or the schedule. A check that fails while the registry stops is logged at debug level and not counted. + * Checks the factory unless the registry has stopped, and schedules its next check. Counts and logs a failed + * check and retries it after {@link #CHECK_PERIOD}, so a failure does not stop the checks. A check that fails + * while the registry stops is logged at debug level and not counted. */ private synchronized void check() { if (executor.isShutdown()) return; + if (log.isDebugEnabled()) + log.debug("TLS hot reload check started [transports=" + transports + ']'); + + long nextCheckDelay; + try { reloadIfDue(); - scheduleDueCheck(); + + nextCheckDelay = nextCheckDelay(); } catch (Throwable e) { - if (!executor.isShutdown()) { - failures.incrementAndGet(); + if (executor.isShutdown()) { + if (log.isDebugEnabled()) + log.debug("TLS hot reload failed during node stop [transports=" + transports + ", err=" + e + ']'); - log.warning("TLS hot reload failed [transports=" + transports + ", nextAttempt=" - + new Date(System.currentTimeMillis() + nextPeriodicCheckDelay()) + ']', e); + return; } - else if (log.isDebugEnabled()) - log.debug("TLS hot reload failed during node stop [transports=" + transports + ", err=" + e + ']'); + + failures.incrementAndGet(); + + nextCheckDelay = CHECK_PERIOD; + + log.warning("TLS hot reload failed [transports=" + transports + ", nextAttempt=" + + new Date(System.currentTimeMillis() + nextCheckDelay) + ']', e); } + + scheduleCheck(nextCheckDelay); } /** @@ -250,23 +244,25 @@ private void reloadIfDue() { } /** - * Schedules a check of this factory at the hot reload time if it comes before the next periodic check. - * The check replaces the one scheduled before. + * @return Delay until the hot reload time, but no longer than {@link #CHECK_PERIOD}. Certificates without a hot + * reload time, or that are already due, are checked again after the full period. */ - private void scheduleDueCheck() { - if (dueCheck != null) - dueCheck.cancel(false); - - dueCheck = null; + private long nextCheckDelay() { + long delay = reloadable.getHotReloadTime() - System.currentTimeMillis(); - long hotReloadTime = reloadable.getHotReloadTime(); - long delay = hotReloadTime - System.currentTimeMillis(); + return delay > 0 ? Math.min(delay, CHECK_PERIOD) : CHECK_PERIOD; + } - if (hotReloadTime == 0 || delay >= nextPeriodicCheckDelay()) + /** Replaces the scheduled check of the factory with one after the given delay, once the registry has started. */ + private synchronized void scheduleCheck(long delay) { + if (executor == null) return; + if (nextCheck != null) + nextCheck.cancel(false); + try { - dueCheck = executor.schedule(new OperationContextAwareRunnable(this::check, null), delay, MILLISECONDS); + nextCheck = executor.schedule(new OperationContextAwareRunnable(this::check, null), delay, MILLISECONDS); } catch (RejectedExecutionException ignored) { // The registry has stopped. @@ -288,8 +284,7 @@ public synchronized void reload() { logHotReloadTime(reloadable.getHotReloadTime()); - if (periodicCheck != null) - scheduleDueCheck(); + scheduleCheck(nextCheckDelay()); } /** */ diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index b6d05e048ca73..9c99387bbbb8e 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -24,6 +24,7 @@ import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Date; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; @@ -75,7 +76,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.longThat; +import static org.mockito.Mockito.RETURNS_DEFAULTS; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -86,7 +87,7 @@ /** * A manual reload is {@link SslFactoryRegistry#reload}, which the TLS reload command calls. - * An attempt is an automatic hot reload attempt that the periodic check makes. + * An attempt is an automatic hot reload attempt that a scheduled check makes. */ public class SslFactoryRegistryTest { /** Upper bound for waiting for an event that must happen. */ @@ -110,8 +111,8 @@ public class SslFactoryRegistryTest { /** */ private MockedStatic executorFactory; - /** Periodic hot reload check that the registry scheduled. */ - private Runnable check; + /** Checks that the registry has scheduled and that have not run or been cancelled, with their delays, in scheduling order. */ + private final Map scheduled = new LinkedHashMap<>(); /** */ private Path dir; @@ -126,8 +127,8 @@ public class SslFactoryRegistryTest { private TestCertificateAuthority authority; /** - * Each test gets a registry whose hot reload executor records the periodic check instead of running it. - * Tests run the check themselves. + * Each test gets a registry whose hot reload executor records the scheduled checks instead of running them. + * Tests run the checks themselves. * The setup also writes the trust store of a test CA to a temporary directory and stubs the node metrics and logger. */ @Before @@ -147,10 +148,14 @@ public void setUp() throws Exception { registry = new SslFactoryRegistry(ctx); - when(executor.scheduleWithFixedDelay(any(Runnable.class), anyLong(), anyLong(), eq(MILLISECONDS))).thenAnswer(call -> { - check = call.getArgument(0); + when(executor.schedule(any(Runnable.class), anyLong(), eq(MILLISECONDS))).thenAnswer(call -> { + Runnable check = call.getArgument(0); - return mock(ScheduledFuture.class); + scheduled.put(check, call.getArgument(1)); + + return mock(ScheduledFuture.class, cancel -> "cancel".equals(cancel.getMethod().getName()) + ? scheduled.remove(check) != null + : RETURNS_DEFAULTS.answer(cancel)); }); executorFactory = mockStatic(IgniteScheduledThreadPoolExecutor.class); @@ -221,7 +226,7 @@ public void testReloadableFactoryIsHotReloadedAndReloadedManually() { registry.register("HTTP REST", rest); registry.onKernalStart(true); - check.run(); + runChecks(); reload(rest); verify(rest, times(2)).init(); @@ -249,7 +254,7 @@ public void testEachFactoryInstanceReloadsOnce() throws Exception { long prevTime = communication.getHotReloadTime(); writeFreshCertificates(keys); - check.run(); + runChecks(); assertEquals(2, metric("AutomaticHotReloadAttempts")); assertTrue(communication.getHotReloadTime() > prevTime); @@ -295,7 +300,7 @@ public void testStoreWithoutPrivateKeyIsReportedUntilKeysAreReloaded() throws Ex save(authority.trustStore(), keys); registerTransport("communication", communication); registry.onKernalStart(true); - check.run(); + runChecks(); assertEquals(1, logged.size()); assertTrue(logged.get(0), logged.get(0).startsWith("TLS hot reload will not run")); @@ -310,11 +315,12 @@ public void testStoreWithoutPrivateKeyIsReportedUntilKeysAreReloaded() throws Ex /** * Given: the loaded certificates are due for hot reload, and the key store file is deleted after start. - * When: the periodic check runs three times. - * Then: the check runs at start and then every check period of an hour, and each run counts one more failed attempt. + * When: the scheduled check runs three times. + * Then: the first check runs at start, each failed check schedules a retry in an hour, and each run counts one more + * failed attempt. */ @Test - public void testHotReloadIsCheckedPeriodicallyFromStart() throws Exception { + public void testFailedCheckIsRetriedAfterCheckPeriod() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); @@ -322,23 +328,25 @@ public void testHotReloadIsCheckedPeriodicallyFromStart() throws Exception { registry.onKernalStart(true); Files.delete(keys); - verify(executor).scheduleWithFixedDelay(any(Runnable.class), eq(0L), eq(HOURS.toMillis(1)), eq(MILLISECONDS)); + assertEquals(List.of(0L), List.copyOf(scheduled.values())); for (int failure = 1; failure <= 3; failure++) { - check.run(); + runChecks(); assertEquals(failure, failures()); + assertEquals(List.of(HOURS.toMillis(1)), List.copyOf(scheduled.values())); } } /** * Given: communication has certificates that are due for hot reload in 30 minutes, and the client connector has * certificates that are due in 23 days. - * When: the periodic check runs. - * Then: the registry schedules one more check, of communication, in 30 minutes. + * When: the checks at start run. + * Then: the next check of communication comes at its hot reload time, and the next check of the client connector + * comes in an hour, the longest interval between checks. */ @Test - public void testCheckIsScheduledAtHotReloadTimeBeforeNextPeriodicCheck() throws Exception { + public void testNextCheckComesAtHotReloadTimeButWithinCheckPeriod() throws Exception { Path clientKeys = dir.resolve("client-keys.jks"); writeCertificatesDueIn30Minutes(keys); @@ -346,15 +354,18 @@ public void testCheckIsScheduledAtHotReloadTimeBeforeNextPeriodicCheck() throws registerTransport("communication", factory(keys)); registerTransport("client connector", factory(clientKeys)); registry.onKernalStart(true); - check.run(); + runChecks(); + + List delays = List.copyOf(scheduled.values()); - verify(executor).schedule(any(Runnable.class), longThat(SslFactoryRegistryTest::isAbout30Minutes), eq(MILLISECONDS)); + assertTrue(delays.toString(), isAbout30Minutes(delays.get(0))); + assertEquals(HOURS.toMillis(1), (long)delays.get(1)); } /** * Given: the loaded certificates are due for hot reload, and the key store gets certificates that are due in 30 minutes. - * When: the periodic check loads them. - * Then: the registry schedules the next check of the factory in 30 minutes. + * When: the scheduled check loads them. + * Then: the next check of the factory comes in 30 minutes. */ @Test public void testHotReloadSchedulesCheckAtNewHotReloadTime() throws Exception { @@ -362,16 +373,16 @@ public void testHotReloadSchedulesCheckAtNewHotReloadTime() throws Exception { registerTransport("communication", factory(keys)); registry.onKernalStart(true); writeCertificatesDueIn30Minutes(keys); - check.run(); + runChecks(); assertEquals(0, failures()); - verify(executor).schedule(any(Runnable.class), longThat(SslFactoryRegistryTest::isAbout30Minutes), eq(MILLISECONDS)); + assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); } /** * Given: the registry has started, and the key store gets certificates that are due for hot reload in 30 minutes. * When: a manual reload loads them. - * Then: the registry schedules a check of the factory in 30 minutes. + * Then: the check that the registry scheduled at start is replaced by one in 30 minutes. */ @Test public void testManualReloadSchedulesCheckAtHotReloadTime() throws Exception { @@ -383,7 +394,25 @@ public void testManualReloadSchedulesCheckAtHotReloadTime() throws Exception { writeCertificatesDueIn30Minutes(keys); reload(communication); - verify(executor).schedule(any(Runnable.class), longThat(SslFactoryRegistryTest::isAbout30Minutes), eq(MILLISECONDS)); + assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); + } + + /** + * Given: the registry has started, and the key store still holds certificates that are due for hot reload. + * When: a manual reload loads them. + * Then: the failure count is zero, and the next check comes in an hour rather than right away. + */ + @Test + public void testManualReloadOfDueCertificatesDefersNextCheck() throws Exception { + SslContextFactory communication = factory(keys); + + writeDueCertificates(keys); + registerTransport("communication", communication); + registry.onKernalStart(true); + reload(communication); + + assertEquals(0, failures()); + assertEquals(HOURS.toMillis(1), nextCheckDelay()); } /** @@ -432,7 +461,7 @@ public void testErrorFromOneFactoryDoesNotStopCheck() throws Exception { registerTransport("client connector", clientConnector); registry.onKernalStart(true); writeFreshCertificates(keys); - check.run(); + runChecks(); assertEquals(1, failures()); assertEquals(2, metric("AutomaticHotReloadAttempts")); @@ -457,9 +486,9 @@ public void testLogShowsDueTimeStartAndResultOfAttempts() throws Exception { long due = communication.getHotReloadTime(); Files.delete(keys); - check.run(); + runChecks(); writeFreshCertificates(keys); - check.run(); + runChecks(); List evts = new ArrayList<>(); @@ -489,18 +518,18 @@ public void testSuccessResetsFailuresAndLaterChecksWait() throws Exception { registerTransport("communication", communication); registry.onKernalStart(true); Files.delete(keys); - check.run(); + runChecks(); assertEquals(1, failures()); assertEquals(1, metric("AutomaticHotReloadAttempts")); writeFreshCertificates(keys); - check.run(); + runChecks(); assertEquals(0, failures()); assertEquals(2, metric("AutomaticHotReloadAttempts")); - check.run(); + runChecks(); assertEquals(2, metric("AutomaticHotReloadAttempts")); } @@ -518,13 +547,13 @@ public void testCheckResetsFailuresWhenFactoryIsNoLongerDue() throws Exception { writeDueCertificates(keys); registerTransport("communication", communication); registry.onKernalStart(true); - check.run(); + runChecks(); assertEquals(1, failures()); writeFreshCertificates(keys); communication.init(); - check.run(); + runChecks(); assertEquals(0, failures()); assertEquals(1, metric("AutomaticHotReloadAttempts")); @@ -593,7 +622,7 @@ public void testScheduledReloadUsesCustomFactoryKeyStoreAndPassword() throws Exc KeyStore replacement = authority.keyStore("node", at(-1), at(DAYS.toHours(30)), replacementPwd); custom.setKeys(replacement, replacementPwd); - check.run(); + runChecks(); assertNotSame(initCtx, custom.create()); @@ -621,7 +650,7 @@ public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { custom.setKeys(null, null); reload(custom); - check.run(); + runChecks(); assertEquals(0, custom.getHotReloadTime()); assertEquals(0, metric("AutomaticHotReloadAttempts")); @@ -656,7 +685,7 @@ public void testFailedManualReloadKeepsFailures() throws Exception { registerTransport("communication", communication); registry.onKernalStart(true); Files.delete(keys); - check.run(); + runChecks(); IgniteException err = assertThrows(IgniteException.class, () -> reload(communication)); @@ -691,7 +720,7 @@ public void testManualReloadWaitsForRunningAttempt() throws Exception { return false; }); - GridTestThread attempt = new GridTestThread(check); + GridTestThread attempt = new GridTestThread(nextCheck()); GridTestThread manualReload = new GridTestThread(() -> reload(communication)); attempt.start(); @@ -738,7 +767,7 @@ public void testManualReloadResetsOnlyItsFactoryFailures() throws Exception { registerTransport("communication", communication); registerTransport("client connector", clientConnector); registry.onKernalStart(true); - check.run(); + runChecks(); assertEquals(1, failures()); @@ -747,7 +776,7 @@ public void testManualReloadResetsOnlyItsFactoryFailures() throws Exception { assertEquals(1, failures()); - check.run(); + runChecks(); assertEquals(3, failures()); @@ -821,10 +850,10 @@ public void testAttemptFailingDuringStopIsNotCounted() { registry.register("communication", factory); registry.onKernalStart(true); - check.run(); + runChecks(); assertEquals(0, failures()); - assertTrue(logged.toString(), logged.contains("TLS hot reload check started")); + assertTrue(logged.toString(), logged.contains("TLS hot reload check started [transports=communication]")); assertTrue(logged.toString(), logged.toString().contains("TLS hot reload failed during node stop [transports=communication, err=")); } @@ -854,7 +883,7 @@ public void testStopDuringCheckSkipsRemainingFactories() { registry.register("communication", factory); registry.register("client connector", clientConnector); registry.onKernalStart(true); - check.run(); + runChecks(); assertEquals(1, loads.get()); } @@ -885,6 +914,34 @@ private List captureLog(boolean debug) { return logged; } + /** Runs the checks that the registry has scheduled, in scheduling order. The checks that they schedule stay pending. */ + private void runChecks() { + List checks = List.copyOf(scheduled.keySet()); + + scheduled.clear(); + + for (Runnable check : checks) + check.run(); + } + + /** @return The only check that the registry has scheduled, which no longer counts as pending. */ + private Runnable nextCheck() { + assertEquals(1, scheduled.size()); + + Runnable check = scheduled.keySet().iterator().next(); + + scheduled.clear(); + + return check; + } + + /** @return Delay of the only check that the registry has scheduled. */ + private long nextCheckDelay() { + assertEquals(1, scheduled.size()); + + return scheduled.values().iterator().next(); + } + /** Reloads the registered factory, as the reload command does. */ private void reload(Factory factory) { for (RegisteredFactory registered : registry.factories()) { From a914e1ac3ccf22bc7510835115499db23b6066e2 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 19:44:27 +0300 Subject: [PATCH 15/53] IGNITE-29212 Name the Jetty factory lock in the adapter The class javadoc now says which lock the reload holds: the internal lock of Jetty's factory, under which it loads its TLS state and new connections take it. reloadLocked becomes reloadOrRestore and works on the factory field, ReloadDone becomes SkipUnload, and TlsMaterial becomes TlsState. The fields are no longer transient: the adapter is serializable only because Factory is, and serializing it now fails instead of producing an adapter without its Jetty factory. Co-Authored-By: Claude Opus 5.5 --- .../http/jetty/ReloadableJettySslFactory.java | 76 ++++++++++--------- 1 file changed, 40 insertions(+), 36 deletions(-) diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index f2d364c9733c7..e98b50e28ead0 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -30,28 +30,32 @@ /** * TLS factory of the Jetty HTTPS connector. A failed reload leaves the previous keys and trust settings in use. *

- * Jetty clears its active context before loading the replacement. Holding its lock through reload and recovery lets - * new connections use the previous context if loading fails. Jetty uses the accompanying key store for SNI. - * If reinstalling the previous context fails too, the factory has no context until the next successful reload, and the - * reload error carries that failure as a suppressed exception. + * Jetty's factory guards its TLS state with an internal lock: it loads the state under this lock, and new connections + * take the state under it too. Before loading a replacement, Jetty clears the state. So that new connections never see + * a factory without keys, the reload and, if loading fails, the restore of the previous state run under this lock. + * Jetty lets callers hold the lock only inside {@link SslContextFactory#unload(Consumer)} and + * {@link SslContextFactory#reload(Consumer)}, so the work runs inside {@code unload(...)} and ends with {@link SkipUnload}. + * Jetty selects certificates for SNI host names from the key store of the state, so the restore keeps SNI selection. + * If the restore fails too, the factory has no state until the next successful reload, and the reload error carries + * that failure as a suppressed exception. */ class ReloadableJettySslFactory implements ReloadableSslFactory { - /** The adapter is serializable only because {@link Factory} is, and is never serialized. */ + /** The adapter is serializable only because {@link Factory} is. Serializing it fails, as Jetty's factory is not serializable. */ private static final long serialVersionUID = 0L; /** */ - private final transient SslContextFactory factory; + private final SslContextFactory factory; - /** Objects supplied directly to Jetty. A null store lets the factory read its configured source. */ - private final transient TlsMaterial configured; + /** State set in {@code jetty.xml}. The factory loads a {@code null} part from its configured source. */ + private final TlsState configured; - /** @param factory TLS factory of the HTTPS connector before startup, when its getters expose the configured objects. */ + /** @param factory TLS factory of the HTTPS connector before startup, when its getters return the state set in {@code jetty.xml}. */ ReloadableJettySslFactory(SslContextFactory factory) { assert !factory.isStarted(); this.factory = factory; - configured = new TlsMaterial(factory); + configured = new TlsState(factory); } /** {@inheritDoc} */ @@ -62,11 +66,11 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { /** {@inheritDoc} */ @Override public void init() { try { - factory.unload(this::reloadLocked); + factory.unload(ignored -> reloadOrRestore()); } - catch (ReloadDone done) { - if (done.err != null) - throw new IgniteException(done.err); + catch (SkipUnload skip) { + if (skip.loadErr != null) + throw new IgniteException(skip.loadErr); } } @@ -83,45 +87,45 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { } /** - * Reloads the factory while {@link SslContextFactory#unload(Consumer)} holds its lock. - * Always throws {@link ReloadDone}, so that {@code unload(...)} does not unload the factory. + * Reloads the factory and, if loading fails, restores the state that new connections used before. Runs under the + * factory lock inside {@code unload(...)}, and always throws {@link SkipUnload}. */ - private void reloadLocked(SslContextFactory f) { - TlsMaterial prev = new TlsMaterial(f); + private void reloadOrRestore() { + TlsState prev = new TlsState(factory); try { - f.reload(ignored -> {}); + factory.reload(ignored -> {}); } catch (Exception e) { - restore(f, prev, e); + restore(prev, e); - throw new ReloadDone(e); + throw new SkipUnload(e); } - throw new ReloadDone(null); + throw new SkipUnload(null); } - /** Reinstalls the working context, then restores the settings Jetty will use on the next reload. */ - private void restore(SslContextFactory f, TlsMaterial prev, Exception err) { + /** Makes the factory load the previous state, then sets back the state from {@code jetty.xml} for the next reload. */ + private void restore(TlsState prev, Exception loadErr) { try { - f.reload(prev::applyTo); + factory.reload(prev::applyTo); } catch (Exception e) { - err.addSuppressed(e); + loadErr.addSuppressed(e); } finally { - configured.applyTo(f); + configured.applyTo(factory); } } - /** The context and stores Jetty uses together for new connections. */ - private record TlsMaterial(SSLContext ctx, KeyStore keyStore, KeyStore trustStore) { + /** Context and stores that Jetty uses together for new connections. */ + private record TlsState(SSLContext ctx, KeyStore keyStore, KeyStore trustStore) { /** */ - TlsMaterial(SslContextFactory factory) { + TlsState(SslContextFactory factory) { this(factory.getSslContext(), factory.getKeyStore(), factory.getTrustStore()); } - /** */ + /** Sets this state on the factory, which loads it on the next reload. */ private void applyTo(SslContextFactory factory) { factory.setSslContext(ctx); factory.setKeyStore(keyStore); @@ -129,19 +133,19 @@ private void applyTo(SslContextFactory factory) { } } - /** Ends {@code unload(...)} without unloading the factory. */ - private static class ReloadDone extends RuntimeException { + /** Ends {@code unload(...)} before it unloads the factory. */ + private static class SkipUnload extends RuntimeException { /** */ private static final long serialVersionUID = 0L; /** Load failure, or {@code null} if the factory has the replacement. */ - @Nullable private final Exception err; + @Nullable private final Exception loadErr; /** */ - private ReloadDone(@Nullable Exception err) { + private SkipUnload(@Nullable Exception loadErr) { super(null, null, false, false); - this.err = err; + this.loadErr = loadErr; } } } From 47a838a41242e1a644c02fe4e6a76b5f7176a386 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 19:50:01 +0300 Subject: [PATCH 16/53] IGNITE-29212 Say what SkipUnload does not do SkipUnload only keeps the outer unload(...) from unloading the factory. The state that a failed reload inside has already cleared comes back from restore(...). Co-Authored-By: Claude Opus 5.5 --- .../rest/protocols/http/jetty/ReloadableJettySslFactory.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index e98b50e28ead0..ef98a291e64c8 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -133,7 +133,10 @@ private void applyTo(SslContextFactory factory) { } } - /** Ends {@code unload(...)} before it unloads the factory. */ + /** + * Ends the outer {@code unload(...)} before it unloads the factory. It does not bring back the state that a failed + * reload inside has already cleared: {@code restore(...)} does that. + */ private static class SkipUnload extends RuntimeException { /** */ private static final long serialVersionUID = 0L; From e9a9a9bc52be98d0156af292b6181d37adedd6a7 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 20:37:52 +0300 Subject: [PATCH 17/53] IGNITE-29212 Start hot reload in one pass over the registered factories onKernalStart() no longer goes over the factories twice with a flag in between: it creates the hot reload thread for the first factory that supports reload, logs the hot reload time of each such factory and schedules its first check. The javadoc of reload() now says that it schedules the next check of its factory. Co-Authored-By: Claude Opus 5.5 --- .../processors/ssl/SslFactoryRegistry.java | 26 +++++++------------ 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 477e5f00b72ab..6de3172e6aa91 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -94,24 +94,15 @@ public List factories() { metrics.register("AutomaticHotReloadAttempts", automaticHotReloadAttempts::get, "Number of automatic hot reload attempts."); - boolean hotReload = false; - for (RegisteredFactory registered : factories) { - if (registered.supportsReload()) { - registered.logHotReloadTime(registered.reloadable.getHotReloadTime()); - - hotReload = true; - } - } - - if (!hotReload) - return; + if (!registered.supportsReload()) + continue; - executor = newSingleThreadScheduledExecutor("ssl-hot-reload", ctx.igniteInstanceName()); + if (executor == null) + executor = newSingleThreadScheduledExecutor("ssl-hot-reload", ctx.igniteInstanceName()); - for (RegisteredFactory registered : factories) { - if (registered.supportsReload()) - registered.scheduleCheck(0); + registered.logHotReloadTime(registered.reloadable.getHotReloadTime()); + registered.scheduleCheck(0); } } @@ -274,7 +265,10 @@ private static boolean due(long hotReloadTime) { return hotReloadTime != 0 && hotReloadTime <= System.currentTimeMillis(); } - /** Reloads a factory that supports reload. Waits for its running check and resets its failure count. */ + /** + * Reloads a factory that supports reload. Waits for its running check, resets its failure count and schedules + * its next check for the loaded certificates. + */ public synchronized void reload() { manualReloadAttempts.incrementAndGet(); From 987263651e5d7d2bb31fb971c324fa906fa3b98d Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 20:40:59 +0300 Subject: [PATCH 18/53] IGNITE-29212 Report a Jetty factory without TLS state as IgniteException If a reload outside Ignite has left the Jetty factory without TLS state, its getters throw IllegalStateException. init() let it escape, while ReloadableSslFactory declares IgniteException; now it wraps it, as getHotReloadTime() already does. The docs no longer call the next check after a manual reload hourly. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/security/ssl-tls.adoc | 2 +- .../http/jetty/ReloadableJettySslFactory.java | 3 +++ .../http/jetty/JettyRestHttpsReloadTest.java | 26 +++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index 30443c8bae313..a042f528f028e 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -234,7 +234,7 @@ If the loaded certificates are still due for hot reload, Ignite records a failed This can happen when the certificates have not changed, only the trust store changed, or the replacements are already due when loaded. The loaded context remains in use until a later reload replaces it. -After a manual reload, the next hourly check uses the loaded certificates. +After a manual reload, Ignite schedules the next check from the loaded certificates. New connections use the loaded certificates; established connections remain open. To confirm a replacement, open a new TLS connection to each affected endpoint and compare its peer certificate with the replacement. diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index ef98a291e64c8..a78f55e1df410 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -72,6 +72,9 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { if (skip.loadErr != null) throw new IgniteException(skip.loadErr); } + catch (IllegalStateException e) { + throw new IgniteException("Failed to read the TLS state of the HTTPS connector", e); + } } /** {@inheritDoc} */ diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index 3b32d2245d4f2..70d6dba235f4e 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -39,6 +39,7 @@ import org.apache.ignite.internal.management.api.CommandInvoker; import org.apache.ignite.internal.management.api.NoArg; import org.apache.ignite.internal.management.ssl.SslReloadCommand; +import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; import org.apache.ignite.ssl.TestCertificateAuthority; import org.apache.ignite.testframework.junits.WithSystemProperty; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; @@ -209,6 +210,31 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { } } + /** + * Given: a reload that Ignite did not start, such as one by Jetty's {@code KeyStoreScanner}, has failed and left + * the custom Jetty factory without keys. + * When: Ignite reloads the factory and reads its hot reload time. + * Then: both fail with {@link IgniteException}, as {@link ReloadableSslFactory} declares. + */ + @Test + public void testFactoryLeftWithoutKeysFailsWithIgniteException() throws Exception { + SourceSslContextFactory.supply(fresh(), new IOException("Source is unavailable")); + + SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + + jettyFactory.start(); + + try { + assertThrows(log, () -> jettyFactory.reload(f -> { }), Exception.class, "Source is unavailable"); + assertThrows(log, factory::init, IgniteException.class, "TLS state of the HTTPS connector"); + assertThrows(log, factory::getHotReloadTime, IgniteException.class, "certificates of the HTTPS connector"); + } + finally { + jettyFactory.stop(); + } + } + /** * Given: Jetty has keys configured in memory and reads its trust store from a file. * When: reload fails because the file is corrupt, then the operator replaces it and retries. From 189017e33a8591a50632375d2420ea53272e8b95 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 20:48:45 +0300 Subject: [PATCH 19/53] IGNITE-29212 Document that a failed HTTPS reload drops stores set on the running factory After a failed reload, the Jetty factory gets back the context and stores from jetty.xml. Jetty's getters return the loaded state once the factory has started, so the adapter cannot keep a context or store that code sets on the running factory. The REST API docs now ask users to keep the stores in the sources that the factory loads. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/restapi.adoc | 3 +++ .../rest/protocols/http/jetty/ReloadableJettySslFactory.java | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/docs/_docs/restapi.adoc b/docs/_docs/restapi.adoc index c25c17fe27477..f85cfd1d8028d 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -116,6 +116,9 @@ New connections use the replacement certificates; established connections stay o If loading fails, the endpoint keeps its current keys and trust settings, and new connections keep working with them. Correct the stores and run the command again. +Keep the stores in the sources that the factory loads: the store paths in the Jetty XML file, or the `loadKeyStore(Resource)` and `loadTrustStore(Resource)` methods of a custom subclass. +A store that your code sets on the running factory, for example with `setKeyStore(KeyStore)`, does not survive a failed reload: the next reload loads the stores configured in the Jetty XML file instead. + === Security When link:security/authentication[authentication] is configured in the cluster, all applications that use REST API request authentication by providing security credentials. diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index a78f55e1df410..8dab9453cb5e1 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -38,6 +38,11 @@ * Jetty selects certificates for SNI host names from the key store of the state, so the restore keeps SNI selection. * If the restore fails too, the factory has no state until the next successful reload, and the reload error carries * that failure as a suppressed exception. + *

+ * After a failed reload, the factory gets back the context and stores set in {@code jetty.xml}, and the next reload + * reads its configured sources again. Once the factory has started, its getters return the loaded state rather than + * these settings. So the adapter cannot keep a context or store that code sets on the running factory: a failed reload + * drops it. */ class ReloadableJettySslFactory implements ReloadableSslFactory { /** The adapter is serializable only because {@link Factory} is. Serializing it fails, as Jetty's factory is not serializable. */ From 74ccdd01c7f52454b7d2bb2a97895c02b7b0b2d8 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 21:18:17 +0300 Subject: [PATCH 20/53] IGNITE-29212 Decide each hot reload check from one read of the hot reload time A check read the hot reload time twice: once to decide whether to reload, and once for the delay of the next check. If the time came between the two reads, the check neither reloaded the factory nor scheduled a check at that time, and waited an hour. Now one read gives both the decision and the delay. The registry no longer reads the hot reload time at start. A Jetty factory that a reload outside Ignite has left without keys fails that read, and the failure stopped the node start. The first scheduled check now reads and logs the time, and a failure there is counted and retried like any failed check. The registry logs the time when it differs from the one logged last. The REST API docs tell the operator to restart the node when Jetty fails to load the previous keys back after a failed reload. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/restapi.adoc | 2 + .../processors/ssl/SslFactoryRegistry.java | 66 +++++++++++-------- .../ssl/SslFactoryRegistryTest.java | 52 +++++++++++++++ 3 files changed, 94 insertions(+), 26 deletions(-) diff --git a/docs/_docs/restapi.adoc b/docs/_docs/restapi.adoc index f85cfd1d8028d..d47233a123bc5 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -115,6 +115,8 @@ Each reload asks the Jetty factory to load its stores again. New connections use the replacement certificates; established connections stay open. If loading fails, the endpoint keeps its current keys and trust settings, and new connections keep working with them. Correct the stores and run the command again. +If Jetty also fails to load the current keys back, new HTTPS connections fail, and the next run of the command reports `Failed to read the TLS state of the HTTPS connector`. +In this case, fix the cause and restart the node. Keep the stores in the sources that the factory loads: the store paths in the Jetty XML file, or the `loadKeyStore(Resource)` and `loadTrustStore(Resource)` methods of a custom subclass. A store that your code sets on the running factory, for example with `setKeyStore(KeyStore)`, does not survive a failed reload: the next reload loads the stores configured in the Jetty XML file instead. diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 6de3172e6aa91..282dddcff83d5 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -101,7 +101,6 @@ public List factories() { if (executor == null) executor = newSingleThreadScheduledExecutor("ssl-hot-reload", ctx.igniteInstanceName()); - registered.logHotReloadTime(registered.reloadable.getHotReloadTime()); registered.scheduleCheck(0); } } @@ -139,6 +138,9 @@ public class RegisteredFactory { /** */ @Nullable private ScheduledFuture nextCheck; + /** Hot reload time that the registry logged last, or {@code -1} before the first log. */ + private long loggedHotReloadTime = -1; + /** */ private RegisteredFactory(Factory factory, String transports) { this.factory = factory; @@ -177,9 +179,16 @@ private synchronized void check() { long nextCheckDelay; try { - reloadIfDue(); + long hotReloadTime = reloadable.getHotReloadTime(); + + logHotReloadTime(hotReloadTime); + + nextCheckDelay = nextCheckDelay(hotReloadTime); - nextCheckDelay = nextCheckDelay(); + if (nextCheckDelay == 0) + nextCheckDelay = hotReload(); + else + failures.set(0); } catch (Throwable e) { if (executor.isShutdown()) { @@ -201,17 +210,12 @@ private synchronized void check() { } /** - * Reloads the factory if its hot reload time has come, and ends the failure streak if it has not. + * Reloads the factory, whose hot reload time has come, and ends the failure streak. * + * @return Delay of the next check. * @throws IgniteException If the reload fails or leaves certificates that are still due. */ - private void reloadIfDue() { - if (!due(reloadable.getHotReloadTime())) { - failures.set(0); - - return; - } - + private long hotReload() { automaticHotReloadAttempts.incrementAndGet(); if (log.isInfoEnabled()) @@ -220,8 +224,9 @@ private void reloadIfDue() { reloadable.init(); long hotReloadTime = reloadable.getHotReloadTime(); + long nextCheckDelay = nextCheckDelay(hotReloadTime); - if (due(hotReloadTime)) { + if (nextCheckDelay == 0) { throw new IgniteException("Loaded certificates are still due for hot reload [hotReloadTime=" + new Date(hotReloadTime) + ']'); } @@ -232,16 +237,20 @@ private void reloadIfDue() { log.info("TLS hot reload succeeded [transports=" + transports + ']'); logHotReloadTime(hotReloadTime); + + return nextCheckDelay; } /** - * @return Delay until the hot reload time, but no longer than {@link #CHECK_PERIOD}. Certificates without a hot - * reload time, or that are already due, are checked again after the full period. + * @param hotReloadTime Hot reload time of the loaded certificates, or {@code 0} if they have none. + * @return Delay until the hot reload time, but no longer than {@link #CHECK_PERIOD}, or {@code 0} if the time has + * come. Certificates without a hot reload time are checked again after the full period. */ - private long nextCheckDelay() { - long delay = reloadable.getHotReloadTime() - System.currentTimeMillis(); + private static long nextCheckDelay(long hotReloadTime) { + if (hotReloadTime == 0) + return CHECK_PERIOD; - return delay > 0 ? Math.min(delay, CHECK_PERIOD) : CHECK_PERIOD; + return Math.max(0, Math.min(hotReloadTime - System.currentTimeMillis(), CHECK_PERIOD)); } /** Replaces the scheduled check of the factory with one after the given delay, once the registry has started. */ @@ -260,14 +269,10 @@ private synchronized void scheduleCheck(long delay) { } } - /** @return Whether the loaded certificates have a hot reload time, and it has come. */ - private static boolean due(long hotReloadTime) { - return hotReloadTime != 0 && hotReloadTime <= System.currentTimeMillis(); - } - /** * Reloads a factory that supports reload. Waits for its running check, resets its failure count and schedules - * its next check for the loaded certificates. + * its next check for the loaded certificates. If they are already due, the next check comes after + * {@link #CHECK_PERIOD}, because a hot reload right away would load the same certificates from the source. */ public synchronized void reload() { manualReloadAttempts.incrementAndGet(); @@ -276,13 +281,22 @@ public synchronized void reload() { failures.set(0); - logHotReloadTime(reloadable.getHotReloadTime()); + long hotReloadTime = reloadable.getHotReloadTime(); + + logHotReloadTime(hotReloadTime); + + long nextCheckDelay = nextCheckDelay(hotReloadTime); - scheduleCheck(nextCheckDelay()); + scheduleCheck(nextCheckDelay == 0 ? CHECK_PERIOD : nextCheckDelay); } - /** */ + /** Logs the hot reload time of the loaded certificates if it differs from the one logged last. */ private void logHotReloadTime(long hotReloadTime) { + if (hotReloadTime == loggedHotReloadTime) + return; + + loggedHotReloadTime = hotReloadTime; + if (hotReloadTime == 0) { log.warning("TLS hot reload will not run: no private key with an X.509 certificate chain was found [transports=" + transports + ']'); diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index 9c99387bbbb8e..1bfbd3e2cc17c 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -32,6 +32,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; import javax.cache.configuration.Factory; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; @@ -338,6 +339,31 @@ public void testFailedCheckIsRetriedAfterCheckPeriod() throws Exception { } } + /** + * Given: two factories, and reading the hot reload time of the first one fails, as it does for a Jetty factory that + * a failed reload outside the registry has left without keys. + * When: the registry starts and its checks run. + * Then: the start completes, the check of the first factory fails and is retried in an hour, and the second factory + * gets its next check at its hot reload time. + */ + @Test + public void testFailedReadOfHotReloadTimeIsRetriedWithoutFailingStart() throws Exception { + ReloadableSslFactory rest = mock(ReloadableSslFactory.class); + + when(rest.getHotReloadTime()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")); + writeCertificatesDueIn30Minutes(keys); + registry.register("HTTP REST", rest); + registerTransport("communication", factory(keys)); + registry.onKernalStart(true); + runChecks(); + + List delays = List.copyOf(scheduled.values()); + + assertEquals(1, failures()); + assertEquals(HOURS.toMillis(1), (long)delays.get(0)); + assertTrue(delays.toString(), isAbout30Minutes(delays.get(1))); + } + /** * Given: communication has certificates that are due for hot reload in 30 minutes, and the client connector has * certificates that are due in 23 days. @@ -362,6 +388,32 @@ public void testNextCheckComesAtHotReloadTimeButWithinCheckPeriod() throws Excep assertEquals(HOURS.toMillis(1), (long)delays.get(1)); } + /** + * Given: the certificates of a factory become due for hot reload a second after the registry starts, and each read + * of their hot reload time takes 600 ms, as it does while a reload outside the registry holds the factory. + * When: the check at start runs. + * Then: the factory is hot reloaded no later than its hot reload time: the check either reloads it or schedules + * the next check within that second. + */ + @Test + public void testCheckRightBeforeHotReloadTimeSchedulesCheckAtThatTime() { + ReloadableSslFactory rest = mock(ReloadableSslFactory.class); + AtomicLong hotReloadTime = new AtomicLong(at(DAYS.toHours(30))); + + when(rest.getHotReloadTime()).thenAnswer(call -> { + Thread.sleep(600); + + return hotReloadTime.get(); + }); + + registry.register("HTTP REST", rest); + registry.onKernalStart(true); + hotReloadTime.set(System.currentTimeMillis() + 1000); + runChecks(); + + assertTrue(scheduled.toString(), metric("AutomaticHotReloadAttempts") == 1 || nextCheckDelay() <= 1000); + } + /** * Given: the loaded certificates are due for hot reload, and the key store gets certificates that are due in 30 minutes. * When: the scheduled check loads them. From acc33ad321e5fd5ba8a3d93933c319445272c78a Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 21:29:35 +0300 Subject: [PATCH 21/53] IGNITE-29212 Keep the HTTPS keys when a Jetty reload throws an error The adapter restored the previous TLS state only after an exception. A reload that threw an error left the Jetty factory without keys, while ReloadableSslFactory.init() promises that new connections keep the previous ones after any failed load. The adapter now restores the state after any throwable, as Ignite factories keep their context. The REST API docs no longer describe a failed restore. Jetty restores the previous context without reading the stores, so a restore fails only when code changes the running factory's settings. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/restapi.adoc | 2 -- .../http/jetty/ReloadableJettySslFactory.java | 10 +++--- .../http/jetty/JettyRestHttpsReloadTest.java | 33 +++++++++++++++++-- 3 files changed, 36 insertions(+), 9 deletions(-) diff --git a/docs/_docs/restapi.adoc b/docs/_docs/restapi.adoc index d47233a123bc5..f85cfd1d8028d 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -115,8 +115,6 @@ Each reload asks the Jetty factory to load its stores again. New connections use the replacement certificates; established connections stay open. If loading fails, the endpoint keeps its current keys and trust settings, and new connections keep working with them. Correct the stores and run the command again. -If Jetty also fails to load the current keys back, new HTTPS connections fail, and the next run of the command reports `Failed to read the TLS state of the HTTPS connector`. -In this case, fix the cause and restart the node. Keep the stores in the sources that the factory loads: the store paths in the Jetty XML file, or the `loadKeyStore(Resource)` and `loadTrustStore(Resource)` methods of a custom subclass. A store that your code sets on the running factory, for example with `setKeyStore(KeyStore)`, does not survive a failed reload: the next reload loads the stores configured in the Jetty XML file instead. diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index 8dab9453cb5e1..e848e828beb81 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -104,7 +104,7 @@ private void reloadOrRestore() { try { factory.reload(ignored -> {}); } - catch (Exception e) { + catch (Throwable e) { restore(prev, e); throw new SkipUnload(e); @@ -114,11 +114,11 @@ private void reloadOrRestore() { } /** Makes the factory load the previous state, then sets back the state from {@code jetty.xml} for the next reload. */ - private void restore(TlsState prev, Exception loadErr) { + private void restore(TlsState prev, Throwable loadErr) { try { factory.reload(prev::applyTo); } - catch (Exception e) { + catch (Throwable e) { loadErr.addSuppressed(e); } finally { @@ -150,10 +150,10 @@ private static class SkipUnload extends RuntimeException { private static final long serialVersionUID = 0L; /** Load failure, or {@code null} if the factory has the replacement. */ - @Nullable private final Exception loadErr; + @Nullable private final Throwable loadErr; /** */ - private SkipUnload(@Nullable Exception loadErr) { + private SkipUnload(@Nullable Throwable loadErr) { super(null, null, false, false); this.loadErr = loadErr; diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index 70d6dba235f4e..2220d4b7b1ff4 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -210,6 +210,32 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { } } + /** + * Given: a custom Jetty factory has loaded its keys, and its source then throws an error instead of an exception. + * When: Ignite reloads the factory. + * Then: the reload fails with {@link IgniteException}, and the factory keeps its working context, as + * {@link ReloadableSslFactory#init()} promises for any failure. + */ + @Test + public void testErrorFromSourceKeepsLastWorkingKeys() throws Exception { + SourceSslContextFactory.supply(fresh(), new NoClassDefFoundError("Key store provider")); + + SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + + jettyFactory.start(); + + try { + SSLContext ctx = jettyFactory.getSslContext(); + + assertThrows(log, factory::init, IgniteException.class, "Key store provider"); + assertSame(ctx, jettyFactory.getSslContext()); + } + finally { + jettyFactory.stop(); + } + } + /** * Given: a reload that Ignite did not start, such as one by Jetty's {@code KeyStoreScanner}, has failed and left * the custom Jetty factory without keys. @@ -373,13 +399,13 @@ private Certificate serverCertificate(IgniteEx node) throws Exception { /** * Custom Jetty factory that takes its key stores from a source in memory instead of a file. - * Each load takes the next key store or throws the next exception that the test supplied. The last one repeats. + * Each load takes the next key store or throws the next exception or error that the test supplied. The last one repeats. */ public static class SourceSslContextFactory extends SslContextFactory.Server { /** */ private static final Deque LOADS = new ConcurrentLinkedDeque<>(); - /** Replaces what the next loads take: key stores and exceptions, in order. */ + /** Replaces what the next loads take: key stores, exceptions and errors, in order. */ private static void supply(Object... loads) { LOADS.clear(); LOADS.addAll(List.of(loads)); @@ -402,6 +428,9 @@ public SourceSslContextFactory() throws Exception { if (load instanceof Exception e) throw e; + if (load instanceof Error e) + throw e; + return (KeyStore)load; } } From cae7151057053d61af4a2c86545c611f6f6c0323 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 21:35:18 +0300 Subject: [PATCH 22/53] IGNITE-29212 Name the boundary test after the guarantee it checks The test accepts either a reload in the check or a next check within the hot reload time, so its name now says that the check does not defer the hot reload. Co-Authored-By: Claude Opus 5.5 --- .../ignite/internal/processors/ssl/SslFactoryRegistryTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index 1bfbd3e2cc17c..27c99a7bad6da 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -396,7 +396,7 @@ public void testNextCheckComesAtHotReloadTimeButWithinCheckPeriod() throws Excep * the next check within that second. */ @Test - public void testCheckRightBeforeHotReloadTimeSchedulesCheckAtThatTime() { + public void testCheckRightBeforeHotReloadTimeDoesNotDeferHotReload() { ReloadableSslFactory rest = mock(ReloadableSslFactory.class); AtomicLong hotReloadTime = new AtomicLong(at(DAYS.toHours(30))); From bb16792aaeee8e6cd63b4cc1289b86a0a3ce6d57 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 21:52:25 +0300 Subject: [PATCH 23/53] IGNITE-29212 Find the HTTPS factory inside nested Jetty connection factories A Jetty connector that accepts HTTP and HTTPS on one port keeps its SslConnectionFactory inside a DetectorConnectionFactory. The node looked only at the top-level connection factories, so neither the reload command nor hot reload covered such a connector. It now looks among all components of the connector. Tests: - the reload command applies a replaced key store behind a DetectorConnectionFactory; - the automatic attempt in the HTTP REST registry test succeeds on its own, so the manual reload no longer hides its failure; - the boundary test is deterministic: a later read finds the hot reload time passed; - the chain test has an issuer that is due before a key certificate that expires sooner. Co-Authored-By: Claude Opus 5.5 --- .../ssl/SslFactoryRegistryTest.java | 29 ++++------ .../ssl/SslContextFactoryHotReloadTest.java | 5 +- .../http/jetty/GridJettyRestProtocol.java | 12 ++-- .../http/jetty/JettyRestHttpsReloadTest.java | 26 ++++++++- .../META-INF/jetty/https-detector.xml | 57 +++++++++++++++++++ 5 files changed, 105 insertions(+), 24 deletions(-) create mode 100644 modules/rest-http/src/test/resources/META-INF/jetty/https-detector.xml diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index 27c99a7bad6da..69f2071931b93 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -32,7 +32,6 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; import javax.cache.configuration.Factory; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; @@ -216,24 +215,27 @@ public void testFactoryWithoutReloadDoesNotStartHotReload() { /** * Given: HTTP REST registers a factory that is not an Ignite SSL context factory, with certificates due for hot reload. - * When: the periodic check runs, and then a manual reload runs. - * Then: the registry reloads the factory each time and counts one automatic and one manual attempt. + * When: the periodic check runs and loads certificates that are not due, and then a manual reload runs. + * Then: the automatic attempt succeeds, the registry reloads the factory each time and counts one automatic + * and one manual attempt. */ @Test public void testReloadableFactoryIsHotReloadedAndReloadedManually() { ReloadableSslFactory rest = mock(ReloadableSslFactory.class); - when(rest.getHotReloadTime()).thenReturn(due(), due(), at(DAYS.toHours(30))); + when(rest.getHotReloadTime()).thenReturn(due(), at(DAYS.toHours(30))); registry.register("HTTP REST", rest); registry.onKernalStart(true); runChecks(); + + assertEquals(0, failures()); + reload(rest); verify(rest, times(2)).init(); assertEquals(1, metric("AutomaticHotReloadAttempts")); assertEquals(1, metric("ManualReloadAttempts")); - assertEquals(0, failures()); } /** @@ -389,29 +391,22 @@ public void testNextCheckComesAtHotReloadTimeButWithinCheckPeriod() throws Excep } /** - * Given: the certificates of a factory become due for hot reload a second after the registry starts, and each read - * of their hot reload time takes 600 ms, as it does while a reload outside the registry holds the factory. + * Given: the check reads a hot reload time that comes in 30 minutes, and any later read finds that the time has come, + * as when the clock passes the hot reload time while the check runs. * When: the check at start runs. - * Then: the factory is hot reloaded no later than its hot reload time: the check either reloads it or schedules - * the next check within that second. + * Then: the next check comes in 30 minutes, at the hot reload time that the check read, not after the full hour. */ @Test public void testCheckRightBeforeHotReloadTimeDoesNotDeferHotReload() { ReloadableSslFactory rest = mock(ReloadableSslFactory.class); - AtomicLong hotReloadTime = new AtomicLong(at(DAYS.toHours(30))); - when(rest.getHotReloadTime()).thenAnswer(call -> { - Thread.sleep(600); - - return hotReloadTime.get(); - }); + when(rest.getHotReloadTime()).thenReturn(System.currentTimeMillis() + MINUTES.toMillis(30), due()); registry.register("HTTP REST", rest); registry.onKernalStart(true); - hotReloadTime.set(System.currentTimeMillis() + 1000); runChecks(); - assertTrue(scheduled.toString(), metric("AutomaticHotReloadAttempts") == 1 || nextCheckDelay() <= 1000); + assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); } /** diff --git a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java index a5042cd4aa187..1549071711cbf 100644 --- a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java +++ b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java @@ -109,7 +109,8 @@ public void testHotReloadLeadIsThirdOfLifetimeUpToSevenDays() throws Exception { /** * Given: key stores in which the certificate due first was issued 30 hours ago and expires in 15 hours. - * In one of them, that certificate is the issuer of a key certificate that is due later. + * In one of them, that certificate is the issuer of a key certificate that expires sooner, in 5 hours, but is + * due later, in 3 hours, a third of its 6-hour lifetime before it expires. * Other entries are a chain that is due later, a secret key and a key with a certificate chain that is not X.509. * When: the factory loads each key store. * Then: hot reload is due now, a third of the 45-hour lifetime before that certificate expires. @@ -127,7 +128,7 @@ public void testHotReloadTimeComesFromCertificateDueFirst() throws Exception { new Certificate[] {new OtherCertificate(node.getCertificate("node").getPublicKey())}); assertHotReloadTime(now, node); - assertHotReloadTime(now, shortIssuer.keyStore("node", at(-60), at(100))); + assertHotReloadTime(now, shortIssuer.keyStore("node", at(-1), at(5))); assertHotReloadTime(now, merge(authority.keyStore("first", at(-30), at(15)), authority.keyStore("second", at(-100), at(200)))); assertHotReloadTime(now, merge(authority.keyStore("first", at(-100), at(200)), authority.keyStore("second", at(-30), at(15)))); assertHotReloadTime(now, withUnusableKeys); diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java index 9b2b937c05a50..ca782cfe399d3 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java @@ -169,20 +169,24 @@ else if (log.isDebugEnabled()) int portRange = config().getPortRange(); int lastPort = portRange == 0 ? initPort : initPort + portRange - 1; - SslConnectionFactory tls = connector.getConnectionFactory(SslConnectionFactory.class); - ReloadableJettySslFactory sslFactory = tls == null ? null : new ReloadableJettySslFactory(tls.getSslContextFactory()); + Collection sslFactories = connector.getContainedBeans(SslConnectionFactory.class).stream() + .map(SslConnectionFactory::getSslContextFactory) + .distinct() + .map(ReloadableJettySslFactory::new) + .toList(); for (port = initPort; port <= lastPort; port++) { connector.setPort(port); if (startJetty()) { - if (sslFactory != null) + for (ReloadableJettySslFactory sslFactory : sslFactories) ctx.ssl().register("HTTP REST", sslFactory); if (log.isInfoEnabled()) { log.info(startInfo()); - String proto = tls == null ? "http" : "https"; + boolean isSsl = connector.getConnectionFactory(SslConnectionFactory.class) != null; + String proto = isSsl ? "https" : "http"; log.info("HTTP REST protocol address: " + proto + "://" + host + ":" + port + "/"); } diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index 2220d4b7b1ff4..d26832cf12a30 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -62,7 +62,8 @@ /** * TLS reload of the HTTP REST connector configured in Jetty XML. The standard Jetty factory reads its key store from a file - * and requires an SNI host name ({@code jetty/https.xml}). The custom factory ({@code jetty/https-source.xml}) takes its + * and requires an SNI host name ({@code jetty/https.xml}); {@code jetty/https-detector.xml} reads the same file through + * a connector that accepts HTTP and HTTPS on one port. The custom factory ({@code jetty/https-source.xml}) takes its * key stores from {@link SourceSslContextFactory}. The connectors in these files set no port, so the tests set * {@code IGNITE_JETTY_PORT}; otherwise the node would publish port 0. */ @@ -123,6 +124,29 @@ public void testReloadCommandAppliesReplacementKeyStore() throws Exception { assertEquals(b.getCertificate(HOST), serverCertificate(node)); } + /** + * Given: the Jetty connector accepts HTTP and HTTPS on one port, so its TLS factory sits inside + * a {@code DetectorConnectionFactory}, and HTTPS serves certificate A from a key store file. + * When: the file gets certificate B, and the operator runs the reload command. + * Then: the command reports HTTP REST as reloaded, and a new client sees B. + */ + @Test + @WithSystemProperty(key = KEY_STORE_PATH, value = "") + public void testReloadCommandFindsTlsFactoryInsideDetector() throws Exception { + KeyStore a = fresh(); + KeyStore b = fresh(); + Path keys = keyStoreFile(a); + + IgniteEx node = startGrid(jettyConfig("jetty/https-detector.xml")); + + assertEquals(a.getCertificate(HOST), serverCertificate(node)); + + save(b, keys); + + assertTrue(reload(node).contains(": HTTP REST: reloaded")); + assertEquals(b.getCertificate(HOST), serverCertificate(node)); + } + /** * Given: HTTPS serves certificate A from a key store file of the standard Jetty factory, which selects certificates * by SNI host name. diff --git a/modules/rest-http/src/test/resources/META-INF/jetty/https-detector.xml b/modules/rest-http/src/test/resources/META-INF/jetty/https-detector.xml new file mode 100644 index 0000000000000..19de10aa58c80 --- /dev/null +++ b/modules/rest-http/src/test/resources/META-INF/jetty/https-detector.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + JKS + 123456 + + + http/1.1 + + + + + + + + + + + + + + + From 09f060603375b0ddbffc5bbeafd14cafdd543b5d Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 22:13:27 +0300 Subject: [PATCH 24/53] IGNITE-29212 Drop the redundant Factory from AbstractSslContextFactory ReloadableSslFactory already extends Factory, so the base class still implements it. Co-Authored-By: Claude Opus 5.5 --- .../java/org/apache/ignite/ssl/AbstractSslContextFactory.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java index a5c535646263d..eb9f429d835a1 100644 --- a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java @@ -22,7 +22,6 @@ import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.util.concurrent.atomic.AtomicReference; -import javax.cache.configuration.Factory; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; @@ -38,7 +37,7 @@ * {@link #create()} returns the last one that it loaded, loading one on the first call. The hot reload time comes from * the key store that the factory passes to {@link #createKeyManagers(KeyManagerFactory, KeyStore, char[])}. */ -public abstract class AbstractSslContextFactory implements Factory, ReloadableSslFactory { +public abstract class AbstractSslContextFactory implements ReloadableSslFactory { /** */ private static final long serialVersionUID = 0L; From 7461a26e568d3393c77b735609da222fbd371622 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 22:21:48 +0300 Subject: [PATCH 25/53] IGNITE-29212 Keep the registry's check and reloadIfDue() in their master shape reloadIfDue() keeps its name, place and early return, and now returns the delay of the next check. The failure handling in check() is the one from master: a check that fails during stop schedules nothing, as the stopped executor rejects it. Co-Authored-By: Claude Opus 5.5 --- .../processors/ssl/SslFactoryRegistry.java | 50 +++++++++---------- 1 file changed, 24 insertions(+), 26 deletions(-) diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 282dddcff83d5..83f585642446b 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -176,46 +176,44 @@ private synchronized void check() { if (log.isDebugEnabled()) log.debug("TLS hot reload check started [transports=" + transports + ']'); - long nextCheckDelay; + long nextCheckDelay = CHECK_PERIOD; try { - long hotReloadTime = reloadable.getHotReloadTime(); - - logHotReloadTime(hotReloadTime); - - nextCheckDelay = nextCheckDelay(hotReloadTime); - - if (nextCheckDelay == 0) - nextCheckDelay = hotReload(); - else - failures.set(0); + nextCheckDelay = reloadIfDue(); } catch (Throwable e) { - if (executor.isShutdown()) { - if (log.isDebugEnabled()) - log.debug("TLS hot reload failed during node stop [transports=" + transports + ", err=" + e + ']'); + if (!executor.isShutdown()) { + failures.incrementAndGet(); - return; + log.warning("TLS hot reload failed [transports=" + transports + ", nextAttempt=" + + new Date(System.currentTimeMillis() + CHECK_PERIOD) + ']', e); } - - failures.incrementAndGet(); - - nextCheckDelay = CHECK_PERIOD; - - log.warning("TLS hot reload failed [transports=" + transports + ", nextAttempt=" - + new Date(System.currentTimeMillis() + nextCheckDelay) + ']', e); + else if (log.isDebugEnabled()) + log.debug("TLS hot reload failed during node stop [transports=" + transports + ", err=" + e + ']'); } scheduleCheck(nextCheckDelay); } /** - * Reloads the factory, whose hot reload time has come, and ends the failure streak. + * Reloads the factory if its hot reload time has come, and ends the failure streak if it has not. * * @return Delay of the next check. * @throws IgniteException If the reload fails or leaves certificates that are still due. */ - private long hotReload() { + private long reloadIfDue() { + long hotReloadTime = reloadable.getHotReloadTime(); + + logHotReloadTime(hotReloadTime); + + long nextCheckDelay = nextCheckDelay(hotReloadTime); + + if (nextCheckDelay != 0) { + failures.set(0); + + return nextCheckDelay; + } + automaticHotReloadAttempts.incrementAndGet(); if (log.isInfoEnabled()) @@ -223,8 +221,8 @@ private long hotReload() { reloadable.init(); - long hotReloadTime = reloadable.getHotReloadTime(); - long nextCheckDelay = nextCheckDelay(hotReloadTime); + hotReloadTime = reloadable.getHotReloadTime(); + nextCheckDelay = nextCheckDelay(hotReloadTime); if (nextCheckDelay == 0) { throw new IgniteException("Loaded certificates are still due for hot reload [hotReloadTime=" From 49048a5c6b6c6aa4e729bdeb7eeba6cdfc261f82 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 22:29:50 +0300 Subject: [PATCH 26/53] IGNITE-29212 Keep the SSL factory registry API from master factories() lists the factories with their transports again, and reload(...) on the registry takes the factory, now typed as ReloadableSslFactory. RegisteredFactory stays private. The reload command differs from master only in that type. Co-Authored-By: Claude Opus 5.5 --- .../management/ssl/SslReloadTask.java | 19 ++++--- .../processors/ssl/SslFactoryRegistry.java | 55 ++++++++++--------- .../ssl/SslFactoryRegistryTest.java | 46 ++++++---------- 3 files changed, 56 insertions(+), 64 deletions(-) diff --git a/modules/core/src/main/java/org/apache/ignite/internal/management/ssl/SslReloadTask.java b/modules/core/src/main/java/org/apache/ignite/internal/management/ssl/SslReloadTask.java index 7ab71ce0e185d..a99afb5241b4c 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/management/ssl/SslReloadTask.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/management/ssl/SslReloadTask.java @@ -22,14 +22,17 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.UUID; +import javax.cache.configuration.Factory; +import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.cluster.ClusterTopologyException; import org.apache.ignite.compute.ComputeJob; import org.apache.ignite.compute.ComputeJobResult; import org.apache.ignite.internal.management.api.NoArg; -import org.apache.ignite.internal.processors.ssl.SslFactoryRegistry.RegisteredFactory; +import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; import org.apache.ignite.internal.processors.task.GridInternal; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.visor.VisorJob; @@ -115,7 +118,7 @@ private SslReloadJob(NoArg arg, boolean debug) { /** {@inheritDoc} */ @Override protected String run(NoArg arg) { - List factories = ignite.context().ssl().factories(); + List, String>> factories = ignite.context().ssl().factories(); UUID nodeId = ignite.localNode().id(); String initiator = ""; @@ -133,9 +136,9 @@ private SslReloadJob(NoArg arg, boolean debug) { return report; } - for (RegisteredFactory registered : factories) { - if (!registered.supportsReload()) { - String report = registered.transports() + ": unsupported: " + registered.factory().getClass().getName(); + for (Entry, String> entry : factories) { + if (!(entry.getKey() instanceof ReloadableSslFactory)) { + String report = entry.getValue() + ": unsupported: " + entry.getKey().getClass().getName(); ignite.log().warning("TLS reload: " + nodeId + ": " + report + initiator); @@ -145,11 +148,11 @@ private SslReloadJob(NoArg arg, boolean debug) { List reports = new ArrayList<>(); - for (RegisteredFactory registered : factories) { - String transports = registered.transports(); + for (Entry, String> entry : factories) { + String transports = entry.getValue(); try { - registered.reload(); + ignite.context().ssl().reload((ReloadableSslFactory)entry.getKey()); } catch (Exception e) { ignite.log().warning("TLS reload: " + nodeId + ": " + transports + ": failed" + initiator, e); diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 83f585642446b..02c6bdd567dc0 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -17,8 +17,11 @@ package org.apache.ignite.internal.processors.ssl; +import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Map; +import java.util.Map.Entry; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; @@ -79,9 +82,14 @@ public synchronized void register(String transport, Factory factory) factories.add(new RegisteredFactory(factory, transport)); } - /** @return Registered factories in registration order. */ - public List factories() { - return List.copyOf(factories); + /** @return Registered factories in registration order, each with its transports joined by commas. */ + public List, String>> factories() { + List, String>> res = new ArrayList<>(factories.size()); + + for (RegisteredFactory registered : factories) + res.add(Map.entry(registered.factory, registered.transports)); + + return res; } /** {@inheritDoc} */ @@ -95,7 +103,7 @@ public List factories() { "Number of automatic hot reload attempts."); for (RegisteredFactory registered : factories) { - if (!registered.supportsReload()) + if (registered.reloadable == null) continue; if (executor == null) @@ -121,8 +129,22 @@ private long consecutiveHotReloadFailures() { executor.shutdownNow(); } + /** + * Reloads a registered factory. Waits for its running check, resets its failure count and schedules its next check + * for the loaded certificates. If they are already due, the next check comes after {@link #CHECK_PERIOD}, because + * a hot reload right away would load the same certificates from the source. + * + * @param factory Registered factory to reload. + */ + public void reload(ReloadableSslFactory factory) { + for (RegisteredFactory registered : factories) { + if (registered.factory == factory) + registered.reload(); + } + } + /** Registered factory with its transports and hot reload state. Its checks and manual reload hold its monitor. */ - public class RegisteredFactory { + private class RegisteredFactory { /** */ private final Factory factory; @@ -149,21 +171,6 @@ private RegisteredFactory(Factory factory, String transports) { reloadable = factory instanceof ReloadableSslFactory sslFactory ? sslFactory : null; } - /** @return The factory that the transports registered. */ - public Factory factory() { - return factory; - } - - /** @return Transports that use the factory, joined by commas. */ - public String transports() { - return transports; - } - - /** @return Whether the registry can reload the factory. */ - public boolean supportsReload() { - return reloadable != null; - } - /** * Checks the factory unless the registry has stopped, and schedules its next check. Counts and logs a failed * check and retries it after {@link #CHECK_PERIOD}, so a failure does not stop the checks. A check that fails @@ -267,12 +274,8 @@ private synchronized void scheduleCheck(long delay) { } } - /** - * Reloads a factory that supports reload. Waits for its running check, resets its failure count and schedules - * its next check for the loaded certificates. If they are already due, the next check comes after - * {@link #CHECK_PERIOD}, because a hot reload right away would load the same certificates from the source. - */ - public synchronized void reload() { + /** */ + private synchronized void reload() { manualReloadAttempts.incrementAndGet(); reloadable.init(); diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index 69f2071931b93..f00a0c43d1d30 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -42,7 +42,6 @@ import org.apache.ignite.internal.GridKernalContext; import org.apache.ignite.internal.processors.metric.GridMetricManager; import org.apache.ignite.internal.processors.metric.MetricRegistryImpl; -import org.apache.ignite.internal.processors.ssl.SslFactoryRegistry.RegisteredFactory; import org.apache.ignite.internal.thread.context.OperationContext; import org.apache.ignite.internal.thread.context.OperationContextAttribute; import org.apache.ignite.internal.thread.context.Scope; @@ -188,13 +187,8 @@ public void testFactoriesAreGroupedInRegistrationOrder() { registry.register("client connector", clientConnector); registry.register("discovery", factory); - List> registered = new ArrayList<>(); - - for (RegisteredFactory f : registry.factories()) - registered.add(Map.entry(f.factory(), f.transports())); - - assertEquals(List.of(Map.entry(factory, "communication, discovery"), Map.entry(clientConnector, "client connector")), - registered); + assertEquals(List.of(Map.entry(factory, "communication, discovery"), + Map.entry(clientConnector, "client connector")), registry.factories()); } /** @@ -231,7 +225,7 @@ public void testReloadableFactoryIsHotReloadedAndReloadedManually() { assertEquals(0, failures()); - reload(rest); + registry.reload(rest); verify(rest, times(2)).init(); assertEquals(1, metric("AutomaticHotReloadAttempts")); @@ -282,7 +276,7 @@ public void testManualReloadLoadsOnlyItsFactoryInstance() throws Exception { long prevTime = communication.getHotReloadTime(); writeFreshCertificates(keys); - reload(clientConnector); + registry.reload(clientConnector); assertTrue(clientConnector.getHotReloadTime() > prevTime); assertEquals(prevTime, communication.getHotReloadTime()); @@ -310,7 +304,7 @@ public void testStoreWithoutPrivateKeyIsReportedUntilKeysAreReloaded() throws Ex assertEquals(0, metric("AutomaticHotReloadAttempts")); writeFreshCertificates(keys); - reload(communication); + registry.reload(communication); assertEquals("TLS hot reload due [transports=communication, hotReloadTime=" + new Date(communication.getHotReloadTime()) + ']', logged.get(logged.size() - 1)); @@ -439,7 +433,7 @@ public void testManualReloadSchedulesCheckAtHotReloadTime() throws Exception { registerTransport("communication", communication); registry.onKernalStart(true); writeCertificatesDueIn30Minutes(keys); - reload(communication); + registry.reload(communication); assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); } @@ -456,7 +450,7 @@ public void testManualReloadOfDueCertificatesDefersNextCheck() throws Exception writeDueCertificates(keys); registerTransport("communication", communication); registry.onKernalStart(true); - reload(communication); + registry.reload(communication); assertEquals(0, failures()); assertEquals(HOURS.toMillis(1), nextCheckDelay()); @@ -621,7 +615,7 @@ public void testManualReloadBeforeStartLoadsFactory() throws Exception { long prevTime = communication.getHotReloadTime(); writeFreshCertificates(keys); - reload(communication); + registry.reload(communication); assertTrue(communication.getHotReloadTime() > prevTime); } @@ -638,13 +632,13 @@ public void testManualReloadCountsAppliedAndFailedLoads() throws Exception { writeFreshCertificates(keys); registerTransport("communication", communication); registry.onKernalStart(true); - reload(communication); + registry.reload(communication); assertEquals(1, metric("ManualReloadAttempts")); Files.delete(keys); - assertThrows(IgniteException.class, () -> reload(communication)); + assertThrows(IgniteException.class, () -> registry.reload(communication)); assertEquals(2, metric("ManualReloadAttempts")); assertEquals(0, metric("AutomaticHotReloadAttempts")); } @@ -696,7 +690,7 @@ public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { registry.onKernalStart(true); custom.setKeys(null, null); - reload(custom); + registry.reload(custom); runChecks(); assertEquals(0, custom.getHotReloadTime()); @@ -714,7 +708,7 @@ public void testManualReloadSupportsAbstractFactory() throws Exception { registry.register("client connector", factory); registry.onKernalStart(true); - reload(factory); + registry.reload(factory); verify(factory).init(); } @@ -734,7 +728,7 @@ public void testFailedManualReloadKeepsFailures() throws Exception { Files.delete(keys); runChecks(); - IgniteException err = assertThrows(IgniteException.class, () -> reload(communication)); + IgniteException err = assertThrows(IgniteException.class, () -> registry.reload(communication)); assertTrue(X.hasCause(err, "key store file was not found", SSLException.class)); assertEquals(1, failures()); @@ -768,7 +762,7 @@ public void testManualReloadWaitsForRunningAttempt() throws Exception { }); GridTestThread attempt = new GridTestThread(nextCheck()); - GridTestThread manualReload = new GridTestThread(() -> reload(communication)); + GridTestThread manualReload = new GridTestThread(() -> registry.reload(communication)); attempt.start(); @@ -819,7 +813,7 @@ public void testManualReloadResetsOnlyItsFactoryFailures() throws Exception { assertEquals(1, failures()); writeDueCertificates(keys); - reload(communication); + registry.reload(communication); assertEquals(1, failures()); @@ -828,7 +822,7 @@ public void testManualReloadResetsOnlyItsFactoryFailures() throws Exception { assertEquals(3, failures()); writeFreshCertificates(clientKeys); - reload(clientConnector); + registry.reload(clientConnector); assertEquals(1, failures()); } @@ -989,14 +983,6 @@ private long nextCheckDelay() { return scheduled.values().iterator().next(); } - /** Reloads the registered factory, as the reload command does. */ - private void reload(Factory factory) { - for (RegisteredFactory registered : registry.factories()) { - if (registered.factory() == factory) - registered.reload(); - } - } - /** Loads a file-backed factory before registration, as the TCP transports do during startup. */ private void registerTransport(String transport, SslContextFactory factory) { factory.create(); From 92846f7f5ddd2ac075158ea00044f190766c5276 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Tue, 24 Nov 2026 22:33:16 +0300 Subject: [PATCH 27/53] IGNITE-29212 Drop a repeated docs sentence and keep a test's certificates due The recovery section already says that Ignite keeps the current certificates after a failed load, which covers the HTTP REST endpoint too. testLoadWithoutKeyStoreClearsHotReloadDate starts from due certificates, as its description says. Under the lead of a third of the lifetime, a certificate valid from an hour ago for 10 more hours was no longer due, so the certificate now starts 30 hours ago. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/security/ssl-tls.adoc | 1 - .../ignite/internal/processors/ssl/SslFactoryRegistryTest.java | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index a042f528f028e..23838619f390c 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -242,7 +242,6 @@ To confirm a replacement, open a new TLS connection to each affected endpoint an === Check Failures and Recover If loading the stores or creating the TLS context fails, Ignite keeps the current certificates and retries on the next check, even after they expire. -The HTTP REST endpoint keeps its current keys and trust settings in the same way. Keeping expired certificates does not extend their validity, so new connections may fail until a valid replacement is available. If the replacements appear after hot reload is due, the next retry loads them. diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index f00a0c43d1d30..57d66b6f4220e 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -681,7 +681,7 @@ public void testScheduledReloadUsesCustomFactoryKeyStoreAndPassword() throws Exc public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { SourceSslContextFactory custom = new SourceSslContextFactory(); - custom.setKeys(authority.keyStore("node", at(-1), at(10)), PASSWORD); + custom.setKeys(authority.keyStore("node", at(-30), at(10)), PASSWORD); custom.create(); assertTrue(custom.getHotReloadTime() > 0); From 8cd54e02a0640de39ae73b125281913fbd3ddf3a Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 13:40:44 +0300 Subject: [PATCH 28/53] IGNITE-29212 Keep a switch to disable hot reload of an Ignite SSL factory AbstractSslContextFactory keeps hotReloadEnabled, now true by default, so an operator can still turn hot reload off for a transport. ReloadableSslFactory gets isHotReloadEnabled(), true by default, so the Jetty factory of HTTP REST stays covered. The registry neither schedules checks of a disabled factory at start nor after its manual reload; the reload command still reloads it. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/security/ssl-tls.adoc | 25 +++- .../processors/ssl/ReloadableSslFactory.java | 5 + .../ignite/ssl/AbstractSslContextFactory.java | 16 +++ .../processors/ssl/SslFactoryRegistry.java | 11 +- .../ssl/SslFactoryRegistryTest.java | 120 ++++++++++++++++-- .../ssl/SslContextFactoryHotReloadTest.java | 7 +- 6 files changed, 160 insertions(+), 24 deletions(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index 23838619f390c..d286d862ef081 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -164,7 +164,7 @@ It also reloads the link:restapi#https[HTTP REST endpoint] when its Jetty connec External client applications reload their certificates separately. Follow the trust-first order below even if you do not plan to run the command. -<> is always on, so a node can load a replaced key store by itself within an hour once its current certificates are due. +<> is enabled by default, so a node can load a replaced key store by itself within an hour once its current certificates are due. If a peer does not trust the new certificate yet, its new connections to that node fail. . Back up the key and trust store files before replacing them. @@ -196,11 +196,24 @@ If you configured `trustManagers` directly, the command reuses them instead of r == Automatic Certificate Hot Reload Automatic hot reload lets nodes load replacement certificates without a reload command. -It is always on and needs no configuration. You must supply the replacements: Ignite reads them from the configured source and does not issue certificates. Hot reload covers the same transports as <>, including the HTTP REST endpoint. It does not update external client applications. +=== Disable Hot Reload + +Hot reload is enabled by default. +To disable it for a transport, disable it on the transport's factory before starting the node: + +[source,java] +---- +factory.setHotReloadEnabled(false); +---- + +Changing this setting requires a node restart. +The reload command still reloads the factory. +The HTTP REST endpoint has no such setting: hot reload always covers it. + === Supply Replacements The key store must contain a private key with an X.509 certificate chain. @@ -218,7 +231,7 @@ Ignite loads the replacements automatically when hot reload is due; no reload co === When Hot Reload Runs -At startup, Ignite checks each factory. +At startup, Ignite checks each factory with hot reload enabled. It checks each factory again when its certificates become due, but no later than an hour after the previous check. After a failed attempt, it retries an hour later. All checks run in one thread, so a slow certificate source can delay the checks of other factories. @@ -258,7 +271,7 @@ To recover without waiting for the next retry: . Check the command result and verify a new connection with the replacement certificates. *What happens to automatic hot reload.* -Automatic hot reload continues after manual reload, as described in <>. +If enabled, automatic hot reload continues after manual reload, as described in <>. A failed automatic attempt does not undo the manual reload. *If the command cannot connect.* @@ -303,6 +316,10 @@ Limit request duration in custom sources: a blocked load delays other hot reload |The protocol for secure transport. https://docs.oracle.com/en/java/javase/11/docs/specs/security/standard-names.html#sslcontext-algorithms[Supported algorithms,window=_blank]. |`TLS` +|`hotReloadEnabled` +|Enables automatic certificate hot reload. See <>. +|`true` + |`trustStoreFilePath` |The path to the trust store file. |`N/A` diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index 817bea9985c4f..287468644a131 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -49,6 +49,11 @@ public interface ReloadableSslFactory extends Factory { */ public long getHotReloadTime(); + /** @return Whether the registry reloads the factory before its certificates expire. Manual reload works either way. */ + public default boolean isHotReloadEnabled() { + return true; + } + /** * Calculates the hot reload time that {@link #getHotReloadTime()} describes. * diff --git a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java index eb9f429d835a1..853ac8d201810 100644 --- a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java @@ -56,12 +56,28 @@ public abstract class AbstractSslContextFactory implements ReloadableSslFactory /** Cached instance of an {@link SSLContext}. */ protected final AtomicReference sslCtx = new AtomicReference<>(); + /** */ + private boolean hotReloadEnabled = true; + /** */ private transient volatile long hotReloadTime; /** */ private transient long pendingHotReloadTime; + /** {@inheritDoc} */ + @Override public boolean isHotReloadEnabled() { + return hotReloadEnabled; + } + + /** + * @param enabled Whether automatic certificate hot reload is enabled. It is enabled by default. Changes require + * a node restart. + */ + public void setHotReloadEnabled(boolean enabled) { + hotReloadEnabled = enabled; + } + /** {@inheritDoc} */ @Override public long getHotReloadTime() { return hotReloadTime; diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 02c6bdd567dc0..4d9f2acef0930 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -103,7 +103,7 @@ public List, String>> factories() { "Number of automatic hot reload attempts."); for (RegisteredFactory registered : factories) { - if (registered.reloadable == null) + if (registered.reloadable == null || !registered.reloadable.isHotReloadEnabled()) continue; if (executor == null) @@ -130,9 +130,9 @@ private long consecutiveHotReloadFailures() { } /** - * Reloads a registered factory. Waits for its running check, resets its failure count and schedules its next check - * for the loaded certificates. If they are already due, the next check comes after {@link #CHECK_PERIOD}, because - * a hot reload right away would load the same certificates from the source. + * Reloads a registered factory. For a factory with hot reload enabled, waits for its running check, resets its failure + * count and schedules its next check for the loaded certificates. If they are already due, the next check comes after + * {@link #CHECK_PERIOD}, because a hot reload right away would load the same certificates from the source. * * @param factory Registered factory to reload. */ @@ -280,6 +280,9 @@ private synchronized void reload() { reloadable.init(); + if (!reloadable.isHotReloadEnabled()) + return; + failures.set(0); long hotReloadTime = reloadable.getHotReloadTime(); diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index 57d66b6f4220e..58c84cc6326db 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -40,6 +40,7 @@ import javax.net.ssl.TrustManager; import org.apache.ignite.IgniteException; import org.apache.ignite.internal.GridKernalContext; +import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.processors.metric.GridMetricManager; import org.apache.ignite.internal.processors.metric.MetricRegistryImpl; import org.apache.ignite.internal.thread.context.OperationContext; @@ -75,6 +76,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.RETURNS_DEFAULTS; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; @@ -191,6 +193,24 @@ public void testFactoriesAreGroupedInRegistrationOrder() { Map.entry(clientConnector, "client connector")), registry.factories()); } + /** + * Given: a factory with hot reload disabled and valid certificates. + * When: the registry starts. + * Then: no hot reload thread starts, and the failure metric reads zero. + */ + @Test + public void testDisabledFactoryDoesNotStartHotReload() throws Exception { + SslContextFactory communication = factory(keys); + + writeFreshCertificates(keys); + communication.setHotReloadEnabled(false); + registerTransport("communication", communication); + registry.onKernalStart(true); + + executorFactory.verifyNoInteractions(); + assertEquals(0, failures()); + } + /** * Given: a transport registers a factory that only creates contexts and cannot reload them. * When: the registry starts. @@ -215,7 +235,7 @@ public void testFactoryWithoutReloadDoesNotStartHotReload() { */ @Test public void testReloadableFactoryIsHotReloadedAndReloadedManually() { - ReloadableSslFactory rest = mock(ReloadableSslFactory.class); + ReloadableSslFactory rest = httpRestFactory(); when(rest.getHotReloadTime()).thenReturn(due(), at(DAYS.toHours(30))); @@ -344,7 +364,7 @@ public void testFailedCheckIsRetriedAfterCheckPeriod() throws Exception { */ @Test public void testFailedReadOfHotReloadTimeIsRetriedWithoutFailingStart() throws Exception { - ReloadableSslFactory rest = mock(ReloadableSslFactory.class); + ReloadableSslFactory rest = httpRestFactory(); when(rest.getHotReloadTime()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")); writeCertificatesDueIn30Minutes(keys); @@ -392,7 +412,7 @@ public void testNextCheckComesAtHotReloadTimeButWithinCheckPeriod() throws Excep */ @Test public void testCheckRightBeforeHotReloadTimeDoesNotDeferHotReload() { - ReloadableSslFactory rest = mock(ReloadableSslFactory.class); + ReloadableSslFactory rest = httpRestFactory(); when(rest.getHotReloadTime()).thenReturn(System.currentTimeMillis() + MINUTES.toMillis(30), due()); @@ -468,7 +488,7 @@ public void testHotReloadDoesNotInheritStartupContext() throws Exception { OperationContextAttribute reqId = OperationContextAttribute.newInstance(); CompletableFuture reloadReqId = new CompletableFuture<>(); - loaded(factory, due()); + enableHotReload(factory, due()); doAnswer(call -> { reloadReqId.complete(OperationContext.get(reqId)); @@ -495,7 +515,7 @@ public void testErrorFromOneFactoryDoesNotStopCheck() throws Exception { List logged = captureLog(); SslContextFactory clientConnector = factory(keys); - loaded(factory, due()); + enableHotReload(factory, due()); doThrow(new NoClassDefFoundError("Key store provider")).when(factory).init(); writeDueCertificates(keys); registry.register("communication", factory); @@ -621,15 +641,16 @@ public void testManualReloadBeforeStartLoadsFactory() throws Exception { } /** - * Given: a factory with certificates that are not due for hot reload. + * Given: a factory with hot reload disabled. * When: a manual reload succeeds, and a second one fails because the key store file is deleted. * Then: both count as manual attempts, and none counts as automatic. */ @Test - public void testManualReloadCountsAppliedAndFailedLoads() throws Exception { + public void testManualReloadWithoutHotReloadCountsAppliedAndFailedLoads() throws Exception { SslContextFactory communication = factory(keys); writeFreshCertificates(keys); + communication.setHotReloadEnabled(false); registerTransport("communication", communication); registry.onKernalStart(true); registry.reload(communication); @@ -643,6 +664,28 @@ public void testManualReloadCountsAppliedAndFailedLoads() throws Exception { assertEquals(0, metric("AutomaticHotReloadAttempts")); } + /** + * Given: communication has hot reload disabled and due certificates, and the client connector has hot reload enabled. + * When: communication is reloaded manually, and the scheduled checks run. + * Then: the checks make no automatic attempt, as communication gets no scheduled check. + */ + @Test + public void testManualReloadDoesNotScheduleCheckOfDisabledFactory() throws Exception { + Path clientKeys = dir.resolve("client-keys.jks"); + SslContextFactory communication = factory(keys); + + writeDueCertificates(keys); + writeFreshCertificates(clientKeys); + communication.setHotReloadEnabled(false); + registerTransport("communication", communication); + registerTransport("client connector", factory(clientKeys)); + registry.onKernalStart(true); + registry.reload(communication); + runChecks(); + + assertEquals(0, metric("AutomaticHotReloadAttempts")); + } + /** * Given: a custom factory has loaded a certificate that is due for hot reload. * When: the source supplies a new key store and password and the scheduled check runs. @@ -734,6 +777,47 @@ public void testFailedManualReloadKeepsFailures() throws Exception { assertEquals(1, failures()); } + /** + * Given: communication only reloads manually, and the client connector is due for hot reload. + * When: the scheduled check runs while communication is waiting for its certificate source. + * Then: the client connector loads its replacement before the manual reload finishes. + */ + @Test + public void testManualOnlyFactoryDoesNotDelayHotReload() throws Exception { + SslContextFactory clientConnector = factory(keys); + CountDownLatch manualStarted = new CountDownLatch(1); + CountDownLatch finishManual = new CountDownLatch(1); + + doAnswer(call -> { + manualStarted.countDown(); + finishManual.await(); + + return null; + }).when(factory).init(); + + writeDueCertificates(keys); + registry.register("communication", factory); + registerTransport("client connector", clientConnector); + registry.onKernalStart(true); + + long prevTime = clientConnector.getHotReloadTime(); + + writeFreshCertificates(keys); + + IgniteInternalFuture manual = runAsync(() -> registry.reload(factory)); + + try { + assertTrue(manualStarted.await(TIMEOUT_MS, MILLISECONDS)); + runAsync(nextCheck()).get(TIMEOUT_MS); + + assertTrue(clientConnector.getHotReloadTime() > prevTime); + } + finally { + finishManual.countDown(); + manual.get(TIMEOUT_MS); + } + } + /** * Given: an automatic attempt has started, failed to load a missing key store file, and pauses at its stop check * before it counts the failure. @@ -841,7 +925,7 @@ public void testStopInterruptsActiveAttemptWithoutWaitingForIt() throws Exceptio CountDownLatch attemptInterrupted = new CountDownLatch(1); CountDownLatch allowCompletion = new CountDownLatch(1); - loaded(factory, due()); + enableHotReload(factory, due()); doAnswer(call -> { attemptStarted.countDown(); @@ -882,7 +966,7 @@ public void testStopInterruptsActiveAttemptWithoutWaitingForIt() throws Exceptio public void testAttemptFailingDuringStopIsNotCounted() { List logged = captureLog(true); - loaded(factory, due()); + enableHotReload(factory, due()); doAnswer(call -> { when(executor.isShutdown()).thenReturn(true); @@ -909,8 +993,8 @@ public void testStopDuringCheckSkipsRemainingFactories() { SslContextFactory clientConnector = mock(SslContextFactory.class); AtomicInteger loads = new AtomicInteger(); - loaded(factory, due()); - loaded(clientConnector, due()); + enableHotReload(factory, due()); + enableHotReload(clientConnector, due()); for (SslContextFactory sslFactory : List.of(factory, clientConnector)) { doAnswer(call -> { @@ -1000,15 +1084,25 @@ private long metric(String name) { } /** - * Makes the factory mock look like a factory that has loaded certificates with the given hot reload date. + * Makes the factory mock look like a factory with hot reload enabled and loaded certificates with the given date. + * The mock returns {@code true} from {@code isHotReloadEnabled()} and the date from {@code getHotReloadTime()}. * * @param factory Factory mock. * @param hotReloadTime Hot reload time of the loaded certificates. */ - private static void loaded(SslContextFactory factory, long hotReloadTime) { + private static void enableHotReload(SslContextFactory factory, long hotReloadTime) { + when(factory.isHotReloadEnabled()).thenReturn(true); when(factory.getHotReloadTime()).thenReturn(hotReloadTime); } + /** + * @return Mock of a factory that is not an Ignite SSL context factory, such as the one of HTTP REST. It keeps the + * default methods of {@link ReloadableSslFactory}, so hot reload is enabled for it. + */ + private static ReloadableSslFactory httpRestFactory() { + return mock(ReloadableSslFactory.class, CALLS_REAL_METHODS); + } + /** @return Hot reload time that has already come. */ private static long due() { return System.currentTimeMillis(); diff --git a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java index 1549071711cbf..6b22362e010d0 100644 --- a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java +++ b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java @@ -83,14 +83,15 @@ public void setUp() throws Exception { } /** - * Given: a key store with only a CA certificate. + * Given: a key store with only a CA certificate and the default hot reload setting. * When: the factory loads the store. - * Then: the load succeeds, and the factory has no hot reload date. + * Then: the load succeeds with hot reload enabled and no scheduled reload date. */ @Test - public void testStoreWithOnlyCaCertificateHasNoHotReloadDate() throws Exception { + public void testDefaultSettingsAcceptStoreWithoutPrivateKeys() throws Exception { InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.trustStore()); + assertTrue(factory.isHotReloadEnabled()); assertNotNull(factory.create()); assertEquals(0, factory.getHotReloadTime()); } From 59a786ea0ade8e58e9b47a434e8aa91bd6e67699 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 13:47:48 +0300 Subject: [PATCH 29/53] IGNITE-29212 Word the hot reload lead by the time left before expiry A certificate becomes due when the time left before it expires drops to a third of its lifetime or to 7 days, whichever is shorter. The rule is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/security/ssl-tls.adoc | 2 +- .../ignite/internal/processors/ssl/ReloadableSslFactory.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index d286d862ef081..96933a9d2d6ad 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -236,7 +236,7 @@ It checks each factory again when its certificates become due, but no later than After a failed attempt, it retries an hour later. All checks run in one thread, so a slow certificate source can delay the checks of other factories. -Each certificate in the private key chains, including issuing certificates, becomes due before it expires by a third of its lifetime, but by no more than 7 days. +Each certificate in the private key chains, including issuing certificates, becomes due when the time left before it expires drops to a third of its lifetime or to 7 days, whichever is shorter. For example, a certificate valid for 24 hours is due 8 hours before it expires, and a certificate valid for 90 days is due 7 days before. A factory is due when its first certificate is due. For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded. diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index 287468644a131..6b665140c98ab 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -39,7 +39,8 @@ public interface ReloadableSslFactory extends Factory { /** * The hot reload time comes from the certificate chains of the private keys that new connections use. - * Each certificate in these chains is due before it expires by a third of its lifetime, but by no more than 7 days. + * Each certificate in these chains becomes due when the time left before it expires drops to a third of its lifetime + * or to 7 days, whichever is shorter. * The factory is due when its first certificate is due. Keys without an X.509 certificate chain are ignored, * as TLS cannot use them. * From b25b363fb6a567e6233c618a72f4cbd17cc711a3 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 14:28:34 +0300 Subject: [PATCH 30/53] IGNITE-29212 Keep the fixed hot reload lead time and its setting from master Hot reload becomes due hotReloadBeforeExpiryMs, 7 days by default, before the earliest certificate expiry in the private key chains, as on master. AbstractSslContextFactory keeps getHotReloadBeforeExpiryMs() and setHotReloadBeforeExpiryMs(long), so an operator can shorten the lead time for short-lived certificates. ReloadableSslFactory shares the expiry calculation, and the Jetty factory of HTTP REST always uses 7 days. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/security/ssl-tls.adoc | 17 ++-- .../processors/ssl/ReloadableSslFactory.java | 39 ++++---- .../ignite/ssl/AbstractSslContextFactory.java | 43 +++++++-- .../ssl/SslFactoryRegistryTest.java | 16 ++-- .../ssl/SslContextFactoryHotReloadTest.java | 96 ++++++++++++------- .../http/jetty/ReloadableJettySslFactory.java | 7 +- .../http/jetty/JettyRestHttpsReloadTest.java | 9 +- 7 files changed, 144 insertions(+), 83 deletions(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index 96933a9d2d6ad..2be80d49691c3 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -236,15 +236,16 @@ It checks each factory again when its certificates become due, but no later than After a failed attempt, it retries an hour later. All checks run in one thread, so a slow certificate source can delay the checks of other factories. -Each certificate in the private key chains, including issuing certificates, becomes due when the time left before it expires drops to a third of its lifetime or to 7 days, whichever is shorter. -For example, a certificate valid for 24 hours is due 8 hours before it expires, and a certificate valid for 90 days is due 7 days before. -A factory is due when its first certificate is due. -For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded. +For each factory, hot reload becomes due `hotReloadBeforeExpiryMs` before the earliest certificate expiry in its private key chains. +This includes issuing certificates. The default lead time is 7 days. +For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded, and the lead time is always 7 days. The first check at or after that date attempts a reload, including the startup check. -Supply the replacements before the current certificates are due, so that the next check loads them. +Allow enough time before expiry to supply the replacements and load the stores. +Keep the lead time shorter than the lifetime of the replacement certificates, or they will already be due when loaded. +See link:{javadoc_base_url}/org/apache/ignite/ssl/AbstractSslContextFactory.html#getHotReloadTime()[getHotReloadTime(), window=_blank] for the calculation. If the loaded certificates are still due for hot reload, Ignite records a failed hot reload attempt even though it installed them. -This can happen when the certificates have not changed, only the trust store changed, or the replacements are already due when loaded. +This can happen when the certificates have not changed, only the trust store changed, or the replacements expire within `hotReloadBeforeExpiryMs`. The loaded context remains in use until a later reload replaces it. After a manual reload, Ignite schedules the next check from the loaded certificates. @@ -320,6 +321,10 @@ Limit request duration in custom sources: a blocked load delays other hot reload |Enables automatic certificate hot reload. See <>. |`true` +|`hotReloadBeforeExpiryMs` +|How long before the certificates expire hot reload becomes due, in milliseconds. See <>. +|`604800000` (7 days) + |`trustStoreFilePath` |The path to the trust store file. |`N/A` diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index 6b665140c98ab..27ca8b68b060f 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -26,8 +26,6 @@ import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; -import static java.util.concurrent.TimeUnit.DAYS; - /** SSL context factory that the SSL factory registry can reload on request and before its certificates expire. */ public interface ReloadableSslFactory extends Factory { /** @@ -38,11 +36,9 @@ public interface ReloadableSslFactory extends Factory { public void init(); /** - * The hot reload time comes from the certificate chains of the private keys that new connections use. - * Each certificate in these chains becomes due when the time left before it expires drops to a third of its lifetime - * or to 7 days, whichever is shorter. - * The factory is due when its first certificate is due. Keys without an X.509 certificate chain are ignored, - * as TLS cannot use them. + * The hot reload time comes a lead time of the factory before the earliest expiry among the certificate chains of the + * private keys that new connections use. A chain expires when any certificate in it expires. + * Keys without an X.509 certificate chain are ignored, as TLS cannot use them. * * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the factory gives no private key with * an X.509 certificate chain. @@ -56,21 +52,21 @@ public default boolean isHotReloadEnabled() { } /** - * Calculates the hot reload time that {@link #getHotReloadTime()} describes. - * * @param store Loaded key store. - * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the store has no private key + * @return Earliest certificate expiry in the private key chains, or {@code 0} if the store has no private key * with an X.509 certificate chain. * @throws GeneralSecurityException If the key store cannot be read. */ - public static long hotReloadTime(KeyStore store) throws GeneralSecurityException { + public static long keyChainsExpiry(KeyStore store) throws GeneralSecurityException { long earliest = Long.MAX_VALUE; for (Enumeration aliases = store.aliases(); aliases.hasMoreElements(); ) { String alias = aliases.nextElement(); - if (store.isKeyEntry(alias)) - earliest = Math.min(earliest, chainHotReloadTime(store.getCertificateChain(alias))); + if (!store.isKeyEntry(alias)) + continue; + + earliest = Math.min(earliest, chainExpiry(store.getCertificateChain(alias))); } return earliest == Long.MAX_VALUE ? 0 : earliest; @@ -78,25 +74,22 @@ public static long hotReloadTime(KeyStore store) throws GeneralSecurityException /** * @param chain Certificate chain of a key entry, or {@code null} if the entry has none. - * @return Time when the first certificate in the chain is due, or {@link Long#MAX_VALUE} if there is no chain - * or it holds a certificate other than X.509, as TLS ignores such keys. + * @return Earliest expiry in the chain, or {@link Long#MAX_VALUE} if there is no chain or it holds a certificate other + * than X.509, as TLS ignores such keys. */ - private static long chainHotReloadTime(Certificate[] chain) { - long time = Long.MAX_VALUE; + private static long chainExpiry(Certificate[] chain) { + long expiry = Long.MAX_VALUE; if (chain == null) - return time; + return expiry; for (Certificate cert : chain) { if (!(cert instanceof X509Certificate x509)) return Long.MAX_VALUE; - long notAfter = x509.getNotAfter().getTime(); - long lifetime = notAfter - x509.getNotBefore().getTime(); - - time = Math.min(time, notAfter - Math.min(DAYS.toMillis(7), lifetime / 3)); + expiry = Math.min(expiry, x509.getNotAfter().getTime()); } - return time; + return expiry; } } diff --git a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java index 853ac8d201810..56bb46f7d044a 100644 --- a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java @@ -21,6 +21,7 @@ import java.security.KeyManagementException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; @@ -34,8 +35,9 @@ /** * Base class for SSL context factories that cache their {@link SSLContext}. {@link #init()} loads a new context, and - * {@link #create()} returns the last one that it loaded, loading one on the first call. The hot reload time comes from - * the key store that the factory passes to {@link #createKeyManagers(KeyManagerFactory, KeyStore, char[])}. + * {@link #create()} returns the last one that it loaded, loading one on the first call. The hot reload time comes + * {@link #getHotReloadBeforeExpiryMs()} before the earliest expiry in the key store that the factory passed to + * {@link #createKeyManagers(KeyManagerFactory, KeyStore, char[])} during the last successful load. */ public abstract class AbstractSslContextFactory implements ReloadableSslFactory { /** */ @@ -44,6 +46,9 @@ public abstract class AbstractSslContextFactory implements ReloadableSslFactory /** Default SSL protocol. */ public static final String DFLT_SSL_PROTOCOL = "TLS"; + /** Default lead time for certificate hot reload: 7 days. */ + public static final long DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS = TimeUnit.DAYS.toMillis(7); + /** SSL protocol. */ protected String proto = DFLT_SSL_PROTOCOL; @@ -60,10 +65,13 @@ public abstract class AbstractSslContextFactory implements ReloadableSslFactory private boolean hotReloadEnabled = true; /** */ - private transient volatile long hotReloadTime; + private volatile long hotReloadBeforeExpiryMs = DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; + + /** */ + private transient volatile long earliestExpiry; /** */ - private transient long pendingHotReloadTime; + private transient long pendingExpiry; /** {@inheritDoc} */ @Override public boolean isHotReloadEnabled() { @@ -78,9 +86,28 @@ public void setHotReloadEnabled(boolean enabled) { hotReloadEnabled = enabled; } + /** + * @return How long before the certificates expire hot reload becomes due, in milliseconds. + * Defaults to {@link #DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. + */ + public long getHotReloadBeforeExpiryMs() { + return hotReloadBeforeExpiryMs; + } + + /** + * @param millis How long before the certificates expire hot reload becomes due, in milliseconds. Must be positive. + */ + public void setHotReloadBeforeExpiryMs(long millis) { + A.ensure(millis > 0, "millis > 0"); + + hotReloadBeforeExpiryMs = millis; + } + /** {@inheritDoc} */ @Override public long getHotReloadTime() { - return hotReloadTime; + long expiry = earliestExpiry; + + return expiry == 0 ? 0 : expiry - hotReloadBeforeExpiryMs; } /** @@ -148,7 +175,7 @@ public void setProtocols(String... protocols) { private SSLContext createSslContext() throws SSLException { checkParameters(); - pendingHotReloadTime = 0; + pendingExpiry = 0; KeyManager[] keyMgrs = createKeyManagers(); @@ -171,7 +198,7 @@ private SSLContext createSslContext() throws SSLException { ctx.init(keyMgrs, trustMgrs, null); - hotReloadTime = pendingHotReloadTime; + earliestExpiry = pendingExpiry; return ctx; } @@ -220,7 +247,7 @@ protected final synchronized KeyManager[] createKeyManagers(KeyManagerFactory ke throws GeneralSecurityException { keyMgrFactory.init(store, pwd); - pendingHotReloadTime = ReloadableSslFactory.hotReloadTime(store); + pendingExpiry = ReloadableSslFactory.keyChainsExpiry(store); return keyMgrFactory.getKeyManagers(); } diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index 58c84cc6326db..567884409a42e 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -695,7 +695,7 @@ public void testManualReloadDoesNotScheduleCheckOfDisabledFactory() throws Excep public void testScheduledReloadUsesCustomFactoryKeyStoreAndPassword() throws Exception { SourceSslContextFactory custom = new SourceSslContextFactory(); - custom.setKeys(authority.keyStore("node", at(-30), at(10)), PASSWORD); + custom.setKeys(authority.keyStore("node", at(-1), at(10)), PASSWORD); SSLContext initCtx = custom.create(); @@ -712,7 +712,7 @@ public void testScheduledReloadUsesCustomFactoryKeyStoreAndPassword() throws Exc long expiry = ((X509Certificate)replacement.getCertificate("node")).getNotAfter().getTime(); - assertEquals(expiry - DAYS.toMillis(7), custom.getHotReloadTime()); + assertEquals(expiry - custom.getHotReloadBeforeExpiryMs(), custom.getHotReloadTime()); } /** @@ -724,7 +724,7 @@ public void testScheduledReloadUsesCustomFactoryKeyStoreAndPassword() throws Exc public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { SourceSslContextFactory custom = new SourceSslContextFactory(); - custom.setKeys(authority.keyStore("node", at(-30), at(10)), PASSWORD); + custom.setKeys(authority.keyStore("node", at(-1), at(10)), PASSWORD); custom.create(); assertTrue(custom.getHotReloadTime() > 0); @@ -1127,7 +1127,7 @@ private SslContextFactory factory(Path keyStore, SslContextFactory sslFactory) { } /** - * Writes a key store that is already due for hot reload. + * Writes a key store that is already due for hot reload with the default lead time. * Its certificate expires in 10 hours. */ private void writeDueCertificates(Path keyStore) throws Exception { @@ -1135,13 +1135,13 @@ private void writeDueCertificates(Path keyStore) throws Exception { } /** - * Writes a key store whose certificate became valid 30 minutes ago and expires in an hour, so it is due for hot reload - * in 30 minutes, a third of its lifetime before it expires. + * Writes a key store that is due for hot reload in 30 minutes with the default lead time. + * Its certificate became valid an hour ago and expires in 7 days and 30 minutes. */ private void writeCertificatesDueIn30Minutes(Path keyStore) throws Exception { long now = System.currentTimeMillis(); - save(authority.keyStore("node", now - MINUTES.toMillis(30), now + MINUTES.toMillis(60)), keyStore); + save(authority.keyStore("node", now - HOURS.toMillis(1), now + DAYS.toMillis(7) + MINUTES.toMillis(30)), keyStore); } /** @return Whether the delay ends within the next 30 minutes, but no more than a minute earlier. */ @@ -1150,7 +1150,7 @@ private static boolean isAbout30Minutes(long delay) { } /** - * Writes a key store that is due for hot reload in 23 days. + * Writes a key store that is due for hot reload in 23 days with the default lead time. * Its certificate became valid an hour ago and expires in 30 days. */ private void writeFreshCertificates(Path keyStore) throws Exception { diff --git a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java index 6b22362e010d0..d2b66da4b6f87 100644 --- a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java +++ b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java @@ -43,6 +43,7 @@ import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.apache.ignite.ssl.SslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD; import static org.apache.ignite.ssl.TestCertificateAuthority.merge; import static org.apache.ignite.ssl.TestCertificateAuthority.save; @@ -97,29 +98,55 @@ public void testDefaultSettingsAcceptStoreWithoutPrivateKeys() throws Exception } /** - * Given: a certificate valid for 24 hours and a certificate valid for 90 days, both issued by a CA valid for 2 years. - * When: the factory loads each of them. - * Then: hot reload is due 8 hours, a third of the lifetime, before the first one expires, and 7 days before the - * second one expires, as a third of 90 days exceeds 7 days. + * Given: a factory has loaded a certificate that expires in 10 days. + * When: the application increases the lead time from the default of 7 days to 14 days before starting the node. + * Then: the same certificate is already due for hot reload. */ @Test - public void testHotReloadLeadIsThirdOfLifetimeUpToSevenDays() throws Exception { - assertHotReloadTime(at(4), authority.keyStore("node", at(-12), at(12))); - assertHotReloadTime(at(DAYS.toHours(30 - 7)), authority.keyStore("node", at(-DAYS.toHours(60)), at(DAYS.toHours(30)))); + public void testHotReloadTimeUsesCurrentLeadTime() throws Exception { + Path keys = tmp.newFile("keys.jks").toPath(); + + save(authority.keyStore("node", at(-1), at(DAYS.toHours(10))), keys); + + SslContextFactory factory = new SslContextFactory(); + + factory.setKeyStoreFilePath(keys.toString()); + factory.setKeyStorePassword(PASSWORD); + factory.setTrustManagers(SslContextFactory.getDisabledTrustManager()); + factory.create(); + + assertEquals(at(DAYS.toHours(3)), factory.getHotReloadTime()); + + factory.setHotReloadBeforeExpiryMs(DAYS.toMillis(14)); + + assertEquals(at(-DAYS.toHours(4)), factory.getHotReloadTime()); } /** - * Given: key stores in which the certificate due first was issued 30 hours ago and expires in 15 hours. - * In one of them, that certificate is the issuer of a key certificate that expires sooner, in 5 hours, but is - * due later, in 3 hours, a third of its 6-hour lifetime before it expires. - * Other entries are a chain that is due later, a secret key and a key with a certificate chain that is not X.509. + * Given: a factory with the default lead time. + * When: the application sets a zero or negative lead time. + * Then: the setter rejects it and keeps the default. + */ + @Test + public void testNonPositiveHotReloadBeforeExpiryMsIsRejected() { + SslContextFactory factory = new SslContextFactory(); + + assertThrows(IllegalArgumentException.class, () -> factory.setHotReloadBeforeExpiryMs(0)); + assertThrows(IllegalArgumentException.class, () -> factory.setHotReloadBeforeExpiryMs(-1)); + assertEquals(DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS, factory.getHotReloadBeforeExpiryMs()); + } + + /** + * Given: key stores in which the chain that expires first has 15 hours left. + * In one of them, that chain gets its expiry from an issuer that expires before the key certificate. + * Other entries are a chain that expires later, a secret key and a key with a certificate chain that is not X.509. * When: the factory loads each key store. - * Then: hot reload is due now, a third of the 45-hour lifetime before that certificate expires. + * Then: hot reload is due now, 15 hours before the chain that expires first. */ @Test - public void testHotReloadTimeComesFromCertificateDueFirst() throws Exception { - TestCertificateAuthority shortIssuer = new TestCertificateAuthority("short-issuer", at(-30), at(15)); - KeyStore node = authority.keyStore("node", at(-30), at(15)); + public void testHotReloadTimeComesFromEarliestExpiringChain() throws Exception { + TestCertificateAuthority shortIssuer = new TestCertificateAuthority("short-issuer", now - DAYS.toMillis(365), at(15)); + KeyStore node = authority.keyStore("node", at(-85), at(15)); KeyStore withUnusableKeys = KeyStore.getInstance("JCEKS"); withUnusableKeys.load(null, PASSWORD); @@ -128,11 +155,11 @@ public void testHotReloadTimeComesFromCertificateDueFirst() throws Exception { withUnusableKeys.setKeyEntry("other", node.getKey("node", PASSWORD), PASSWORD, new Certificate[] {new OtherCertificate(node.getCertificate("node").getPublicKey())}); - assertHotReloadTime(now, node); - assertHotReloadTime(now, shortIssuer.keyStore("node", at(-1), at(5))); - assertHotReloadTime(now, merge(authority.keyStore("first", at(-30), at(15)), authority.keyStore("second", at(-100), at(200)))); - assertHotReloadTime(now, merge(authority.keyStore("first", at(-100), at(200)), authority.keyStore("second", at(-30), at(15)))); - assertHotReloadTime(now, withUnusableKeys); + assertHotReloadIsDueNow(node); + assertHotReloadIsDueNow(shortIssuer.keyStore("node", at(-85), at(100))); + assertHotReloadIsDueNow(merge(authority.keyStore("first", at(-85), at(15)), authority.keyStore("second", at(-200), at(100)))); + assertHotReloadIsDueNow(merge(authority.keyStore("first", at(-200), at(100)), authority.keyStore("second", at(-85), at(15)))); + assertHotReloadIsDueNow(withUnusableKeys); } /** @@ -150,10 +177,9 @@ public void testLoadReadsKeyStoreOnce() throws Exception { } /** - * Given: the issuer was valid for 99 hours and expired an hour ago, and the key certificate becomes valid in 99 hours. + * Given: the issuer expired an hour ago, and the key certificate becomes valid in 99 hours. * When: the factory loads the chain for the first time. - * Then: the load succeeds, and hot reload has been due since 33 hours, a third of the issuer's lifetime, before - * the issuer expired. + * Then: the load succeeds, and hot reload has been due since 15 hours before the issuer expired. */ @Test public void testFirstLoadAcceptsChainOutsideValidityPeriod() throws Exception { @@ -162,7 +188,7 @@ public void testFirstLoadAcceptsChainOutsideValidityPeriod() throws Exception { factory.create(); - assertEquals(at(-34), factory.getHotReloadTime()); + assertEquals(at(-16), factory.getHotReloadTime()); } /** @@ -270,14 +296,14 @@ public void testReloadRecoversAfterFailedTrustStoreLoad() throws Exception { save(authority.trustStore(), trust); - InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.keyStore("node", at(-80), at(10))); + InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.keyStore("node", at(-90), at(10))); factory.useTrustStore(trust.toString()); SSLContext ctx = factory.create(); long hotReloadTime = factory.getHotReloadTime(); - factory.keyStore = authority.keyStore("node", at(-1), at(101)); + factory.keyStore = authority.keyStore("node", at(-1), at(99)); Files.delete(trust); IgniteException err = assertThrows(IgniteException.class, factory::init); @@ -290,7 +316,7 @@ public void testReloadRecoversAfterFailedTrustStoreLoad() throws Exception { factory.init(); assertNotSame(ctx, factory.create()); - assertEquals(at(67), factory.getHotReloadTime()); + assertEquals(at(84), factory.getHotReloadTime()); } /** @@ -335,28 +361,28 @@ public void testHotReloadTimeRemainsReadableDuringLoad() throws Exception { } /** - * Creates a factory that has loaded certificates due for hot reload 20 hours ago. - * It reads both stores from memory. The certificates were issued 80 hours ago and expire in 10 hours. + * Creates a factory that has loaded certificates due for hot reload 5 hours ago. + * It reads both stores from memory. The certificates expire in 10 hours. */ private InMemorySslContextFactory dueFactory() throws Exception { - InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.keyStore("node", at(-80), at(10))); + InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.keyStore("node", at(-90), at(10))); factory.trustStore = authority.trustStore(); factory.useTrustStore("memory-trust"); factory.create(); - assertEquals(at(-20), factory.getHotReloadTime()); + assertEquals(at(-5), factory.getHotReloadTime()); return factory; } - /** Checks the hot reload time of a factory that has loaded the given key store. */ - private static void assertHotReloadTime(long expected, KeyStore keys) { + /** */ + private void assertHotReloadIsDueNow(KeyStore keys) { InMemorySslContextFactory factory = new InMemorySslContextFactory(keys); factory.create(); - assertEquals(expected, factory.getHotReloadTime()); + assertEquals(now, factory.getHotReloadTime()); } /** @@ -405,6 +431,7 @@ private long at(long hours) { * A factory that reads its key store from a field instead of a file and counts the reads. * Tests change the field to put new certificates into the source. * By default the factory trusts all peers. Tests can configure a trust store from memory or a file. + * Hot reload is due 15 hours before expiry, so the tests count certificate dates in hours. */ private static class InMemorySslContextFactory extends SslContextFactory { /** */ @@ -426,6 +453,7 @@ private InMemorySslContextFactory(KeyStore keyStore) { setKeyStoreFilePath("memory"); setKeyStorePassword(PASSWORD); setTrustManagers(getDisabledTrustManager()); + setHotReloadBeforeExpiryMs(HOURS.toMillis(15)); } /** Selects the trust store that supplies the factory's trust managers. */ diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index e848e828beb81..082decdc62b54 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -24,11 +24,15 @@ import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; +import org.apache.ignite.ssl.AbstractSslContextFactory; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.jetbrains.annotations.Nullable; +import static org.apache.ignite.ssl.AbstractSslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; + /** * TLS factory of the Jetty HTTPS connector. A failed reload leaves the previous keys and trust settings in use. + * Hot reload comes {@link AbstractSslContextFactory#DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS} before the certificates expire. *

* Jetty's factory guards its TLS state with an internal lock: it loads the state under this lock, and new connections * take the state under it too. Before loading a replacement, Jetty clears the state. So that new connections never see @@ -86,8 +90,9 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { @Override public long getHotReloadTime() { try { KeyStore store = factory.getKeyStore(); + long expiry = store == null ? 0 : ReloadableSslFactory.keyChainsExpiry(store); - return store == null ? 0 : ReloadableSslFactory.hotReloadTime(store); + return expiry == 0 ? 0 : expiry - DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; } catch (IllegalStateException | GeneralSecurityException e) { throw new IgniteException("Failed to read the certificates of the HTTPS connector", e); diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index d26832cf12a30..24c12413f34c5 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -209,7 +209,8 @@ public void testHotReloadedKeysSurviveFailedManualReload() throws Exception { * Given: a custom Jetty factory has loaded certificate A, valid for 30 days. * When: the factory reloads by itself and gets certificate B, which was issued 20 hours ago and expires in an hour. * Then its source fails, and Ignite reloads the factory. - * Then: the hot reload date is 23 days ahead for A and 6 hours ago for B, and the failed reload keeps B's date. + * Then: the hot reload date comes 7 days before the certificate in use expires: 23 days ahead for A, 7 days before + * the expiry of B for B. The failed reload keeps B's date. */ @Test public void testHotReloadTimeFollowsKeysInUse() throws Exception { @@ -225,9 +226,11 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { jettyFactory.reload(f -> { }); - assertEquals(now - HOURS.toMillis(6), factory.getHotReloadTime()); + long dueB = now + HOURS.toMillis(1) - DAYS.toMillis(7); + + assertEquals(dueB, factory.getHotReloadTime()); assertThrows(log, factory::init, IgniteException.class, "Source is unavailable"); - assertEquals(now - HOURS.toMillis(6), factory.getHotReloadTime()); + assertEquals(dueB, factory.getHotReloadTime()); } finally { jettyFactory.stop(); From 688367b1fd1da2258820f6248bbbd3e4677c700e Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 14:39:47 +0300 Subject: [PATCH 31/53] IGNITE-29212 Take the HTTPS hot reload settings from the REST connector's SSL factory The Jetty factory of HTTP REST follows hotReloadEnabled and hotReloadBeforeExpiryMs of the SSL factory that binary REST uses: ConnectorConfiguration.getSslFactory(), or the node's factory if the connector has none. Without such an Ignite factory, hot reload is enabled with the default lead time. The rule that picks the factory moved from GridTcpRestProtocol to GridRestProtocolAdapter, so both REST protocols share it. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/restapi.adoc | 2 + docs/_docs/security/ssl-tls.adoc | 4 +- .../protocols/GridRestProtocolAdapter.java | 9 ++++ .../protocols/tcp/GridTcpRestProtocol.java | 11 +---- .../http/jetty/GridJettyRestProtocol.java | 2 +- .../http/jetty/ReloadableJettySslFactory.java | 25 +++++++++-- .../http/jetty/JettyRestHttpsReloadTest.java | 44 ++++++++++++++++--- 7 files changed, 76 insertions(+), 21 deletions(-) diff --git a/docs/_docs/restapi.adoc b/docs/_docs/restapi.adoc index f85cfd1d8028d..86bda267a3df1 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -111,6 +111,8 @@ Both the standard Jetty factory and custom subclasses of `SslContextFactory.Serv After you replace the stores, run the link:tools/control-script#reloading-tls-certificates[`--ssl reload` command]. The node also reloads the stores automatically before its certificates expire, as described in link:security/ssl-tls#automatic-certificate-hot-reload[Automatic Certificate Hot Reload]. +Hot reload of the endpoint follows the `hotReloadEnabled` and `hotReloadBeforeExpiryMs` settings of the REST connector's SSL factory: the one set by `ConnectorConfiguration.setSslFactory(...)`, or the node's `IgniteConfiguration.setSslContextFactory(...)` if the connector sets none. +If there is no such factory, or it does not extend `AbstractSslContextFactory`, hot reload is enabled with a lead time of 7 days. Each reload asks the Jetty factory to load its stores again. New connections use the replacement certificates; established connections stay open. If loading fails, the endpoint keeps its current keys and trust settings, and new connections keep working with them. diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index 2be80d49691c3..8437d03019174 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -212,7 +212,7 @@ factory.setHotReloadEnabled(false); Changing this setting requires a node restart. The reload command still reloads the factory. -The HTTP REST endpoint has no such setting: hot reload always covers it. +The HTTP REST endpoint follows this setting of the REST connector's SSL factory, as described in link:restapi#https[HTTPS]. === Supply Replacements @@ -238,7 +238,7 @@ All checks run in one thread, so a slow certificate source can delay the checks For each factory, hot reload becomes due `hotReloadBeforeExpiryMs` before the earliest certificate expiry in its private key chains. This includes issuing certificates. The default lead time is 7 days. -For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded, and the lead time is always 7 days. +For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded, and the lead time from the REST connector's SSL factory, as described in link:restapi#https[HTTPS]. The first check at or after that date attempts a reload, including the startup check. Allow enough time before expiry to supply the replacements and load the stores. Keep the lead time shorter than the lifetime of the replacement certificates, or they will already be due when loaded. diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java index 0a639c4b1edc6..0f4d40eb6dd7e 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java @@ -27,6 +27,8 @@ import java.util.Collection; import java.util.Collections; import java.util.StringTokenizer; +import javax.cache.configuration.Factory; +import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.configuration.ConnectorConfiguration; @@ -149,6 +151,13 @@ protected ConnectorConfiguration config() { return ctx.config().getConnectorConfiguration(); } + /** @return SSL context factory that the connector configuration sets, or the node's one if the connector sets none. */ + protected Factory sslContextFactory() { + Factory factory = config().getSslFactory(); + + return factory != null ? factory : ctx.config().getSslContextFactory(); + } + /** {@inheritDoc} */ @Override public Collection> getProperties() { try { diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java index d7e7328adca83..9eb169a41121d 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java @@ -168,7 +168,7 @@ private GridNioFilter[] makeFilters(ConnectorConfiguration cfg) throws SSLExcept if (!cfg.isSslEnabled()) return new GridNioFilter[] { codec }; - Factory sslCtxFactory = sslContextFactory(cfg); + Factory sslCtxFactory = sslContextFactory(); if (sslCtxFactory == null) // Thrown SSL exception instead of IgniteCheckedException for writing correct warning message into log. @@ -187,13 +187,6 @@ private GridNioFilter[] makeFilters(ConnectorConfiguration cfg) throws SSLExcept return new GridNioFilter[] { codec, sslFilter }; } - /** */ - private Factory sslContextFactory(ConnectorConfiguration cfg) { - Factory factory = cfg.getSslFactory(); - - return factory != null ? factory : ctx.config().getSslContextFactory(); - } - /** * Tries to start server with given parameters. * @@ -238,7 +231,7 @@ private boolean startTcpServer(InetAddress hostAddr, int port, GridNioServerList ctx.ports().registerPort(port, IgnitePortProtocol.TCP, getClass()); if (cfg.isSslEnabled()) - ctx.ssl().register("binary REST", sslContextFactory(cfg)); + ctx.ssl().register("binary REST", sslContextFactory()); return true; } diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java index ca782cfe399d3..c1c19b672d8cb 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java @@ -172,7 +172,7 @@ else if (log.isDebugEnabled()) Collection sslFactories = connector.getContainedBeans(SslConnectionFactory.class).stream() .map(SslConnectionFactory::getSslContextFactory) .distinct() - .map(ReloadableJettySslFactory::new) + .map(factory -> new ReloadableJettySslFactory(factory, sslContextFactory())) .toList(); for (port = initPort; port <= lastPort; port++) { diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index 082decdc62b54..a6abc2b877075 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -32,7 +32,10 @@ /** * TLS factory of the Jetty HTTPS connector. A failed reload leaves the previous keys and trust settings in use. - * Hot reload comes {@link AbstractSslContextFactory#DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS} before the certificates expire. + * Hot reload follows {@link AbstractSslContextFactory#isHotReloadEnabled()} and + * {@link AbstractSslContextFactory#getHotReloadBeforeExpiryMs()} of the SSL factory of the REST connector. If that + * factory is not an {@link AbstractSslContextFactory}, hot reload is enabled and comes + * {@link AbstractSslContextFactory#DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS} before the certificates expire. *

* Jetty's factory guards its TLS state with an internal lock: it loads the state under this lock, and new connections * take the state under it too. Before loading a replacement, Jetty clears the state. So that new connections never see @@ -58,13 +61,20 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { /** State set in {@code jetty.xml}. The factory loads a {@code null} part from its configured source. */ private final TlsState configured; - /** @param factory TLS factory of the HTTPS connector before startup, when its getters return the state set in {@code jetty.xml}. */ - ReloadableJettySslFactory(SslContextFactory factory) { + /** SSL factory of the REST connector with the hot reload settings, or {@code null} to use the defaults. */ + @Nullable private final AbstractSslContextFactory hotReloadSettings; + + /** + * @param factory TLS factory of the HTTPS connector before startup, when its getters return the state set in {@code jetty.xml}. + * @param connectorFactory SSL factory of the REST connector. + */ + ReloadableJettySslFactory(SslContextFactory factory, @Nullable Factory connectorFactory) { assert !factory.isStarted(); this.factory = factory; configured = new TlsState(factory); + hotReloadSettings = connectorFactory instanceof AbstractSslContextFactory sslFactory ? sslFactory : null; } /** {@inheritDoc} */ @@ -86,13 +96,20 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { } } + /** {@inheritDoc} */ + @Override public boolean isHotReloadEnabled() { + return hotReloadSettings == null || hotReloadSettings.isHotReloadEnabled(); + } + /** {@inheritDoc} */ @Override public long getHotReloadTime() { try { KeyStore store = factory.getKeyStore(); long expiry = store == null ? 0 : ReloadableSslFactory.keyChainsExpiry(store); - return expiry == 0 ? 0 : expiry - DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; + long lead = hotReloadSettings == null ? DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS : hotReloadSettings.getHotReloadBeforeExpiryMs(); + + return expiry == 0 ? 0 : expiry - lead; } catch (IllegalStateException | GeneralSecurityException e) { throw new IgniteException("Failed to read the certificates of the HTTPS connector", e); diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index 24c12413f34c5..9c3c591d5a25d 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -22,6 +22,7 @@ import java.nio.file.Path; import java.security.KeyStore; import java.security.cert.Certificate; +import java.security.cert.X509Certificate; import java.util.Deque; import java.util.List; import java.util.concurrent.ConcurrentLinkedDeque; @@ -217,7 +218,7 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { SourceSslContextFactory.supply(fresh(), due(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); jettyFactory.start(); @@ -237,6 +238,39 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { } } + /** + * Given: the SSL factory of the REST connector disables hot reload and sets a lead time of an hour, and HTTPS serves + * a certificate that expires in 30 days. + * When: the node starts. + * Then: the HTTPS factory follows both settings: its hot reload is disabled, and its hot reload date comes an hour + * before the certificate expires. + */ + @Test + @WithSystemProperty(key = KEY_STORE_PATH, value = "") + public void testHttpsFollowsHotReloadSettingsOfRestConnectorFactory() throws Exception { + KeyStore keys = fresh(); + org.apache.ignite.ssl.SslContextFactory connectorFactory = new org.apache.ignite.ssl.SslContextFactory(); + + keyStoreFile(keys); + connectorFactory.setHotReloadEnabled(false); + connectorFactory.setHotReloadBeforeExpiryMs(HOURS.toMillis(1)); + + IgniteConfiguration cfg = jettyConfig("jetty/https.xml"); + + cfg.getConnectorConfiguration().setSslFactory(connectorFactory); + + IgniteEx node = startGrid(cfg); + ReloadableSslFactory https = (ReloadableSslFactory)node.context().ssl().factories().stream() + .filter(registered -> "HTTP REST".equals(registered.getValue())) + .findFirst() + .orElseThrow() + .getKey(); + long expiry = ((X509Certificate)keys.getCertificate(HOST)).getNotAfter().getTime(); + + assertFalse(https.isHotReloadEnabled()); + assertEquals(expiry - HOURS.toMillis(1), https.getHotReloadTime()); + } + /** * Given: a custom Jetty factory has loaded its keys, and its source then throws an error instead of an exception. * When: Ignite reloads the factory. @@ -248,7 +282,7 @@ public void testErrorFromSourceKeepsLastWorkingKeys() throws Exception { SourceSslContextFactory.supply(fresh(), new NoClassDefFoundError("Key store provider")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); jettyFactory.start(); @@ -274,7 +308,7 @@ public void testFactoryLeftWithoutKeysFailsWithIgniteException() throws Exceptio SourceSslContextFactory.supply(fresh(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); jettyFactory.start(); @@ -307,7 +341,7 @@ public void testTrustStoreReloadKeepsConfiguredKeysAfterFailure() throws Excepti jettyFactory.setTrustStoreType("JKS"); jettyFactory.setTrustStorePassword(new String(PASSWORD)); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); jettyFactory.start(); @@ -354,7 +388,7 @@ public void testReloadCallsFactoryReloadOnce() throws Exception { jettyFactory.setKeyStore(fresh()); jettyFactory.setKeyStorePassword(new String(PASSWORD)); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); jettyFactory.start(); From 7b24c63a47baf5477b65b01da0f68e0e57d266b5 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 14:42:15 +0300 Subject: [PATCH 32/53] IGNITE-29212 Clarify the hot reload time contract and the Jetty lead time ReloadableSslFactory states the hot reload time as the earliest expiry minus the lead time of the factory. The Jetty adapter reads its lead time in one method next to the enabled flag, and its javadoc covers a REST connector without an SSL factory. Co-Authored-By: Claude Opus 5.5 --- .../processors/ssl/ReloadableSslFactory.java | 4 ++-- .../http/jetty/ReloadableJettySslFactory.java | 15 +++++++++------ 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index 27ca8b68b060f..eeb3f7d3f0e06 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -36,8 +36,8 @@ public interface ReloadableSslFactory extends Factory { public void init(); /** - * The hot reload time comes a lead time of the factory before the earliest expiry among the certificate chains of the - * private keys that new connections use. A chain expires when any certificate in it expires. + * The hot reload time is the earliest expiry among the certificate chains of the private keys that new connections + * use, minus the lead time of the factory. A chain expires when any certificate in it expires. * Keys without an X.509 certificate chain are ignored, as TLS cannot use them. * * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the factory gives no private key with diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index a6abc2b877075..09e50acf8b946 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -33,9 +33,9 @@ /** * TLS factory of the Jetty HTTPS connector. A failed reload leaves the previous keys and trust settings in use. * Hot reload follows {@link AbstractSslContextFactory#isHotReloadEnabled()} and - * {@link AbstractSslContextFactory#getHotReloadBeforeExpiryMs()} of the SSL factory of the REST connector. If that - * factory is not an {@link AbstractSslContextFactory}, hot reload is enabled and comes - * {@link AbstractSslContextFactory#DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS} before the certificates expire. + * {@link AbstractSslContextFactory#getHotReloadBeforeExpiryMs()} of the SSL factory of the REST connector. If there is + * no such factory, or it is not an {@link AbstractSslContextFactory}, hot reload is enabled with the lead time + * {@link AbstractSslContextFactory#DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. *

* Jetty's factory guards its TLS state with an internal lock: it loads the state under this lock, and new connections * take the state under it too. Before loading a replacement, Jetty clears the state. So that new connections never see @@ -107,15 +107,18 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { KeyStore store = factory.getKeyStore(); long expiry = store == null ? 0 : ReloadableSslFactory.keyChainsExpiry(store); - long lead = hotReloadSettings == null ? DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS : hotReloadSettings.getHotReloadBeforeExpiryMs(); - - return expiry == 0 ? 0 : expiry - lead; + return expiry == 0 ? 0 : expiry - hotReloadBeforeExpiryMs(); } catch (IllegalStateException | GeneralSecurityException e) { throw new IgniteException("Failed to read the certificates of the HTTPS connector", e); } } + /** @return How long before the certificates expire hot reload becomes due, in milliseconds. */ + private long hotReloadBeforeExpiryMs() { + return hotReloadSettings == null ? DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS : hotReloadSettings.getHotReloadBeforeExpiryMs(); + } + /** * Reloads the factory and, if loading fails, restores the state that new connections used before. Runs under the * factory lock inside {@code unload(...)}, and always throws {@link SkipUnload}. From 216ff93d857e5027d9224e067e01402186daf6e3 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 15:11:24 +0300 Subject: [PATCH 33/53] IGNITE-29212 Let the reload command bring back HTTPS after a failed KeyStoreScanner reload A failed reload by Jetty's KeyStoreScanner leaves the factory without state. The adapter read that state before reloading, so the command failed before it read the corrected stores, and HTTPS stayed down. Now, if there is no state, the reload has nothing to restore and loads the configured sources. Docs: the REST API page says how to recover after a failed scanner reload, the TLS page says how to set the hot reload properties for an Ignite.NET node and names Ignite factories in the custom source section, and the metrics page link is back to master. Co-Authored-By: Claude Opus 5.5 --- .../_docs/monitoring-metrics/new-metrics.adoc | 2 +- docs/_docs/restapi.adoc | 2 ++ docs/_docs/security/ssl-tls.adoc | 7 +++++- .../http/jetty/ReloadableJettySslFactory.java | 25 +++++++++++++------ .../http/jetty/JettyRestHttpsReloadTest.java | 16 +++++++++--- 5 files changed, 38 insertions(+), 14 deletions(-) diff --git a/docs/_docs/monitoring-metrics/new-metrics.adoc b/docs/_docs/monitoring-metrics/new-metrics.adoc index fcabdbee44356..3d6c6085234db 100644 --- a/docs/_docs/monitoring-metrics/new-metrics.adoc +++ b/docs/_docs/monitoring-metrics/new-metrics.adoc @@ -445,7 +445,7 @@ Register name: `ssl` |AutomaticHotReloadAttempts | long | Number of automatic hot reload attempts. |=== -See link:security/ssl-tls#automatic-certificate-hot-reload[Automatic Certificate Hot Reload] for when it runs and how to recover. +See link:security/ssl-tls#automatic-certificate-hot-reload[Automatic Certificate Hot Reload] for configuration and recovery. == Communication Connection Pool diff --git a/docs/_docs/restapi.adoc b/docs/_docs/restapi.adoc index 86bda267a3df1..245229c605ab1 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -117,6 +117,8 @@ Each reload asks the Jetty factory to load its stores again. New connections use the replacement certificates; established connections stay open. If loading fails, the endpoint keeps its current keys and trust settings, and new connections keep working with them. Correct the stores and run the command again. +A failed reload by Jetty's own `KeyStoreScanner` leaves the endpoint without keys. +Correct the stores and run the command to load them. Keep the stores in the sources that the factory loads: the store paths in the Jetty XML file, or the `loadKeyStore(Resource)` and `loadTrustStore(Resource)` methods of a custom subclass. A store that your code sets on the running factory, for example with `setKeyStore(KeyStore)`, does not survive a failed reload: the next reload loads the stores configured in the Jetty XML file instead. diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index 8437d03019174..f8203e3f1c229 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -214,6 +214,10 @@ Changing this setting requires a node restart. The reload command still reloads the factory. The HTTP REST endpoint follows this setting of the REST connector's SSL factory, as described in link:restapi#https[HTTPS]. +The `SslContextFactory` of Ignite.NET has no `hotReloadEnabled` or `hotReloadBeforeExpiryMs` property. +To set them for a .NET node, define the SSL factory in the Spring XML file set by `IgniteConfiguration.SpringConfigUrl`. +Leave `IgniteConfiguration.SslContextFactory` unset: it replaces the factory from the XML file. + === Supply Replacements The key store must contain a private key with an X.509 certificate chain. @@ -283,10 +287,11 @@ Otherwise, or to load the corrected stores without waiting, restart the affected === Custom Certificate Sources -For automatic hot reload, a custom factory creates its key managers with `createKeyManagers(KeyManagerFactory, KeyStore, char[])` of javadoc:org.apache.ignite.ssl.AbstractSslContextFactory[]. +For automatic hot reload, a custom Ignite factory creates its key managers with `createKeyManagers(KeyManagerFactory, KeyStore, char[])` of javadoc:org.apache.ignite.ssl.AbstractSslContextFactory[]. On each load, call this method once with the key store and the key password that your source returned. Ignite takes the hot reload date from that key store. A factory that does not call this method has no hot reload date, and the node logs a warning. +A custom Jetty factory of the HTTP REST endpoint needs no such call: Ignite takes the date from the key store that the Jetty factory loads, for example in `loadKeyStore(Resource)`. Limit request duration in custom sources: a blocked load delays other hot reloads and manual reload. == SslContextFactory Properties diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index 09e50acf8b946..e023ac78377dd 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -44,7 +44,8 @@ * {@link SslContextFactory#reload(Consumer)}, so the work runs inside {@code unload(...)} and ends with {@link SkipUnload}. * Jetty selects certificates for SNI host names from the key store of the state, so the restore keeps SNI selection. * If the restore fails too, the factory has no state until the next successful reload, and the reload error carries - * that failure as a suppressed exception. + * that failure as a suppressed exception. A failed reload outside Ignite, such as one by Jetty's {@code KeyStoreScanner}, + * can also leave the factory without state. Then the reload has nothing to restore and loads the configured sources. *

* After a failed reload, the factory gets back the context and stores set in {@code jetty.xml}, and the next reload * reads its configured sources again. Once the factory has started, its getters return the loaded state rather than @@ -91,9 +92,6 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { if (skip.loadErr != null) throw new IgniteException(skip.loadErr); } - catch (IllegalStateException e) { - throw new IgniteException("Failed to read the TLS state of the HTTPS connector", e); - } } /** {@inheritDoc} */ @@ -120,17 +118,18 @@ private long hotReloadBeforeExpiryMs() { } /** - * Reloads the factory and, if loading fails, restores the state that new connections used before. Runs under the - * factory lock inside {@code unload(...)}, and always throws {@link SkipUnload}. + * Reloads the factory and, if loading fails, restores the state that new connections used before, if there was one. + * Runs under the factory lock inside {@code unload(...)}, and always throws {@link SkipUnload}. */ private void reloadOrRestore() { - TlsState prev = new TlsState(factory); + TlsState prev = currentState(); try { factory.reload(ignored -> {}); } catch (Throwable e) { - restore(prev, e); + if (prev != null) + restore(prev, e); throw new SkipUnload(e); } @@ -138,6 +137,16 @@ private void reloadOrRestore() { throw new SkipUnload(null); } + /** @return State that new connections use, or {@code null} if a failed reload has left the factory without state. */ + @Nullable private TlsState currentState() { + try { + return new TlsState(factory); + } + catch (IllegalStateException noState) { + return null; + } + } + /** Makes the factory load the previous state, then sets back the state from {@code jetty.xml} for the next reload. */ private void restore(TlsState prev, Throwable loadErr) { try { diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index 9c3c591d5a25d..a5a208c245a50 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -300,11 +300,14 @@ public void testErrorFromSourceKeepsLastWorkingKeys() throws Exception { /** * Given: a reload that Ignite did not start, such as one by Jetty's {@code KeyStoreScanner}, has failed and left * the custom Jetty factory without keys. - * When: Ignite reloads the factory and reads its hot reload time. - * Then: both fail with {@link IgniteException}, as {@link ReloadableSslFactory} declares. + * When: Ignite reloads the factory while the source still fails, and again after the source supplies certificate B. + * Then: the first reload reports the source error, and the hot reload time cannot be read, as no keys are loaded. + * The second reload installs B. */ @Test - public void testFactoryLeftWithoutKeysFailsWithIgniteException() throws Exception { + public void testReloadRecoversFactoryLeftWithoutKeys() throws Exception { + KeyStore b = fresh(); + SourceSslContextFactory.supply(fresh(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); @@ -314,8 +317,13 @@ public void testFactoryLeftWithoutKeysFailsWithIgniteException() throws Exceptio try { assertThrows(log, () -> jettyFactory.reload(f -> { }), Exception.class, "Source is unavailable"); - assertThrows(log, factory::init, IgniteException.class, "TLS state of the HTTPS connector"); + assertThrows(log, factory::init, IgniteException.class, "Source is unavailable"); assertThrows(log, factory::getHotReloadTime, IgniteException.class, "certificates of the HTTPS connector"); + + SourceSslContextFactory.supply(b); + factory.init(); + + assertEquals(b.getCertificate(HOST), jettyFactory.getKeyStore().getCertificate(HOST)); } finally { jettyFactory.stop(); From 7a46ad343095fc8a5687e5e95542ab85467915ed Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 15:20:24 +0300 Subject: [PATCH 34/53] IGNITE-29212 Let hot reload bring back HTTPS after a failed KeyStoreScanner reload A Jetty factory that a failed reload outside Ignite left without state is now due for hot reload right away, instead of failing to report its date. The scheduled check then reloads it as the reload command does, so HTTPS comes back within an hour once the stores are corrected. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/restapi.adoc | 2 +- .../http/jetty/ReloadableJettySslFactory.java | 12 +++++++++--- .../http/jetty/JettyRestHttpsReloadTest.java | 9 ++++++--- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/docs/_docs/restapi.adoc b/docs/_docs/restapi.adoc index 245229c605ab1..ae8367b5e5c37 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -118,7 +118,7 @@ New connections use the replacement certificates; established connections stay o If loading fails, the endpoint keeps its current keys and trust settings, and new connections keep working with them. Correct the stores and run the command again. A failed reload by Jetty's own `KeyStoreScanner` leaves the endpoint without keys. -Correct the stores and run the command to load them. +Correct the stores, then run the command, or wait up to an hour for hot reload if it is enabled. Keep the stores in the sources that the factory loads: the store paths in the Jetty XML file, or the `loadKeyStore(Resource)` and `loadTrustStore(Resource)` methods of a custom subclass. A store that your code sets on the running factory, for example with `setKeyStore(KeyStore)`, does not survive a failed reload: the next reload loads the stores configured in the Jetty XML file instead. diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index e023ac78377dd..613ae2ec0cfe6 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -45,7 +45,8 @@ * Jetty selects certificates for SNI host names from the key store of the state, so the restore keeps SNI selection. * If the restore fails too, the factory has no state until the next successful reload, and the reload error carries * that failure as a suppressed exception. A failed reload outside Ignite, such as one by Jetty's {@code KeyStoreScanner}, - * can also leave the factory without state. Then the reload has nothing to restore and loads the configured sources. + * can also leave the factory without state. Such a factory is due for hot reload right away, and the reload has nothing + * to restore: it loads the configured sources. *

* After a failed reload, the factory gets back the context and stores set in {@code jetty.xml}, and the next reload * reads its configured sources again. Once the factory has started, its getters return the loaded state rather than @@ -101,13 +102,18 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { /** {@inheritDoc} */ @Override public long getHotReloadTime() { + TlsState state = currentState(); + + if (state == null) + return System.currentTimeMillis(); + try { - KeyStore store = factory.getKeyStore(); + KeyStore store = state.keyStore(); long expiry = store == null ? 0 : ReloadableSslFactory.keyChainsExpiry(store); return expiry == 0 ? 0 : expiry - hotReloadBeforeExpiryMs(); } - catch (IllegalStateException | GeneralSecurityException e) { + catch (GeneralSecurityException e) { throw new IgniteException("Failed to read the certificates of the HTTPS connector", e); } } diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index a5a208c245a50..a26db99214dcf 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -301,8 +301,8 @@ public void testErrorFromSourceKeepsLastWorkingKeys() throws Exception { * Given: a reload that Ignite did not start, such as one by Jetty's {@code KeyStoreScanner}, has failed and left * the custom Jetty factory without keys. * When: Ignite reloads the factory while the source still fails, and again after the source supplies certificate B. - * Then: the first reload reports the source error, and the hot reload time cannot be read, as no keys are loaded. - * The second reload installs B. + * Then: the first reload reports the source error, and the factory is due for hot reload right away, so a scheduled + * check reloads it as the reload command does. The second reload installs B. */ @Test public void testReloadRecoversFactoryLeftWithoutKeys() throws Exception { @@ -318,7 +318,10 @@ public void testReloadRecoversFactoryLeftWithoutKeys() throws Exception { try { assertThrows(log, () -> jettyFactory.reload(f -> { }), Exception.class, "Source is unavailable"); assertThrows(log, factory::init, IgniteException.class, "Source is unavailable"); - assertThrows(log, factory::getHotReloadTime, IgniteException.class, "certificates of the HTTPS connector"); + + long hotReloadTime = factory.getHotReloadTime(); + + assertTrue(hotReloadTime > 0 && hotReloadTime <= System.currentTimeMillis()); SourceSslContextFactory.supply(b); factory.init(); From 19c24f8a4c8c651b9d9f41e0e52cdbe34c9c002a Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 15:33:47 +0300 Subject: [PATCH 35/53] IGNITE-29212 State the due time of a factory without keys and the recovery wait The getHotReloadTime() contract says that a factory that has lost the keys of new connections gives a time that has already come. The registry test no longer uses that case as an example of a failed read. The HTTPS page asks to wait for the next hot reload check instead of naming an hour, as one thread serves all checks. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/restapi.adoc | 2 +- .../ignite/internal/processors/ssl/ReloadableSslFactory.java | 4 +++- .../internal/processors/ssl/SslFactoryRegistryTest.java | 3 +-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/_docs/restapi.adoc b/docs/_docs/restapi.adoc index ae8367b5e5c37..4bc17a88e6337 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -118,7 +118,7 @@ New connections use the replacement certificates; established connections stay o If loading fails, the endpoint keeps its current keys and trust settings, and new connections keep working with them. Correct the stores and run the command again. A failed reload by Jetty's own `KeyStoreScanner` leaves the endpoint without keys. -Correct the stores, then run the command, or wait up to an hour for hot reload if it is enabled. +Correct the stores, then run the command or, if hot reload is enabled, wait for its next check, as described in link:security/ssl-tls#when-hot-reload-runs[When Hot Reload Runs]. Keep the stores in the sources that the factory loads: the store paths in the Jetty XML file, or the `loadKeyStore(Resource)` and `loadTrustStore(Resource)` methods of a custom subclass. A store that your code sets on the running factory, for example with `setKeyStore(KeyStore)`, does not survive a failed reload: the next reload loads the stores configured in the Jetty XML file instead. diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index eeb3f7d3f0e06..ab54804826964 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -38,7 +38,9 @@ public interface ReloadableSslFactory extends Factory { /** * The hot reload time is the earliest expiry among the certificate chains of the private keys that new connections * use, minus the lead time of the factory. A chain expires when any certificate in it expires. - * Keys without an X.509 certificate chain are ignored, as TLS cannot use them. + * Keys without an X.509 certificate chain are ignored, as TLS cannot use them. A factory that has lost the keys + * of new connections, for example after a failed reload outside the registry, gives a time that has already come, + * so that the next check reloads it. * * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the factory gives no private key with * an X.509 certificate chain. diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index 567884409a42e..20fa592bbf80f 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -356,8 +356,7 @@ public void testFailedCheckIsRetriedAfterCheckPeriod() throws Exception { } /** - * Given: two factories, and reading the hot reload time of the first one fails, as it does for a Jetty factory that - * a failed reload outside the registry has left without keys. + * Given: two factories, and reading the hot reload time of the first one fails. * When: the registry starts and its checks run. * Then: the start completes, the check of the first factory fails and is retried in an hour, and the second factory * gets its next check at its hot reload time. From bd236348572a8b70c41474cf32f4805734d20a3e Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 16:03:53 +0300 Subject: [PATCH 36/53] IGNITE-29212 Name the internal hot reload time getter without a prefix Only the product reads the hot reload time, so getHotReloadTime() becomes hotReloadTime(), as internal methods have no get prefix. The properties that Spring XML sets keep their getter and setter pairs: isHotReloadEnabled()/setHotReloadEnabled() and getHotReloadBeforeExpiryMs()/setHotReloadBeforeExpiryMs(), and the product reads them through the same getters. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/security/ssl-tls.adoc | 2 +- .../processors/ssl/ReloadableSslFactory.java | 2 +- .../ignite/ssl/AbstractSslContextFactory.java | 2 +- .../processors/ssl/SslFactoryRegistry.java | 6 +-- .../ssl/SslFactoryRegistryTest.java | 42 +++++++++---------- .../ssl/SslCertificateHotReloadTest.java | 2 +- .../ssl/SslContextFactoryHotReloadTest.java | 26 ++++++------ .../http/jetty/ReloadableJettySslFactory.java | 2 +- .../http/jetty/JettyRestHttpsReloadTest.java | 10 ++--- 9 files changed, 47 insertions(+), 47 deletions(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index f8203e3f1c229..3d9798244970a 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -246,7 +246,7 @@ For the HTTP REST endpoint, Ignite takes the certificates from the key store tha The first check at or after that date attempts a reload, including the startup check. Allow enough time before expiry to supply the replacements and load the stores. Keep the lead time shorter than the lifetime of the replacement certificates, or they will already be due when loaded. -See link:{javadoc_base_url}/org/apache/ignite/ssl/AbstractSslContextFactory.html#getHotReloadTime()[getHotReloadTime(), window=_blank] for the calculation. +See link:{javadoc_base_url}/org/apache/ignite/ssl/AbstractSslContextFactory.html#hotReloadTime()[hotReloadTime(), window=_blank] for the calculation. If the loaded certificates are still due for hot reload, Ignite records a failed hot reload attempt even though it installed them. This can happen when the certificates have not changed, only the trust store changed, or the replacements expire within `hotReloadBeforeExpiryMs`. diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index ab54804826964..9ce105898653e 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -46,7 +46,7 @@ public interface ReloadableSslFactory extends Factory { * an X.509 certificate chain. * @throws IgniteException If the factory cannot give the certificates that new connections use. */ - public long getHotReloadTime(); + public long hotReloadTime(); /** @return Whether the registry reloads the factory before its certificates expire. Manual reload works either way. */ public default boolean isHotReloadEnabled() { diff --git a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java index 56bb46f7d044a..48bd22d9caf0e 100644 --- a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java @@ -104,7 +104,7 @@ public void setHotReloadBeforeExpiryMs(long millis) { } /** {@inheritDoc} */ - @Override public long getHotReloadTime() { + @Override public long hotReloadTime() { long expiry = earliestExpiry; return expiry == 0 ? 0 : expiry - hotReloadBeforeExpiryMs; diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 4d9f2acef0930..77bc5e854370b 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -209,7 +209,7 @@ else if (log.isDebugEnabled()) * @throws IgniteException If the reload fails or leaves certificates that are still due. */ private long reloadIfDue() { - long hotReloadTime = reloadable.getHotReloadTime(); + long hotReloadTime = reloadable.hotReloadTime(); logHotReloadTime(hotReloadTime); @@ -228,7 +228,7 @@ private long reloadIfDue() { reloadable.init(); - hotReloadTime = reloadable.getHotReloadTime(); + hotReloadTime = reloadable.hotReloadTime(); nextCheckDelay = nextCheckDelay(hotReloadTime); if (nextCheckDelay == 0) { @@ -285,7 +285,7 @@ private synchronized void reload() { failures.set(0); - long hotReloadTime = reloadable.getHotReloadTime(); + long hotReloadTime = reloadable.hotReloadTime(); logHotReloadTime(hotReloadTime); diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index 20fa592bbf80f..90f6bd38fbc3a 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -237,7 +237,7 @@ public void testFactoryWithoutReloadDoesNotStartHotReload() { public void testReloadableFactoryIsHotReloadedAndReloadedManually() { ReloadableSslFactory rest = httpRestFactory(); - when(rest.getHotReloadTime()).thenReturn(due(), at(DAYS.toHours(30))); + when(rest.hotReloadTime()).thenReturn(due(), at(DAYS.toHours(30))); registry.register("HTTP REST", rest); registry.onKernalStart(true); @@ -268,14 +268,14 @@ public void testEachFactoryInstanceReloadsOnce() throws Exception { registerTransport("client connector", clientConnector); registry.onKernalStart(true); - long prevTime = communication.getHotReloadTime(); + long prevTime = communication.hotReloadTime(); writeFreshCertificates(keys); runChecks(); assertEquals(2, metric("AutomaticHotReloadAttempts")); - assertTrue(communication.getHotReloadTime() > prevTime); - assertEquals(communication.getHotReloadTime(), clientConnector.getHotReloadTime()); + assertTrue(communication.hotReloadTime() > prevTime); + assertEquals(communication.hotReloadTime(), clientConnector.hotReloadTime()); } /** @@ -293,13 +293,13 @@ public void testManualReloadLoadsOnlyItsFactoryInstance() throws Exception { registerTransport("client connector", clientConnector); registry.onKernalStart(true); - long prevTime = communication.getHotReloadTime(); + long prevTime = communication.hotReloadTime(); writeFreshCertificates(keys); registry.reload(clientConnector); - assertTrue(clientConnector.getHotReloadTime() > prevTime); - assertEquals(prevTime, communication.getHotReloadTime()); + assertTrue(clientConnector.hotReloadTime() > prevTime); + assertEquals(prevTime, communication.hotReloadTime()); } /** @@ -326,7 +326,7 @@ public void testStoreWithoutPrivateKeyIsReportedUntilKeysAreReloaded() throws Ex writeFreshCertificates(keys); registry.reload(communication); - assertEquals("TLS hot reload due [transports=communication, hotReloadTime=" + new Date(communication.getHotReloadTime()) + ']', + assertEquals("TLS hot reload due [transports=communication, hotReloadTime=" + new Date(communication.hotReloadTime()) + ']', logged.get(logged.size() - 1)); } @@ -365,7 +365,7 @@ public void testFailedCheckIsRetriedAfterCheckPeriod() throws Exception { public void testFailedReadOfHotReloadTimeIsRetriedWithoutFailingStart() throws Exception { ReloadableSslFactory rest = httpRestFactory(); - when(rest.getHotReloadTime()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")); + when(rest.hotReloadTime()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")); writeCertificatesDueIn30Minutes(keys); registry.register("HTTP REST", rest); registerTransport("communication", factory(keys)); @@ -413,7 +413,7 @@ public void testNextCheckComesAtHotReloadTimeButWithinCheckPeriod() throws Excep public void testCheckRightBeforeHotReloadTimeDoesNotDeferHotReload() { ReloadableSslFactory rest = httpRestFactory(); - when(rest.getHotReloadTime()).thenReturn(System.currentTimeMillis() + MINUTES.toMillis(30), due()); + when(rest.hotReloadTime()).thenReturn(System.currentTimeMillis() + MINUTES.toMillis(30), due()); registry.register("HTTP REST", rest); registry.onKernalStart(true); @@ -543,7 +543,7 @@ public void testLogShowsDueTimeStartAndResultOfAttempts() throws Exception { registerTransport("communication", communication); registry.onKernalStart(true); - long due = communication.getHotReloadTime(); + long due = communication.hotReloadTime(); Files.delete(keys); runChecks(); @@ -561,7 +561,7 @@ public void testLogShowsDueTimeStartAndResultOfAttempts() throws Exception { assertEquals(List.of("due", "started", "failed", "started", "succeeded", "due"), evts); assertTrue(logged.get(0), logged.get(0).endsWith("hotReloadTime=" + new Date(due) + ']')); assertTrue(logged.get(2), logged.get(2).contains("nextAttempt=")); - assertTrue(logged.get(5), logged.get(5).endsWith("hotReloadTime=" + new Date(communication.getHotReloadTime()) + ']')); + assertTrue(logged.get(5), logged.get(5).endsWith("hotReloadTime=" + new Date(communication.hotReloadTime()) + ']')); } /** @@ -631,12 +631,12 @@ public void testManualReloadBeforeStartLoadsFactory() throws Exception { writeDueCertificates(keys); registerTransport("communication", communication); - long prevTime = communication.getHotReloadTime(); + long prevTime = communication.hotReloadTime(); writeFreshCertificates(keys); registry.reload(communication); - assertTrue(communication.getHotReloadTime() > prevTime); + assertTrue(communication.hotReloadTime() > prevTime); } /** @@ -711,7 +711,7 @@ public void testScheduledReloadUsesCustomFactoryKeyStoreAndPassword() throws Exc long expiry = ((X509Certificate)replacement.getCertificate("node")).getNotAfter().getTime(); - assertEquals(expiry - custom.getHotReloadBeforeExpiryMs(), custom.getHotReloadTime()); + assertEquals(expiry - custom.getHotReloadBeforeExpiryMs(), custom.hotReloadTime()); } /** @@ -726,7 +726,7 @@ public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { custom.setKeys(authority.keyStore("node", at(-1), at(10)), PASSWORD); custom.create(); - assertTrue(custom.getHotReloadTime() > 0); + assertTrue(custom.hotReloadTime() > 0); registry.register("communication", custom); registry.onKernalStart(true); @@ -735,7 +735,7 @@ public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { registry.reload(custom); runChecks(); - assertEquals(0, custom.getHotReloadTime()); + assertEquals(0, custom.hotReloadTime()); assertEquals(0, metric("AutomaticHotReloadAttempts")); } @@ -799,7 +799,7 @@ public void testManualOnlyFactoryDoesNotDelayHotReload() throws Exception { registerTransport("client connector", clientConnector); registry.onKernalStart(true); - long prevTime = clientConnector.getHotReloadTime(); + long prevTime = clientConnector.hotReloadTime(); writeFreshCertificates(keys); @@ -809,7 +809,7 @@ public void testManualOnlyFactoryDoesNotDelayHotReload() throws Exception { assertTrue(manualStarted.await(TIMEOUT_MS, MILLISECONDS)); runAsync(nextCheck()).get(TIMEOUT_MS); - assertTrue(clientConnector.getHotReloadTime() > prevTime); + assertTrue(clientConnector.hotReloadTime() > prevTime); } finally { finishManual.countDown(); @@ -1084,14 +1084,14 @@ private long metric(String name) { /** * Makes the factory mock look like a factory with hot reload enabled and loaded certificates with the given date. - * The mock returns {@code true} from {@code isHotReloadEnabled()} and the date from {@code getHotReloadTime()}. + * The mock returns {@code true} from {@code isHotReloadEnabled()} and the date from {@code hotReloadTime()}. * * @param factory Factory mock. * @param hotReloadTime Hot reload time of the loaded certificates. */ private static void enableHotReload(SslContextFactory factory, long hotReloadTime) { when(factory.isHotReloadEnabled()).thenReturn(true); - when(factory.getHotReloadTime()).thenReturn(hotReloadTime); + when(factory.hotReloadTime()).thenReturn(hotReloadTime); } /** diff --git a/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java b/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java index 458c0965f46a9..7c93e451113a4 100644 --- a/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java +++ b/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java @@ -68,7 +68,7 @@ public void testNodeHotReloadsCertificatesForNewConnections() throws Exception { SSLContext initCtx = serverFactory.create(); - assertTrue("Hot reload must be due at startup", serverFactory.getHotReloadTime() < now); + assertTrue("Hot reload must be due at startup", serverFactory.hotReloadTime() < now); save(ca2.keyStore("node", now - MINUTES.toMillis(1), now + DAYS.toMillis(10)), keys); save(ca2.trustStore(), trust); diff --git a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java index d2b66da4b6f87..503ebf6d79948 100644 --- a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java +++ b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java @@ -94,7 +94,7 @@ public void testDefaultSettingsAcceptStoreWithoutPrivateKeys() throws Exception assertTrue(factory.isHotReloadEnabled()); assertNotNull(factory.create()); - assertEquals(0, factory.getHotReloadTime()); + assertEquals(0, factory.hotReloadTime()); } /** @@ -115,11 +115,11 @@ public void testHotReloadTimeUsesCurrentLeadTime() throws Exception { factory.setTrustManagers(SslContextFactory.getDisabledTrustManager()); factory.create(); - assertEquals(at(DAYS.toHours(3)), factory.getHotReloadTime()); + assertEquals(at(DAYS.toHours(3)), factory.hotReloadTime()); factory.setHotReloadBeforeExpiryMs(DAYS.toMillis(14)); - assertEquals(at(-DAYS.toHours(4)), factory.getHotReloadTime()); + assertEquals(at(-DAYS.toHours(4)), factory.hotReloadTime()); } /** @@ -188,7 +188,7 @@ public void testFirstLoadAcceptsChainOutsideValidityPeriod() throws Exception { factory.create(); - assertEquals(at(-16), factory.getHotReloadTime()); + assertEquals(at(-16), factory.hotReloadTime()); } /** @@ -206,7 +206,7 @@ public void testStoreWithoutPrivateKeyLoadsWithoutHotReloadDate() throws Excepti InMemorySslContextFactory factory = new InMemorySslContextFactory(store); assertNotNull(factory.create()); - assertEquals(0, factory.getHotReloadTime()); + assertEquals(0, factory.hotReloadTime()); } /** @@ -301,7 +301,7 @@ public void testReloadRecoversAfterFailedTrustStoreLoad() throws Exception { factory.useTrustStore(trust.toString()); SSLContext ctx = factory.create(); - long hotReloadTime = factory.getHotReloadTime(); + long hotReloadTime = factory.hotReloadTime(); factory.keyStore = authority.keyStore("node", at(-1), at(99)); Files.delete(trust); @@ -310,24 +310,24 @@ public void testReloadRecoversAfterFailedTrustStoreLoad() throws Exception { assertTrue(err.getCause().getMessage(), err.getCause().getMessage().contains("key store file was not found")); assertSame(ctx, factory.create()); - assertEquals(hotReloadTime, factory.getHotReloadTime()); + assertEquals(hotReloadTime, factory.hotReloadTime()); save(authority.trustStore(), trust); factory.init(); assertNotSame(ctx, factory.create()); - assertEquals(at(84), factory.getHotReloadTime()); + assertEquals(at(84), factory.hotReloadTime()); } /** * Given: a reload of certificates with a new date blocks on the trust store load. - * When: another thread reads {@link SslContextFactory#getHotReloadTime()} during the reload. + * When: another thread reads {@link SslContextFactory#hotReloadTime()} during the reload. * Then: the read returns the current date without waiting for the reload. */ @Test public void testHotReloadTimeRemainsReadableDuringLoad() throws Exception { InMemorySslContextFactory factory = spy(dueFactory()); - long hotReloadTime = factory.getHotReloadTime(); + long hotReloadTime = factory.hotReloadTime(); factory.keyStore = authority.keyStore("node", at(-1), at(99)); @@ -349,7 +349,7 @@ public void testHotReloadTimeRemainsReadableDuringLoad() throws Exception { try { assertTrue(trustLoadStarted.await(TIMEOUT_MS, MILLISECONDS)); - assertEquals(hotReloadTime, factory.getHotReloadTime()); + assertEquals(hotReloadTime, factory.hotReloadTime()); } finally { finishTrustLoad.countDown(); @@ -371,7 +371,7 @@ private InMemorySslContextFactory dueFactory() throws Exception { factory.useTrustStore("memory-trust"); factory.create(); - assertEquals(at(-5), factory.getHotReloadTime()); + assertEquals(at(-5), factory.hotReloadTime()); return factory; } @@ -382,7 +382,7 @@ private void assertHotReloadIsDueNow(KeyStore keys) { factory.create(); - assertEquals(now, factory.getHotReloadTime()); + assertEquals(now, factory.hotReloadTime()); } /** diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index 613ae2ec0cfe6..ba1ceb55da25e 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -101,7 +101,7 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { } /** {@inheritDoc} */ - @Override public long getHotReloadTime() { + @Override public long hotReloadTime() { TlsState state = currentState(); if (state == null) diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index a26db99214dcf..929d72ea9334a 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -223,15 +223,15 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { jettyFactory.start(); try { - assertEquals(now + DAYS.toMillis(23), factory.getHotReloadTime()); + assertEquals(now + DAYS.toMillis(23), factory.hotReloadTime()); jettyFactory.reload(f -> { }); long dueB = now + HOURS.toMillis(1) - DAYS.toMillis(7); - assertEquals(dueB, factory.getHotReloadTime()); + assertEquals(dueB, factory.hotReloadTime()); assertThrows(log, factory::init, IgniteException.class, "Source is unavailable"); - assertEquals(dueB, factory.getHotReloadTime()); + assertEquals(dueB, factory.hotReloadTime()); } finally { jettyFactory.stop(); @@ -268,7 +268,7 @@ public void testHttpsFollowsHotReloadSettingsOfRestConnectorFactory() throws Exc long expiry = ((X509Certificate)keys.getCertificate(HOST)).getNotAfter().getTime(); assertFalse(https.isHotReloadEnabled()); - assertEquals(expiry - HOURS.toMillis(1), https.getHotReloadTime()); + assertEquals(expiry - HOURS.toMillis(1), https.hotReloadTime()); } /** @@ -319,7 +319,7 @@ public void testReloadRecoversFactoryLeftWithoutKeys() throws Exception { assertThrows(log, () -> jettyFactory.reload(f -> { }), Exception.class, "Source is unavailable"); assertThrows(log, factory::init, IgniteException.class, "Source is unavailable"); - long hotReloadTime = factory.getHotReloadTime(); + long hotReloadTime = factory.hotReloadTime(); assertTrue(hotReloadTime > 0 && hotReloadTime <= System.currentTimeMillis()); From 6713f83a1baef6776a2b7be770ef2718e929f31f Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 16:26:11 +0300 Subject: [PATCH 37/53] IGNITE-29212 Move the hot reload settings to IgniteConfiguration Hot reload is a node setting now: IgniteConfiguration.setSslHotReloadEnabled(boolean), enabled by default, and setSslHotReloadBeforeExpiry(long), 7 days by default. They apply to every transport, HTTP REST included, so the Jetty factory no longer takes them from the REST connector's SSL factory, and the REST factory rule is back in GridTcpRestProtocol as on master. Factories report only the certificates expiry through ReloadableSslFactory, and the registry subtracts the lead time. AbstractSslContextFactory loses its unreleased hot reload properties. Ignite.NET does not expose the new properties yet: the parity test lists them as missing, and the docs point .NET users to Spring XML. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/restapi.adoc | 2 - docs/_docs/security/ssl-tls.adoc | 32 +-- .../processors/ssl/ReloadableSslFactory.java | 18 +- .../ignite/ssl/AbstractSslContextFactory.java | 52 +---- .../configuration/IgniteConfiguration.java | 62 ++++++ .../protocols/GridRestProtocolAdapter.java | 9 - .../protocols/tcp/GridTcpRestProtocol.java | 11 +- .../processors/ssl/SslFactoryRegistry.java | 26 ++- .../ssl/SslFactoryRegistryTest.java | 188 ++++++++---------- .../ssl/SslCertificateHotReloadTest.java | 80 +++++++- .../ssl/SslContextFactoryHotReloadTest.java | 99 +++------ .../IgniteConfigurationParityTest.cs | 4 +- .../http/jetty/GridJettyRestProtocol.java | 2 +- .../http/jetty/ReloadableJettySslFactory.java | 37 +--- .../http/jetty/JettyRestHttpsReloadTest.java | 64 ++---- 15 files changed, 323 insertions(+), 363 deletions(-) diff --git a/docs/_docs/restapi.adoc b/docs/_docs/restapi.adoc index 4bc17a88e6337..be0dda69a1434 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -111,8 +111,6 @@ Both the standard Jetty factory and custom subclasses of `SslContextFactory.Serv After you replace the stores, run the link:tools/control-script#reloading-tls-certificates[`--ssl reload` command]. The node also reloads the stores automatically before its certificates expire, as described in link:security/ssl-tls#automatic-certificate-hot-reload[Automatic Certificate Hot Reload]. -Hot reload of the endpoint follows the `hotReloadEnabled` and `hotReloadBeforeExpiryMs` settings of the REST connector's SSL factory: the one set by `ConnectorConfiguration.setSslFactory(...)`, or the node's `IgniteConfiguration.setSslContextFactory(...)` if the connector sets none. -If there is no such factory, or it does not extend `AbstractSslContextFactory`, hot reload is enabled with a lead time of 7 days. Each reload asks the Jetty factory to load its stores again. New connections use the replacement certificates; established connections stay open. If loading fails, the endpoint keeps its current keys and trust settings, and new connections keep working with them. diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index 3d9798244970a..7b9bcbb4bb5f3 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -202,21 +202,19 @@ It does not update external client applications. === Disable Hot Reload -Hot reload is enabled by default. -To disable it for a transport, disable it on the transport's factory before starting the node: +Hot reload is enabled by default for all transports of a node. +To disable it, set `sslHotReloadEnabled` to `false` in the node configuration before starting the node: [source,java] ---- -factory.setHotReloadEnabled(false); +igniteCfg.setSslHotReloadEnabled(false); ---- Changing this setting requires a node restart. -The reload command still reloads the factory. -The HTTP REST endpoint follows this setting of the REST connector's SSL factory, as described in link:restapi#https[HTTPS]. +The reload command still reloads the factories. -The `SslContextFactory` of Ignite.NET has no `hotReloadEnabled` or `hotReloadBeforeExpiryMs` property. -To set them for a .NET node, define the SSL factory in the Spring XML file set by `IgniteConfiguration.SpringConfigUrl`. -Leave `IgniteConfiguration.SslContextFactory` unset: it replaces the factory from the XML file. +The `IgniteConfiguration` of Ignite.NET has no properties for hot reload. +To set `sslHotReloadEnabled` or `sslHotReloadBeforeExpiry` for a .NET node, use the Spring XML file set by `IgniteConfiguration.SpringConfigUrl`. === Supply Replacements @@ -235,21 +233,21 @@ Ignite loads the replacements automatically when hot reload is due; no reload co === When Hot Reload Runs -At startup, Ignite checks each factory with hot reload enabled. +At startup, Ignite checks each factory. It checks each factory again when its certificates become due, but no later than an hour after the previous check. After a failed attempt, it retries an hour later. All checks run in one thread, so a slow certificate source can delay the checks of other factories. -For each factory, hot reload becomes due `hotReloadBeforeExpiryMs` before the earliest certificate expiry in its private key chains. +For each factory, hot reload becomes due `sslHotReloadBeforeExpiry` of the node configuration before the earliest certificate expiry in its private key chains. This includes issuing certificates. The default lead time is 7 days. -For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded, and the lead time from the REST connector's SSL factory, as described in link:restapi#https[HTTPS]. +For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded. The first check at or after that date attempts a reload, including the startup check. Allow enough time before expiry to supply the replacements and load the stores. Keep the lead time shorter than the lifetime of the replacement certificates, or they will already be due when loaded. -See link:{javadoc_base_url}/org/apache/ignite/ssl/AbstractSslContextFactory.html#hotReloadTime()[hotReloadTime(), window=_blank] for the calculation. +See link:{javadoc_base_url}/org/apache/ignite/configuration/IgniteConfiguration.html#setSslHotReloadBeforeExpiry(long)[setSslHotReloadBeforeExpiry(long), window=_blank] for the calculation. If the loaded certificates are still due for hot reload, Ignite records a failed hot reload attempt even though it installed them. -This can happen when the certificates have not changed, only the trust store changed, or the replacements expire within `hotReloadBeforeExpiryMs`. +This can happen when the certificates have not changed, only the trust store changed, or the replacements expire within `sslHotReloadBeforeExpiry`. The loaded context remains in use until a later reload replaces it. After a manual reload, Ignite schedules the next check from the loaded certificates. @@ -322,14 +320,6 @@ Limit request duration in custom sources: a blocked load delays other hot reload |The protocol for secure transport. https://docs.oracle.com/en/java/javase/11/docs/specs/security/standard-names.html#sslcontext-algorithms[Supported algorithms,window=_blank]. |`TLS` -|`hotReloadEnabled` -|Enables automatic certificate hot reload. See <>. -|`true` - -|`hotReloadBeforeExpiryMs` -|How long before the certificates expire hot reload becomes due, in milliseconds. See <>. -|`604800000` (7 days) - |`trustStoreFilePath` |The path to the trust store file. |`N/A` diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index 9ce105898653e..f5453c259c399 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -36,22 +36,16 @@ public interface ReloadableSslFactory extends Factory { public void init(); /** - * The hot reload time is the earliest expiry among the certificate chains of the private keys that new connections - * use, minus the lead time of the factory. A chain expires when any certificate in it expires. - * Keys without an X.509 certificate chain are ignored, as TLS cannot use them. A factory that has lost the keys - * of new connections, for example after a failed reload outside the registry, gives a time that has already come, - * so that the next check reloads it. + * The certificates expire when the first certificate in the chains of the private keys that new connections use + * expires. Keys without an X.509 certificate chain are ignored, as TLS cannot use them. A factory that has lost the + * keys of new connections, for example after a failed reload outside the registry, gives a time that has already + * come, so that the next check reloads it. * - * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the factory gives no private key with + * @return Expiry time in milliseconds since the epoch, or {@code 0} if the factory gives no private key with * an X.509 certificate chain. * @throws IgniteException If the factory cannot give the certificates that new connections use. */ - public long hotReloadTime(); - - /** @return Whether the registry reloads the factory before its certificates expire. Manual reload works either way. */ - public default boolean isHotReloadEnabled() { - return true; - } + public long certificatesExpiry(); /** * @param store Loaded key store. diff --git a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java index 48bd22d9caf0e..11ce1908152e3 100644 --- a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java @@ -21,7 +21,6 @@ import java.security.KeyManagementException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; @@ -35,9 +34,9 @@ /** * Base class for SSL context factories that cache their {@link SSLContext}. {@link #init()} loads a new context, and - * {@link #create()} returns the last one that it loaded, loading one on the first call. The hot reload time comes - * {@link #getHotReloadBeforeExpiryMs()} before the earliest expiry in the key store that the factory passed to - * {@link #createKeyManagers(KeyManagerFactory, KeyStore, char[])} during the last successful load. + * {@link #create()} returns the last one that it loaded, loading one on the first call. The certificates expiry comes + * from the key store that the factory passed to {@link #createKeyManagers(KeyManagerFactory, KeyStore, char[])} during + * the last successful load. */ public abstract class AbstractSslContextFactory implements ReloadableSslFactory { /** */ @@ -46,9 +45,6 @@ public abstract class AbstractSslContextFactory implements ReloadableSslFactory /** Default SSL protocol. */ public static final String DFLT_SSL_PROTOCOL = "TLS"; - /** Default lead time for certificate hot reload: 7 days. */ - public static final long DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS = TimeUnit.DAYS.toMillis(7); - /** SSL protocol. */ protected String proto = DFLT_SSL_PROTOCOL; @@ -61,12 +57,6 @@ public abstract class AbstractSslContextFactory implements ReloadableSslFactory /** Cached instance of an {@link SSLContext}. */ protected final AtomicReference sslCtx = new AtomicReference<>(); - /** */ - private boolean hotReloadEnabled = true; - - /** */ - private volatile long hotReloadBeforeExpiryMs = DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; - /** */ private transient volatile long earliestExpiry; @@ -74,40 +64,8 @@ public abstract class AbstractSslContextFactory implements ReloadableSslFactory private transient long pendingExpiry; /** {@inheritDoc} */ - @Override public boolean isHotReloadEnabled() { - return hotReloadEnabled; - } - - /** - * @param enabled Whether automatic certificate hot reload is enabled. It is enabled by default. Changes require - * a node restart. - */ - public void setHotReloadEnabled(boolean enabled) { - hotReloadEnabled = enabled; - } - - /** - * @return How long before the certificates expire hot reload becomes due, in milliseconds. - * Defaults to {@link #DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. - */ - public long getHotReloadBeforeExpiryMs() { - return hotReloadBeforeExpiryMs; - } - - /** - * @param millis How long before the certificates expire hot reload becomes due, in milliseconds. Must be positive. - */ - public void setHotReloadBeforeExpiryMs(long millis) { - A.ensure(millis > 0, "millis > 0"); - - hotReloadBeforeExpiryMs = millis; - } - - /** {@inheritDoc} */ - @Override public long hotReloadTime() { - long expiry = earliestExpiry; - - return expiry == 0 ? 0 : expiry - hotReloadBeforeExpiryMs; + @Override public long certificatesExpiry() { + return earliestExpiry; } /** diff --git a/modules/core/src/main/java/org/apache/ignite/configuration/IgniteConfiguration.java b/modules/core/src/main/java/org/apache/ignite/configuration/IgniteConfiguration.java index f39d792f924be..920fedce37a48 100644 --- a/modules/core/src/main/java/org/apache/ignite/configuration/IgniteConfiguration.java +++ b/modules/core/src/main/java/org/apache/ignite/configuration/IgniteConfiguration.java @@ -261,6 +261,12 @@ public class IgniteConfiguration implements IgniteConfigurationDefaults { @Deprecated public static final int DFLT_SQL_QUERY_HISTORY_SIZE = SqlConfiguration.DFLT_SQL_QUERY_HISTORY_SIZE; + /** Default value of {@link #isSslHotReloadEnabled()}. */ + public static final boolean DFLT_SSL_HOT_RELOAD_ENABLED = true; + + /** Default value of {@link #getSslHotReloadBeforeExpiry()}: 7 days. */ + public static final long DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY = 7L * 24 * 60 * 60 * 1000; + /** Optional local Ignite instance name. */ private String igniteInstanceName; @@ -512,6 +518,12 @@ public class IgniteConfiguration implements IgniteConfigurationDefaults { /** SSL connection factory. */ private Factory sslCtxFactory; + /** Whether the node reloads its SSL context factories before their certificates expire. */ + private boolean sslHotReloadEnabled = DFLT_SSL_HOT_RELOAD_ENABLED; + + /** How long before the certificates expire hot reload becomes due, in milliseconds. */ + private long sslHotReloadBeforeExpiry = DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY; + /** Platform configuration. */ private PlatformConfiguration platformCfg; @@ -691,6 +703,8 @@ public IgniteConfiguration(IgniteConfiguration cfg) { sndRetryDelay = cfg.getNetworkSendRetryDelay(); sqlConnCfg = cfg.getSqlConnectorConfiguration(); sslCtxFactory = cfg.getSslContextFactory(); + sslHotReloadBeforeExpiry = cfg.getSslHotReloadBeforeExpiry(); + sslHotReloadEnabled = cfg.isSslHotReloadEnabled(); storeSesLsnrs = cfg.getCacheStoreSessionListenerFactories(); stripedPoolSize = cfg.getStripedPoolSize(); svcCfgs = cfg.getServiceConfiguration(); @@ -1864,6 +1878,54 @@ public Factory getSslContextFactory() { return sslCtxFactory; } + /** + * Sets whether the node reloads the SSL context factories of its transports, including the HTTP REST endpoint, + * before their certificates expire. The TLS reload command reloads them either way. Changes require a node restart. + * + * @param sslHotReloadEnabled Whether automatic certificate hot reload is enabled. + * @return {@code this} for chaining. + */ + public IgniteConfiguration setSslHotReloadEnabled(boolean sslHotReloadEnabled) { + this.sslHotReloadEnabled = sslHotReloadEnabled; + + return this; + } + + /** + * Gets whether automatic certificate hot reload is enabled. Defaults to {@link #DFLT_SSL_HOT_RELOAD_ENABLED}. + * + * @return Whether automatic certificate hot reload is enabled. + */ + public boolean isSslHotReloadEnabled() { + return sslHotReloadEnabled; + } + + /** + * Sets how long before the certificates of an SSL context factory expire the node reloads the factory. Hot reload + * becomes due this long before the earliest expiry among the certificate chains of the private keys that the factory + * loaded. + * + * @param sslHotReloadBeforeExpiry Lead time in milliseconds. Must be positive. + * @return {@code this} for chaining. + */ + public IgniteConfiguration setSslHotReloadBeforeExpiry(long sslHotReloadBeforeExpiry) { + A.ensure(sslHotReloadBeforeExpiry > 0, "sslHotReloadBeforeExpiry > 0"); + + this.sslHotReloadBeforeExpiry = sslHotReloadBeforeExpiry; + + return this; + } + + /** + * Gets how long before the certificates expire hot reload becomes due. Defaults to + * {@link #DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY}. + * + * @return Lead time in milliseconds. + */ + public long getSslHotReloadBeforeExpiry() { + return sslHotReloadBeforeExpiry; + } + /** * Should return fully configured event SPI implementation. If not provided, * {@link NoopEventStorageSpi} will be used. diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java index 0f4d40eb6dd7e..0a639c4b1edc6 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java @@ -27,8 +27,6 @@ import java.util.Collection; import java.util.Collections; import java.util.StringTokenizer; -import javax.cache.configuration.Factory; -import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.configuration.ConnectorConfiguration; @@ -151,13 +149,6 @@ protected ConnectorConfiguration config() { return ctx.config().getConnectorConfiguration(); } - /** @return SSL context factory that the connector configuration sets, or the node's one if the connector sets none. */ - protected Factory sslContextFactory() { - Factory factory = config().getSslFactory(); - - return factory != null ? factory : ctx.config().getSslContextFactory(); - } - /** {@inheritDoc} */ @Override public Collection> getProperties() { try { diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java index 9eb169a41121d..d7e7328adca83 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java @@ -168,7 +168,7 @@ private GridNioFilter[] makeFilters(ConnectorConfiguration cfg) throws SSLExcept if (!cfg.isSslEnabled()) return new GridNioFilter[] { codec }; - Factory sslCtxFactory = sslContextFactory(); + Factory sslCtxFactory = sslContextFactory(cfg); if (sslCtxFactory == null) // Thrown SSL exception instead of IgniteCheckedException for writing correct warning message into log. @@ -187,6 +187,13 @@ private GridNioFilter[] makeFilters(ConnectorConfiguration cfg) throws SSLExcept return new GridNioFilter[] { codec, sslFilter }; } + /** */ + private Factory sslContextFactory(ConnectorConfiguration cfg) { + Factory factory = cfg.getSslFactory(); + + return factory != null ? factory : ctx.config().getSslContextFactory(); + } + /** * Tries to start server with given parameters. * @@ -231,7 +238,7 @@ private boolean startTcpServer(InetAddress hostAddr, int port, GridNioServerList ctx.ports().registerPort(port, IgnitePortProtocol.TCP, getClass()); if (cfg.isSslEnabled()) - ctx.ssl().register("binary REST", sslContextFactory()); + ctx.ssl().register("binary REST", sslContextFactory(cfg)); return true; } diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 77bc5e854370b..c4601020d70ba 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -31,6 +31,7 @@ import javax.cache.configuration.Factory; import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; +import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.GridKernalContext; import org.apache.ignite.internal.processors.GridProcessorAdapter; import org.apache.ignite.internal.processors.metric.MetricRegistryImpl; @@ -102,8 +103,11 @@ public List, String>> factories() { metrics.register("AutomaticHotReloadAttempts", automaticHotReloadAttempts::get, "Number of automatic hot reload attempts."); + if (!ctx.config().isSslHotReloadEnabled()) + return; + for (RegisteredFactory registered : factories) { - if (registered.reloadable == null || !registered.reloadable.isHotReloadEnabled()) + if (registered.reloadable == null) continue; if (executor == null) @@ -130,7 +134,7 @@ private long consecutiveHotReloadFailures() { } /** - * Reloads a registered factory. For a factory with hot reload enabled, waits for its running check, resets its failure + * Reloads a registered factory. If hot reload is enabled, waits for the running check of the factory, resets its failure * count and schedules its next check for the loaded certificates. If they are already due, the next check comes after * {@link #CHECK_PERIOD}, because a hot reload right away would load the same certificates from the source. * @@ -209,7 +213,7 @@ else if (log.isDebugEnabled()) * @throws IgniteException If the reload fails or leaves certificates that are still due. */ private long reloadIfDue() { - long hotReloadTime = reloadable.hotReloadTime(); + long hotReloadTime = hotReloadTime(); logHotReloadTime(hotReloadTime); @@ -228,7 +232,7 @@ private long reloadIfDue() { reloadable.init(); - hotReloadTime = reloadable.hotReloadTime(); + hotReloadTime = hotReloadTime(); nextCheckDelay = nextCheckDelay(hotReloadTime); if (nextCheckDelay == 0) { @@ -246,6 +250,16 @@ private long reloadIfDue() { return nextCheckDelay; } + /** + * @return Time when the loaded certificates are due for hot reload: {@link IgniteConfiguration#getSslHotReloadBeforeExpiry()} + * before they expire, or {@code 0} if the factory gives no private key with an X.509 certificate chain. + */ + private long hotReloadTime() { + long expiry = reloadable.certificatesExpiry(); + + return expiry == 0 ? 0 : expiry - ctx.config().getSslHotReloadBeforeExpiry(); + } + /** * @param hotReloadTime Hot reload time of the loaded certificates, or {@code 0} if they have none. * @return Delay until the hot reload time, but no longer than {@link #CHECK_PERIOD}, or {@code 0} if the time has @@ -280,12 +294,12 @@ private synchronized void reload() { reloadable.init(); - if (!reloadable.isHotReloadEnabled()) + if (!ctx.config().isSslHotReloadEnabled()) return; failures.set(0); - long hotReloadTime = reloadable.hotReloadTime(); + long hotReloadTime = hotReloadTime(); logHotReloadTime(hotReloadTime); diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index 90f6bd38fbc3a..d81fd4564f759 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -39,8 +39,8 @@ import javax.net.ssl.SSLException; import javax.net.ssl.TrustManager; import org.apache.ignite.IgniteException; +import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.GridKernalContext; -import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.processors.metric.GridMetricManager; import org.apache.ignite.internal.processors.metric.MetricRegistryImpl; import org.apache.ignite.internal.thread.context.OperationContext; @@ -65,6 +65,7 @@ import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; +import static org.apache.ignite.configuration.IgniteConfiguration.DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY; import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD; import static org.apache.ignite.ssl.TestCertificateAuthority.save; import static org.apache.ignite.testframework.GridTestUtils.runAsync; @@ -76,7 +77,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.RETURNS_DEFAULTS; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; @@ -103,6 +103,9 @@ public class SslFactoryRegistryTest { /** */ private final GridKernalContext ctx = mock(GridKernalContext.class); + /** Node configuration with the hot reload settings. */ + private final IgniteConfiguration cfg = new IgniteConfiguration(); + /** */ private final ScheduledExecutorService executor = mock(ScheduledExecutorService.class); @@ -146,6 +149,7 @@ public void setUp() throws Exception { when(ctx.metric()).thenReturn(metricMgr); when(metricMgr.registry("ssl")).thenReturn(metrics); when(ctx.log(SslFactoryRegistry.class)).thenReturn(new NullLogger()); + when(ctx.config()).thenReturn(cfg); registry = new SslFactoryRegistry(ctx); @@ -194,16 +198,16 @@ public void testFactoriesAreGroupedInRegistrationOrder() { } /** - * Given: a factory with hot reload disabled and valid certificates. + * Given: the node configuration disables hot reload, and a factory has valid certificates. * When: the registry starts. * Then: no hot reload thread starts, and the failure metric reads zero. */ @Test - public void testDisabledFactoryDoesNotStartHotReload() throws Exception { + public void testDisabledHotReloadDoesNotStart() throws Exception { SslContextFactory communication = factory(keys); writeFreshCertificates(keys); - communication.setHotReloadEnabled(false); + cfg.setSslHotReloadEnabled(false); registerTransport("communication", communication); registry.onKernalStart(true); @@ -235,9 +239,9 @@ public void testFactoryWithoutReloadDoesNotStartHotReload() { */ @Test public void testReloadableFactoryIsHotReloadedAndReloadedManually() { - ReloadableSslFactory rest = httpRestFactory(); + ReloadableSslFactory rest = mock(ReloadableSslFactory.class); - when(rest.hotReloadTime()).thenReturn(due(), at(DAYS.toHours(30))); + when(rest.certificatesExpiry()).thenReturn(due(), at(DAYS.toHours(30))); registry.register("HTTP REST", rest); registry.onKernalStart(true); @@ -268,14 +272,14 @@ public void testEachFactoryInstanceReloadsOnce() throws Exception { registerTransport("client connector", clientConnector); registry.onKernalStart(true); - long prevTime = communication.hotReloadTime(); + long prevTime = communication.certificatesExpiry(); writeFreshCertificates(keys); runChecks(); assertEquals(2, metric("AutomaticHotReloadAttempts")); - assertTrue(communication.hotReloadTime() > prevTime); - assertEquals(communication.hotReloadTime(), clientConnector.hotReloadTime()); + assertTrue(communication.certificatesExpiry() > prevTime); + assertEquals(communication.certificatesExpiry(), clientConnector.certificatesExpiry()); } /** @@ -293,13 +297,13 @@ public void testManualReloadLoadsOnlyItsFactoryInstance() throws Exception { registerTransport("client connector", clientConnector); registry.onKernalStart(true); - long prevTime = communication.hotReloadTime(); + long prevTime = communication.certificatesExpiry(); writeFreshCertificates(keys); registry.reload(clientConnector); - assertTrue(clientConnector.hotReloadTime() > prevTime); - assertEquals(prevTime, communication.hotReloadTime()); + assertTrue(clientConnector.certificatesExpiry() > prevTime); + assertEquals(prevTime, communication.certificatesExpiry()); } /** @@ -326,7 +330,7 @@ public void testStoreWithoutPrivateKeyIsReportedUntilKeysAreReloaded() throws Ex writeFreshCertificates(keys); registry.reload(communication); - assertEquals("TLS hot reload due [transports=communication, hotReloadTime=" + new Date(communication.hotReloadTime()) + ']', + assertEquals("TLS hot reload due [transports=communication, hotReloadTime=" + new Date(hotReloadTime(communication)) + ']', logged.get(logged.size() - 1)); } @@ -363,9 +367,9 @@ public void testFailedCheckIsRetriedAfterCheckPeriod() throws Exception { */ @Test public void testFailedReadOfHotReloadTimeIsRetriedWithoutFailingStart() throws Exception { - ReloadableSslFactory rest = httpRestFactory(); + ReloadableSslFactory rest = mock(ReloadableSslFactory.class); - when(rest.hotReloadTime()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")); + when(rest.certificatesExpiry()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")); writeCertificatesDueIn30Minutes(keys); registry.register("HTTP REST", rest); registerTransport("communication", factory(keys)); @@ -403,6 +407,36 @@ public void testNextCheckComesAtHotReloadTimeButWithinCheckPeriod() throws Excep assertEquals(HOURS.toMillis(1), (long)delays.get(1)); } + /** + * Given: the node configuration sets a hot reload lead time of an hour, and the certificates expire in 90 minutes. + * When: the check at start runs. + * Then: the next check comes in 30 minutes, an hour before the certificates expire. + */ + @Test + public void testHotReloadTimeUsesLeadTimeFromConfiguration() throws Exception { + long now = System.currentTimeMillis(); + + cfg.setSslHotReloadBeforeExpiry(HOURS.toMillis(1)); + save(authority.keyStore("node", now - HOURS.toMillis(1), now + MINUTES.toMillis(90)), keys); + registerTransport("communication", factory(keys)); + registry.onKernalStart(true); + runChecks(); + + assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); + } + + /** + * Given: a node configuration with the default lead time. + * When: the application sets a zero or negative lead time. + * Then: the setter rejects it and keeps the default. + */ + @Test + public void testNonPositiveLeadTimeIsRejected() { + assertThrows(IllegalArgumentException.class, () -> cfg.setSslHotReloadBeforeExpiry(0)); + assertThrows(IllegalArgumentException.class, () -> cfg.setSslHotReloadBeforeExpiry(-1)); + assertEquals(DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY, cfg.getSslHotReloadBeforeExpiry()); + } + /** * Given: the check reads a hot reload time that comes in 30 minutes, and any later read finds that the time has come, * as when the clock passes the hot reload time while the check runs. @@ -411,9 +445,11 @@ public void testNextCheckComesAtHotReloadTimeButWithinCheckPeriod() throws Excep */ @Test public void testCheckRightBeforeHotReloadTimeDoesNotDeferHotReload() { - ReloadableSslFactory rest = httpRestFactory(); + ReloadableSslFactory rest = mock(ReloadableSslFactory.class); - when(rest.hotReloadTime()).thenReturn(System.currentTimeMillis() + MINUTES.toMillis(30), due()); + long expiry = System.currentTimeMillis() + DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY + MINUTES.toMillis(30); + + when(rest.certificatesExpiry()).thenReturn(expiry, due()); registry.register("HTTP REST", rest); registry.onKernalStart(true); @@ -487,7 +523,7 @@ public void testHotReloadDoesNotInheritStartupContext() throws Exception { OperationContextAttribute reqId = OperationContextAttribute.newInstance(); CompletableFuture reloadReqId = new CompletableFuture<>(); - enableHotReload(factory, due()); + loaded(factory, due()); doAnswer(call -> { reloadReqId.complete(OperationContext.get(reqId)); @@ -514,7 +550,7 @@ public void testErrorFromOneFactoryDoesNotStopCheck() throws Exception { List logged = captureLog(); SslContextFactory clientConnector = factory(keys); - enableHotReload(factory, due()); + loaded(factory, due()); doThrow(new NoClassDefFoundError("Key store provider")).when(factory).init(); writeDueCertificates(keys); registry.register("communication", factory); @@ -543,7 +579,7 @@ public void testLogShowsDueTimeStartAndResultOfAttempts() throws Exception { registerTransport("communication", communication); registry.onKernalStart(true); - long due = communication.hotReloadTime(); + long due = hotReloadTime(communication); Files.delete(keys); runChecks(); @@ -561,7 +597,7 @@ public void testLogShowsDueTimeStartAndResultOfAttempts() throws Exception { assertEquals(List.of("due", "started", "failed", "started", "succeeded", "due"), evts); assertTrue(logged.get(0), logged.get(0).endsWith("hotReloadTime=" + new Date(due) + ']')); assertTrue(logged.get(2), logged.get(2).contains("nextAttempt=")); - assertTrue(logged.get(5), logged.get(5).endsWith("hotReloadTime=" + new Date(communication.hotReloadTime()) + ']')); + assertTrue(logged.get(5), logged.get(5).endsWith("hotReloadTime=" + new Date(hotReloadTime(communication)) + ']')); } /** @@ -631,25 +667,26 @@ public void testManualReloadBeforeStartLoadsFactory() throws Exception { writeDueCertificates(keys); registerTransport("communication", communication); - long prevTime = communication.hotReloadTime(); + long prevTime = communication.certificatesExpiry(); writeFreshCertificates(keys); registry.reload(communication); - assertTrue(communication.hotReloadTime() > prevTime); + assertTrue(communication.certificatesExpiry() > prevTime); } /** - * Given: a factory with hot reload disabled. + * Given: the node configuration disables hot reload. * When: a manual reload succeeds, and a second one fails because the key store file is deleted. - * Then: both count as manual attempts, and none counts as automatic. + * Then: both count as manual attempts, none counts as automatic, and the log has no hot reload lines. */ @Test public void testManualReloadWithoutHotReloadCountsAppliedAndFailedLoads() throws Exception { + List logged = captureLog(); SslContextFactory communication = factory(keys); writeFreshCertificates(keys); - communication.setHotReloadEnabled(false); + cfg.setSslHotReloadEnabled(false); registerTransport("communication", communication); registry.onKernalStart(true); registry.reload(communication); @@ -661,28 +698,7 @@ public void testManualReloadWithoutHotReloadCountsAppliedAndFailedLoads() throws assertThrows(IgniteException.class, () -> registry.reload(communication)); assertEquals(2, metric("ManualReloadAttempts")); assertEquals(0, metric("AutomaticHotReloadAttempts")); - } - - /** - * Given: communication has hot reload disabled and due certificates, and the client connector has hot reload enabled. - * When: communication is reloaded manually, and the scheduled checks run. - * Then: the checks make no automatic attempt, as communication gets no scheduled check. - */ - @Test - public void testManualReloadDoesNotScheduleCheckOfDisabledFactory() throws Exception { - Path clientKeys = dir.resolve("client-keys.jks"); - SslContextFactory communication = factory(keys); - - writeDueCertificates(keys); - writeFreshCertificates(clientKeys); - communication.setHotReloadEnabled(false); - registerTransport("communication", communication); - registerTransport("client connector", factory(clientKeys)); - registry.onKernalStart(true); - registry.reload(communication); - runChecks(); - - assertEquals(0, metric("AutomaticHotReloadAttempts")); + assertTrue(logged.toString(), logged.isEmpty()); } /** @@ -711,7 +727,7 @@ public void testScheduledReloadUsesCustomFactoryKeyStoreAndPassword() throws Exc long expiry = ((X509Certificate)replacement.getCertificate("node")).getNotAfter().getTime(); - assertEquals(expiry - custom.getHotReloadBeforeExpiryMs(), custom.hotReloadTime()); + assertEquals(expiry, custom.certificatesExpiry()); } /** @@ -726,7 +742,7 @@ public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { custom.setKeys(authority.keyStore("node", at(-1), at(10)), PASSWORD); custom.create(); - assertTrue(custom.hotReloadTime() > 0); + assertTrue(custom.certificatesExpiry() > 0); registry.register("communication", custom); registry.onKernalStart(true); @@ -735,7 +751,7 @@ public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { registry.reload(custom); runChecks(); - assertEquals(0, custom.hotReloadTime()); + assertEquals(0, custom.certificatesExpiry()); assertEquals(0, metric("AutomaticHotReloadAttempts")); } @@ -776,47 +792,6 @@ public void testFailedManualReloadKeepsFailures() throws Exception { assertEquals(1, failures()); } - /** - * Given: communication only reloads manually, and the client connector is due for hot reload. - * When: the scheduled check runs while communication is waiting for its certificate source. - * Then: the client connector loads its replacement before the manual reload finishes. - */ - @Test - public void testManualOnlyFactoryDoesNotDelayHotReload() throws Exception { - SslContextFactory clientConnector = factory(keys); - CountDownLatch manualStarted = new CountDownLatch(1); - CountDownLatch finishManual = new CountDownLatch(1); - - doAnswer(call -> { - manualStarted.countDown(); - finishManual.await(); - - return null; - }).when(factory).init(); - - writeDueCertificates(keys); - registry.register("communication", factory); - registerTransport("client connector", clientConnector); - registry.onKernalStart(true); - - long prevTime = clientConnector.hotReloadTime(); - - writeFreshCertificates(keys); - - IgniteInternalFuture manual = runAsync(() -> registry.reload(factory)); - - try { - assertTrue(manualStarted.await(TIMEOUT_MS, MILLISECONDS)); - runAsync(nextCheck()).get(TIMEOUT_MS); - - assertTrue(clientConnector.hotReloadTime() > prevTime); - } - finally { - finishManual.countDown(); - manual.get(TIMEOUT_MS); - } - } - /** * Given: an automatic attempt has started, failed to load a missing key store file, and pauses at its stop check * before it counts the failure. @@ -924,7 +899,7 @@ public void testStopInterruptsActiveAttemptWithoutWaitingForIt() throws Exceptio CountDownLatch attemptInterrupted = new CountDownLatch(1); CountDownLatch allowCompletion = new CountDownLatch(1); - enableHotReload(factory, due()); + loaded(factory, due()); doAnswer(call -> { attemptStarted.countDown(); @@ -965,7 +940,7 @@ public void testStopInterruptsActiveAttemptWithoutWaitingForIt() throws Exceptio public void testAttemptFailingDuringStopIsNotCounted() { List logged = captureLog(true); - enableHotReload(factory, due()); + loaded(factory, due()); doAnswer(call -> { when(executor.isShutdown()).thenReturn(true); @@ -992,8 +967,8 @@ public void testStopDuringCheckSkipsRemainingFactories() { SslContextFactory clientConnector = mock(SslContextFactory.class); AtomicInteger loads = new AtomicInteger(); - enableHotReload(factory, due()); - enableHotReload(clientConnector, due()); + loaded(factory, due()); + loaded(clientConnector, due()); for (SslContextFactory sslFactory : List.of(factory, clientConnector)) { doAnswer(call -> { @@ -1083,23 +1058,18 @@ private long metric(String name) { } /** - * Makes the factory mock look like a factory with hot reload enabled and loaded certificates with the given date. - * The mock returns {@code true} from {@code isHotReloadEnabled()} and the date from {@code hotReloadTime()}. + * Makes the factory mock look like a factory that has loaded certificates expiring at the given time. * * @param factory Factory mock. - * @param hotReloadTime Hot reload time of the loaded certificates. + * @param expiry Expiry time of the loaded certificates. */ - private static void enableHotReload(SslContextFactory factory, long hotReloadTime) { - when(factory.isHotReloadEnabled()).thenReturn(true); - when(factory.hotReloadTime()).thenReturn(hotReloadTime); + private static void loaded(SslContextFactory factory, long expiry) { + when(factory.certificatesExpiry()).thenReturn(expiry); } - /** - * @return Mock of a factory that is not an Ignite SSL context factory, such as the one of HTTP REST. It keeps the - * default methods of {@link ReloadableSslFactory}, so hot reload is enabled for it. - */ - private static ReloadableSslFactory httpRestFactory() { - return mock(ReloadableSslFactory.class, CALLS_REAL_METHODS); + /** @return Time when the certificates that the factory has loaded are due for hot reload with the configured lead time. */ + private long hotReloadTime(ReloadableSslFactory factory) { + return factory.certificatesExpiry() - cfg.getSslHotReloadBeforeExpiry(); } /** @return Hot reload time that has already come. */ diff --git a/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java b/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java index 7c93e451113a4..6900d7287a235 100644 --- a/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java +++ b/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java @@ -19,6 +19,7 @@ import java.nio.file.Files; import java.nio.file.Path; +import java.util.Date; import java.util.List; import javax.net.ssl.SSLContext; import org.apache.ignite.Ignition; @@ -36,7 +37,9 @@ import org.junit.Test; import static java.util.concurrent.TimeUnit.DAYS; +import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MINUTES; +import static org.apache.ignite.configuration.IgniteConfiguration.DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY; import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD; import static org.apache.ignite.ssl.TestCertificateAuthority.save; import static org.apache.ignite.testframework.GridTestUtils.waitForCondition; @@ -68,7 +71,7 @@ public void testNodeHotReloadsCertificatesForNewConnections() throws Exception { SSLContext initCtx = serverFactory.create(); - assertTrue("Hot reload must be due at startup", serverFactory.hotReloadTime() < now); + assertTrue("Hot reload must be due at startup", serverFactory.certificatesExpiry() - DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY < now); save(ca2.keyStore("node", now - MINUTES.toMillis(1), now + DAYS.toMillis(10)), keys); save(ca2.trustStore(), trust); @@ -177,6 +180,81 @@ public void testNodeStopEndsHotReloadThread() throws Exception { } } + /** + * Given: the node configuration disables hot reload, and the certificates of a TLS transport are due for hot reload. + * When: the node starts. + * Then: the node starts no hot reload thread. + */ + @Test + public void testNodeWithHotReloadDisabledStartsNoHotReloadThread() throws Exception { + long now = System.currentTimeMillis(); + TestCertificateAuthority ca = new TestCertificateAuthority("ca", now - DAYS.toMillis(1), now + DAYS.toMillis(10)); + Path dir = Files.createTempDirectory("ssl-hot-reload"); + Path keys = dir.resolve("keys.jks"); + Path trust = dir.resolve("trust.jks"); + + try { + save(ca.keyStore("node", now - MINUTES.toMillis(110), now + MINUTES.toMillis(10)), keys); + save(ca.trustStore(), trust); + + SslContextFactory serverFactory = configure(new SslContextFactory(), keys, trust); + + IgniteEx node = startGrid(0, cfg -> { + cfg.setSslHotReloadEnabled(false).setClientConnectorConfiguration(sslClientConnector(serverFactory)); + }); + + for (Thread thread : Thread.getAllStackTraces().keySet()) { + String name = thread.getName(); + + assertFalse(name, name.startsWith("ssl-hot-reload") && name.contains(node.name())); + } + } + finally { + stopAllGrids(); + U.delete(dir); + } + } + + /** + * Given: the node configuration sets a hot reload lead time of an hour, and the certificates of a TLS transport + * expire in 10 days. + * When: the node starts. + * Then: the node logs that hot reload is due an hour before the certificates expire. + */ + @Test + public void testNodeUsesHotReloadLeadTimeFromConfiguration() throws Exception { + long now = System.currentTimeMillis(); + long expiry = now + DAYS.toMillis(10); + TestCertificateAuthority ca = new TestCertificateAuthority("ca", now - DAYS.toMillis(1), now + DAYS.toMillis(20)); + Path dir = Files.createTempDirectory("ssl-hot-reload"); + Path keys = dir.resolve("keys.jks"); + Path trust = dir.resolve("trust.jks"); + ListeningTestLogger nodeLog = new ListeningTestLogger(log); + LogListener due = LogListener.matches("TLS hot reload due [transports=client connector, hotReloadTime=" + + new Date(expiry - HOURS.toMillis(1)) + ']').build(); + + nodeLog.registerListener(due); + + try { + save(ca.keyStore("node", now - DAYS.toMillis(1), expiry), keys); + save(ca.trustStore(), trust); + + SslContextFactory serverFactory = configure(new SslContextFactory(), keys, trust); + + startGrid(0, cfg -> { + cfg.setGridLogger(nodeLog) + .setSslHotReloadBeforeExpiry(HOURS.toMillis(1)) + .setClientConnectorConfiguration(sslClientConnector(serverFactory)); + }); + + assertTrue(due.check(TIMEOUT_MS)); + } + finally { + stopAllGrids(); + U.delete(dir); + } + } + /** * Given: a node with the client connector and REST, which stop their servers in their own {@code onKernalStop}. * When: the node starts its components. diff --git a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java index 503ebf6d79948..72241a3a488a7 100644 --- a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java +++ b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java @@ -43,7 +43,6 @@ import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.apache.ignite.ssl.SslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD; import static org.apache.ignite.ssl.TestCertificateAuthority.merge; import static org.apache.ignite.ssl.TestCertificateAuthority.save; @@ -84,56 +83,16 @@ public void setUp() throws Exception { } /** - * Given: a key store with only a CA certificate and the default hot reload setting. + * Given: a key store with only a CA certificate. * When: the factory loads the store. - * Then: the load succeeds with hot reload enabled and no scheduled reload date. + * Then: the load succeeds, and the factory gives no certificates expiry, so hot reload does not run for it. */ @Test - public void testDefaultSettingsAcceptStoreWithoutPrivateKeys() throws Exception { + public void testStoreWithOnlyCaCertificateLoadsWithoutExpiry() throws Exception { InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.trustStore()); - assertTrue(factory.isHotReloadEnabled()); assertNotNull(factory.create()); - assertEquals(0, factory.hotReloadTime()); - } - - /** - * Given: a factory has loaded a certificate that expires in 10 days. - * When: the application increases the lead time from the default of 7 days to 14 days before starting the node. - * Then: the same certificate is already due for hot reload. - */ - @Test - public void testHotReloadTimeUsesCurrentLeadTime() throws Exception { - Path keys = tmp.newFile("keys.jks").toPath(); - - save(authority.keyStore("node", at(-1), at(DAYS.toHours(10))), keys); - - SslContextFactory factory = new SslContextFactory(); - - factory.setKeyStoreFilePath(keys.toString()); - factory.setKeyStorePassword(PASSWORD); - factory.setTrustManagers(SslContextFactory.getDisabledTrustManager()); - factory.create(); - - assertEquals(at(DAYS.toHours(3)), factory.hotReloadTime()); - - factory.setHotReloadBeforeExpiryMs(DAYS.toMillis(14)); - - assertEquals(at(-DAYS.toHours(4)), factory.hotReloadTime()); - } - - /** - * Given: a factory with the default lead time. - * When: the application sets a zero or negative lead time. - * Then: the setter rejects it and keeps the default. - */ - @Test - public void testNonPositiveHotReloadBeforeExpiryMsIsRejected() { - SslContextFactory factory = new SslContextFactory(); - - assertThrows(IllegalArgumentException.class, () -> factory.setHotReloadBeforeExpiryMs(0)); - assertThrows(IllegalArgumentException.class, () -> factory.setHotReloadBeforeExpiryMs(-1)); - assertEquals(DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS, factory.getHotReloadBeforeExpiryMs()); + assertEquals(0, factory.certificatesExpiry()); } /** @@ -141,10 +100,10 @@ public void testNonPositiveHotReloadBeforeExpiryMsIsRejected() { * In one of them, that chain gets its expiry from an issuer that expires before the key certificate. * Other entries are a chain that expires later, a secret key and a key with a certificate chain that is not X.509. * When: the factory loads each key store. - * Then: hot reload is due now, 15 hours before the chain that expires first. + * Then: the certificates expire in 15 hours, with the chain that expires first. */ @Test - public void testHotReloadTimeComesFromEarliestExpiringChain() throws Exception { + public void testExpiryComesFromEarliestExpiringChain() throws Exception { TestCertificateAuthority shortIssuer = new TestCertificateAuthority("short-issuer", now - DAYS.toMillis(365), at(15)); KeyStore node = authority.keyStore("node", at(-85), at(15)); KeyStore withUnusableKeys = KeyStore.getInstance("JCEKS"); @@ -155,17 +114,17 @@ public void testHotReloadTimeComesFromEarliestExpiringChain() throws Exception { withUnusableKeys.setKeyEntry("other", node.getKey("node", PASSWORD), PASSWORD, new Certificate[] {new OtherCertificate(node.getCertificate("node").getPublicKey())}); - assertHotReloadIsDueNow(node); - assertHotReloadIsDueNow(shortIssuer.keyStore("node", at(-85), at(100))); - assertHotReloadIsDueNow(merge(authority.keyStore("first", at(-85), at(15)), authority.keyStore("second", at(-200), at(100)))); - assertHotReloadIsDueNow(merge(authority.keyStore("first", at(-200), at(100)), authority.keyStore("second", at(-85), at(15)))); - assertHotReloadIsDueNow(withUnusableKeys); + assertExpiresIn15Hours(node); + assertExpiresIn15Hours(shortIssuer.keyStore("node", at(-85), at(100))); + assertExpiresIn15Hours(merge(authority.keyStore("first", at(-85), at(15)), authority.keyStore("second", at(-200), at(100)))); + assertExpiresIn15Hours(merge(authority.keyStore("first", at(-200), at(100)), authority.keyStore("second", at(-85), at(15)))); + assertExpiresIn15Hours(withUnusableKeys); } /** * Given: a factory and an in-memory key store that counts its reads. * When: the factory loads its certificates. - * Then: it reads the key store once, so the hot reload date matches the loaded key managers. + * Then: it reads the key store once, so the certificates expiry matches the loaded key managers. */ @Test public void testLoadReadsKeyStoreOnce() throws Exception { @@ -179,7 +138,7 @@ public void testLoadReadsKeyStoreOnce() throws Exception { /** * Given: the issuer expired an hour ago, and the key certificate becomes valid in 99 hours. * When: the factory loads the chain for the first time. - * Then: the load succeeds, and hot reload has been due since 15 hours before the issuer expired. + * Then: the load succeeds, and the certificates expired an hour ago, with the issuer. */ @Test public void testFirstLoadAcceptsChainOutsideValidityPeriod() throws Exception { @@ -188,7 +147,7 @@ public void testFirstLoadAcceptsChainOutsideValidityPeriod() throws Exception { factory.create(); - assertEquals(at(-16), factory.hotReloadTime()); + assertEquals(at(-1), factory.certificatesExpiry()); } /** @@ -206,7 +165,7 @@ public void testStoreWithoutPrivateKeyLoadsWithoutHotReloadDate() throws Excepti InMemorySslContextFactory factory = new InMemorySslContextFactory(store); assertNotNull(factory.create()); - assertEquals(0, factory.hotReloadTime()); + assertEquals(0, factory.certificatesExpiry()); } /** @@ -301,7 +260,7 @@ public void testReloadRecoversAfterFailedTrustStoreLoad() throws Exception { factory.useTrustStore(trust.toString()); SSLContext ctx = factory.create(); - long hotReloadTime = factory.hotReloadTime(); + long expiry = factory.certificatesExpiry(); factory.keyStore = authority.keyStore("node", at(-1), at(99)); Files.delete(trust); @@ -310,24 +269,24 @@ public void testReloadRecoversAfterFailedTrustStoreLoad() throws Exception { assertTrue(err.getCause().getMessage(), err.getCause().getMessage().contains("key store file was not found")); assertSame(ctx, factory.create()); - assertEquals(hotReloadTime, factory.hotReloadTime()); + assertEquals(expiry, factory.certificatesExpiry()); save(authority.trustStore(), trust); factory.init(); assertNotSame(ctx, factory.create()); - assertEquals(at(84), factory.hotReloadTime()); + assertEquals(at(99), factory.certificatesExpiry()); } /** * Given: a reload of certificates with a new date blocks on the trust store load. - * When: another thread reads {@link SslContextFactory#hotReloadTime()} during the reload. + * When: another thread reads {@link SslContextFactory#certificatesExpiry()} during the reload. * Then: the read returns the current date without waiting for the reload. */ @Test - public void testHotReloadTimeRemainsReadableDuringLoad() throws Exception { + public void testCertificatesExpiryRemainsReadableDuringLoad() throws Exception { InMemorySslContextFactory factory = spy(dueFactory()); - long hotReloadTime = factory.hotReloadTime(); + long expiry = factory.certificatesExpiry(); factory.keyStore = authority.keyStore("node", at(-1), at(99)); @@ -349,7 +308,7 @@ public void testHotReloadTimeRemainsReadableDuringLoad() throws Exception { try { assertTrue(trustLoadStarted.await(TIMEOUT_MS, MILLISECONDS)); - assertEquals(hotReloadTime, factory.hotReloadTime()); + assertEquals(expiry, factory.certificatesExpiry()); } finally { finishTrustLoad.countDown(); @@ -361,8 +320,8 @@ public void testHotReloadTimeRemainsReadableDuringLoad() throws Exception { } /** - * Creates a factory that has loaded certificates due for hot reload 5 hours ago. - * It reads both stores from memory. The certificates expire in 10 hours. + * Creates a factory that has loaded certificates that expire in 10 hours, so they are due for hot reload with + * the default lead time. It reads both stores from memory. */ private InMemorySslContextFactory dueFactory() throws Exception { InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.keyStore("node", at(-90), at(10))); @@ -371,18 +330,18 @@ private InMemorySslContextFactory dueFactory() throws Exception { factory.useTrustStore("memory-trust"); factory.create(); - assertEquals(at(-5), factory.hotReloadTime()); + assertEquals(at(10), factory.certificatesExpiry()); return factory; } - /** */ - private void assertHotReloadIsDueNow(KeyStore keys) { + /** Checks that the certificates of the key store expire in 15 hours. */ + private void assertExpiresIn15Hours(KeyStore keys) { InMemorySslContextFactory factory = new InMemorySslContextFactory(keys); factory.create(); - assertEquals(now, factory.hotReloadTime()); + assertEquals(at(15), factory.certificatesExpiry()); } /** @@ -431,7 +390,6 @@ private long at(long hours) { * A factory that reads its key store from a field instead of a file and counts the reads. * Tests change the field to put new certificates into the source. * By default the factory trusts all peers. Tests can configure a trust store from memory or a file. - * Hot reload is due 15 hours before expiry, so the tests count certificate dates in hours. */ private static class InMemorySslContextFactory extends SslContextFactory { /** */ @@ -453,7 +411,6 @@ private InMemorySslContextFactory(KeyStore keyStore) { setKeyStoreFilePath("memory"); setKeyStorePassword(PASSWORD); setTrustManagers(getDisabledTrustManager()); - setHotReloadBeforeExpiryMs(HOURS.toMillis(15)); } /** Selects the trust store that supplies the factory's trust managers. */ diff --git a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/ApiParity/IgniteConfigurationParityTest.cs b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/ApiParity/IgniteConfigurationParityTest.cs index 313832956f6ff..f5fee4c127eae 100644 --- a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/ApiParity/IgniteConfigurationParityTest.cs +++ b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/ApiParity/IgniteConfigurationParityTest.cs @@ -89,7 +89,9 @@ public class IgniteConfigurationParityTest "NetworkCompressionLevel", "PluginProviders", "MetricExporterSpi", - "TracingSpi" + "TracingSpi", + "isSslHotReloadEnabled", + "SslHotReloadBeforeExpiry" }; ///

diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java index c1c19b672d8cb..ca782cfe399d3 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java @@ -172,7 +172,7 @@ else if (log.isDebugEnabled()) Collection sslFactories = connector.getContainedBeans(SslConnectionFactory.class).stream() .map(SslConnectionFactory::getSslContextFactory) .distinct() - .map(factory -> new ReloadableJettySslFactory(factory, sslContextFactory())) + .map(ReloadableJettySslFactory::new) .toList(); for (port = initPort; port <= lastPort; port++) { diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index ba1ceb55da25e..afa226c4a98f9 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -24,18 +24,11 @@ import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; -import org.apache.ignite.ssl.AbstractSslContextFactory; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.jetbrains.annotations.Nullable; -import static org.apache.ignite.ssl.AbstractSslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; - /** * TLS factory of the Jetty HTTPS connector. A failed reload leaves the previous keys and trust settings in use. - * Hot reload follows {@link AbstractSslContextFactory#isHotReloadEnabled()} and - * {@link AbstractSslContextFactory#getHotReloadBeforeExpiryMs()} of the SSL factory of the REST connector. If there is - * no such factory, or it is not an {@link AbstractSslContextFactory}, hot reload is enabled with the lead time - * {@link AbstractSslContextFactory#DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. *

* Jetty's factory guards its TLS state with an internal lock: it loads the state under this lock, and new connections * take the state under it too. Before loading a replacement, Jetty clears the state. So that new connections never see @@ -45,8 +38,8 @@ * Jetty selects certificates for SNI host names from the key store of the state, so the restore keeps SNI selection. * If the restore fails too, the factory has no state until the next successful reload, and the reload error carries * that failure as a suppressed exception. A failed reload outside Ignite, such as one by Jetty's {@code KeyStoreScanner}, - * can also leave the factory without state. Such a factory is due for hot reload right away, and the reload has nothing - * to restore: it loads the configured sources. + * can also leave the factory without state. Its certificates count as expired, so hot reload is due right away, and + * the reload has nothing to restore: it loads the configured sources. *

* After a failed reload, the factory gets back the context and stores set in {@code jetty.xml}, and the next reload * reads its configured sources again. Once the factory has started, its getters return the loaded state rather than @@ -63,20 +56,13 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { /** State set in {@code jetty.xml}. The factory loads a {@code null} part from its configured source. */ private final TlsState configured; - /** SSL factory of the REST connector with the hot reload settings, or {@code null} to use the defaults. */ - @Nullable private final AbstractSslContextFactory hotReloadSettings; - - /** - * @param factory TLS factory of the HTTPS connector before startup, when its getters return the state set in {@code jetty.xml}. - * @param connectorFactory SSL factory of the REST connector. - */ - ReloadableJettySslFactory(SslContextFactory factory, @Nullable Factory connectorFactory) { + /** @param factory TLS factory of the HTTPS connector before startup, when its getters return the state set in {@code jetty.xml}. */ + ReloadableJettySslFactory(SslContextFactory factory) { assert !factory.isStarted(); this.factory = factory; configured = new TlsState(factory); - hotReloadSettings = connectorFactory instanceof AbstractSslContextFactory sslFactory ? sslFactory : null; } /** {@inheritDoc} */ @@ -96,12 +82,7 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { } /** {@inheritDoc} */ - @Override public boolean isHotReloadEnabled() { - return hotReloadSettings == null || hotReloadSettings.isHotReloadEnabled(); - } - - /** {@inheritDoc} */ - @Override public long hotReloadTime() { + @Override public long certificatesExpiry() { TlsState state = currentState(); if (state == null) @@ -109,20 +90,14 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { try { KeyStore store = state.keyStore(); - long expiry = store == null ? 0 : ReloadableSslFactory.keyChainsExpiry(store); - return expiry == 0 ? 0 : expiry - hotReloadBeforeExpiryMs(); + return store == null ? 0 : ReloadableSslFactory.keyChainsExpiry(store); } catch (GeneralSecurityException e) { throw new IgniteException("Failed to read the certificates of the HTTPS connector", e); } } - /** @return How long before the certificates expire hot reload becomes due, in milliseconds. */ - private long hotReloadBeforeExpiryMs() { - return hotReloadSettings == null ? DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS : hotReloadSettings.getHotReloadBeforeExpiryMs(); - } - /** * Reloads the factory and, if loading fails, restores the state that new connections used before, if there was one. * Runs under the factory lock inside {@code unload(...)}, and always throws {@link SkipUnload}. diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index 929d72ea9334a..c4d9cf13b6987 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -22,7 +22,6 @@ import java.nio.file.Path; import java.security.KeyStore; import java.security.cert.Certificate; -import java.security.cert.X509Certificate; import java.util.Deque; import java.util.List; import java.util.concurrent.ConcurrentLinkedDeque; @@ -210,67 +209,32 @@ public void testHotReloadedKeysSurviveFailedManualReload() throws Exception { * Given: a custom Jetty factory has loaded certificate A, valid for 30 days. * When: the factory reloads by itself and gets certificate B, which was issued 20 hours ago and expires in an hour. * Then its source fails, and Ignite reloads the factory. - * Then: the hot reload date comes 7 days before the certificate in use expires: 23 days ahead for A, 7 days before - * the expiry of B for B. The failed reload keeps B's date. + * Then: the factory reports the expiry of the certificate in use: in 30 days for A, in an hour for B. The failed reload + * keeps B's expiry. */ @Test - public void testHotReloadTimeFollowsKeysInUse() throws Exception { + public void testCertificatesExpiryFollowsKeysInUse() throws Exception { SourceSslContextFactory.supply(fresh(), due(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); jettyFactory.start(); try { - assertEquals(now + DAYS.toMillis(23), factory.hotReloadTime()); + assertEquals(now + DAYS.toMillis(30), factory.certificatesExpiry()); jettyFactory.reload(f -> { }); - long dueB = now + HOURS.toMillis(1) - DAYS.toMillis(7); - - assertEquals(dueB, factory.hotReloadTime()); + assertEquals(now + HOURS.toMillis(1), factory.certificatesExpiry()); assertThrows(log, factory::init, IgniteException.class, "Source is unavailable"); - assertEquals(dueB, factory.hotReloadTime()); + assertEquals(now + HOURS.toMillis(1), factory.certificatesExpiry()); } finally { jettyFactory.stop(); } } - /** - * Given: the SSL factory of the REST connector disables hot reload and sets a lead time of an hour, and HTTPS serves - * a certificate that expires in 30 days. - * When: the node starts. - * Then: the HTTPS factory follows both settings: its hot reload is disabled, and its hot reload date comes an hour - * before the certificate expires. - */ - @Test - @WithSystemProperty(key = KEY_STORE_PATH, value = "") - public void testHttpsFollowsHotReloadSettingsOfRestConnectorFactory() throws Exception { - KeyStore keys = fresh(); - org.apache.ignite.ssl.SslContextFactory connectorFactory = new org.apache.ignite.ssl.SslContextFactory(); - - keyStoreFile(keys); - connectorFactory.setHotReloadEnabled(false); - connectorFactory.setHotReloadBeforeExpiryMs(HOURS.toMillis(1)); - - IgniteConfiguration cfg = jettyConfig("jetty/https.xml"); - - cfg.getConnectorConfiguration().setSslFactory(connectorFactory); - - IgniteEx node = startGrid(cfg); - ReloadableSslFactory https = (ReloadableSslFactory)node.context().ssl().factories().stream() - .filter(registered -> "HTTP REST".equals(registered.getValue())) - .findFirst() - .orElseThrow() - .getKey(); - long expiry = ((X509Certificate)keys.getCertificate(HOST)).getNotAfter().getTime(); - - assertFalse(https.isHotReloadEnabled()); - assertEquals(expiry - HOURS.toMillis(1), https.hotReloadTime()); - } - /** * Given: a custom Jetty factory has loaded its keys, and its source then throws an error instead of an exception. * When: Ignite reloads the factory. @@ -282,7 +246,7 @@ public void testErrorFromSourceKeepsLastWorkingKeys() throws Exception { SourceSslContextFactory.supply(fresh(), new NoClassDefFoundError("Key store provider")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); jettyFactory.start(); @@ -301,7 +265,7 @@ public void testErrorFromSourceKeepsLastWorkingKeys() throws Exception { * Given: a reload that Ignite did not start, such as one by Jetty's {@code KeyStoreScanner}, has failed and left * the custom Jetty factory without keys. * When: Ignite reloads the factory while the source still fails, and again after the source supplies certificate B. - * Then: the first reload reports the source error, and the factory is due for hot reload right away, so a scheduled + * Then: the first reload reports the source error, and the certificates of the factory count as expired, so a scheduled * check reloads it as the reload command does. The second reload installs B. */ @Test @@ -311,7 +275,7 @@ public void testReloadRecoversFactoryLeftWithoutKeys() throws Exception { SourceSslContextFactory.supply(fresh(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); jettyFactory.start(); @@ -319,9 +283,9 @@ public void testReloadRecoversFactoryLeftWithoutKeys() throws Exception { assertThrows(log, () -> jettyFactory.reload(f -> { }), Exception.class, "Source is unavailable"); assertThrows(log, factory::init, IgniteException.class, "Source is unavailable"); - long hotReloadTime = factory.hotReloadTime(); + long expiry = factory.certificatesExpiry(); - assertTrue(hotReloadTime > 0 && hotReloadTime <= System.currentTimeMillis()); + assertTrue(expiry > 0 && expiry <= System.currentTimeMillis()); SourceSslContextFactory.supply(b); factory.init(); @@ -352,7 +316,7 @@ public void testTrustStoreReloadKeepsConfiguredKeysAfterFailure() throws Excepti jettyFactory.setTrustStoreType("JKS"); jettyFactory.setTrustStorePassword(new String(PASSWORD)); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); jettyFactory.start(); @@ -399,7 +363,7 @@ public void testReloadCallsFactoryReloadOnce() throws Exception { jettyFactory.setKeyStore(fresh()); jettyFactory.setKeyStorePassword(new String(PASSWORD)); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); jettyFactory.start(); From 9855067499bce4fd656898f994fb4aa24531804b Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 16:47:58 +0300 Subject: [PATCH 38/53] IGNITE-29212 State the unit of the hot reload lead time in the docs Co-Authored-By: Claude Opus 5.5 --- docs/_docs/security/ssl-tls.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index 7b9bcbb4bb5f3..ef908afa0e2f5 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -239,7 +239,7 @@ After a failed attempt, it retries an hour later. All checks run in one thread, so a slow certificate source can delay the checks of other factories. For each factory, hot reload becomes due `sslHotReloadBeforeExpiry` of the node configuration before the earliest certificate expiry in its private key chains. -This includes issuing certificates. The default lead time is 7 days. +This includes issuing certificates. The lead time is in milliseconds; the default is 7 days, `604800000`. For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded. The first check at or after that date attempts a reload, including the startup check. Allow enough time before expiry to supply the replacements and load the stores. From a5f16266c76cf787f1cd933fe1cff3df7c4fd2be Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 16:58:47 +0300 Subject: [PATCH 39/53] IGNITE-29212 Let a factory keep its source on manual reload only ReloadableSslFactory gets hotReloadAllowed(), true by default. A custom Ignite factory whose source allows loads only on request overrides it to return false. The registry then gives the factory no hot reload check, at start or after a manual reload, while the reload command still reloads it. The node switch still turns hot reload off for all factories. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/security/ssl-tls.adoc | 2 + .../processors/ssl/ReloadableSslFactory.java | 10 ++++ .../processors/ssl/SslFactoryRegistry.java | 22 +++++--- .../ssl/SslFactoryRegistryTest.java | 51 +++++++++++++++++-- 4 files changed, 73 insertions(+), 12 deletions(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index ef908afa0e2f5..01d7573b392df 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -290,6 +290,8 @@ On each load, call this method once with the key store and the key password that Ignite takes the hot reload date from that key store. A factory that does not call this method has no hot reload date, and the node logs a warning. A custom Jetty factory of the HTTP REST endpoint needs no such call: Ignite takes the date from the key store that the Jetty factory loads, for example in `loadKeyStore(Resource)`. +If the source of a custom Ignite factory allows loads only on request, override `hotReloadAllowed()` to return `false`. +Hot reload then skips the factory, and the reload command still reloads it. Limit request duration in custom sources: a blocked load delays other hot reloads and manual reload. == SslContextFactory Properties diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index f5453c259c399..b6418438f9cb6 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -47,6 +47,16 @@ public interface ReloadableSslFactory extends Factory { */ public long certificatesExpiry(); + /** + * Override to return {@code false} if the source of the factory allows loads only on request. Then hot reload skips + * the factory, and only the reload command reloads it. + * + * @return Whether the registry may reload the factory before its certificates expire. + */ + public default boolean hotReloadAllowed() { + return true; + } + /** * @param store Loaded key store. * @return Earliest certificate expiry in the private key chains, or {@code 0} if the store has no private key diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index c4601020d70ba..1fcdae778cfc5 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -103,11 +103,8 @@ public List, String>> factories() { metrics.register("AutomaticHotReloadAttempts", automaticHotReloadAttempts::get, "Number of automatic hot reload attempts."); - if (!ctx.config().isSslHotReloadEnabled()) - return; - for (RegisteredFactory registered : factories) { - if (registered.reloadable == null) + if (!registered.hotReloadEnabled()) continue; if (executor == null) @@ -134,9 +131,10 @@ private long consecutiveHotReloadFailures() { } /** - * Reloads a registered factory. If hot reload is enabled, waits for the running check of the factory, resets its failure - * count and schedules its next check for the loaded certificates. If they are already due, the next check comes after - * {@link #CHECK_PERIOD}, because a hot reload right away would load the same certificates from the source. + * Reloads a registered factory. If hot reload is enabled on the node and the factory allows it, waits for the running + * check of the factory, resets its failure count and schedules its next check for the loaded certificates. If they + * are already due, the next check comes after {@link #CHECK_PERIOD}, because a hot reload right away would load + * the same certificates from the source. * * @param factory Registered factory to reload. */ @@ -294,7 +292,7 @@ private synchronized void reload() { reloadable.init(); - if (!ctx.config().isSslHotReloadEnabled()) + if (!hotReloadEnabled()) return; failures.set(0); @@ -308,6 +306,14 @@ private synchronized void reload() { scheduleCheck(nextCheckDelay == 0 ? CHECK_PERIOD : nextCheckDelay); } + /** + * @return Whether the registry reloads the factory before its certificates expire: hot reload is enabled on + * the node, and the factory allows it. + */ + private boolean hotReloadEnabled() { + return reloadable != null && ctx.config().isSslHotReloadEnabled() && reloadable.hotReloadAllowed(); + } + /** Logs the hot reload time of the loaded certificates if it differs from the one logged last. */ private void logHotReloadTime(long hotReloadTime) { if (hotReloadTime == loggedHotReloadTime) diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index d81fd4564f759..a336a55886175 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -77,6 +77,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.RETURNS_DEFAULTS; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; @@ -239,7 +240,7 @@ public void testFactoryWithoutReloadDoesNotStartHotReload() { */ @Test public void testReloadableFactoryIsHotReloadedAndReloadedManually() { - ReloadableSslFactory rest = mock(ReloadableSslFactory.class); + ReloadableSslFactory rest = reloadableFactory(); when(rest.certificatesExpiry()).thenReturn(due(), at(DAYS.toHours(30))); @@ -367,7 +368,7 @@ public void testFailedCheckIsRetriedAfterCheckPeriod() throws Exception { */ @Test public void testFailedReadOfHotReloadTimeIsRetriedWithoutFailingStart() throws Exception { - ReloadableSslFactory rest = mock(ReloadableSslFactory.class); + ReloadableSslFactory rest = reloadableFactory(); when(rest.certificatesExpiry()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")); writeCertificatesDueIn30Minutes(keys); @@ -445,7 +446,7 @@ public void testNonPositiveLeadTimeIsRejected() { */ @Test public void testCheckRightBeforeHotReloadTimeDoesNotDeferHotReload() { - ReloadableSslFactory rest = mock(ReloadableSslFactory.class); + ReloadableSslFactory rest = reloadableFactory(); long expiry = System.currentTimeMillis() + DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY + MINUTES.toMillis(30); @@ -675,6 +676,30 @@ public void testManualReloadBeforeStartLoadsFactory() throws Exception { assertTrue(communication.certificatesExpiry() > prevTime); } + /** + * Given: hot reload is enabled on the node, and communication and the client connector have due certificates. + * The client connector factory allows loads only on request. + * When: the registry starts, the client connector is reloaded manually, and the scheduled checks run. + * Then: only communication makes an automatic attempt: the client connector gets no scheduled check, either at start + * or after its manual reload. + */ + @Test + public void testFactoryThatAllowsOnlyManualReloadGetsNoChecks() throws Exception { + Path clientKeys = dir.resolve("client-keys.jks"); + SslContextFactory clientConnector = factory(clientKeys, new ManualReloadOnlyFactory()); + + writeDueCertificates(keys); + writeDueCertificates(clientKeys); + registerTransport("communication", factory(keys)); + registerTransport("client connector", clientConnector); + registry.onKernalStart(true); + registry.reload(clientConnector); + runChecks(); + + assertEquals(1, metric("AutomaticHotReloadAttempts")); + assertEquals(1, metric("ManualReloadAttempts")); + } + /** * Given: the node configuration disables hot reload. * When: a manual reload succeeds, and a second one fails because the key store file is deleted. @@ -1058,15 +1083,22 @@ private long metric(String name) { } /** - * Makes the factory mock look like a factory that has loaded certificates expiring at the given time. + * Makes the factory mock look like a factory that allows hot reload and has loaded certificates expiring at the given + * time. * * @param factory Factory mock. * @param expiry Expiry time of the loaded certificates. */ private static void loaded(SslContextFactory factory, long expiry) { + when(factory.hotReloadAllowed()).thenReturn(true); when(factory.certificatesExpiry()).thenReturn(expiry); } + /** @return Mock of a reloadable factory that keeps the default methods of {@link ReloadableSslFactory}. */ + private static ReloadableSslFactory reloadableFactory() { + return mock(ReloadableSslFactory.class, CALLS_REAL_METHODS); + } + /** @return Time when the certificates that the factory has loaded are due for hot reload with the configured lead time. */ private long hotReloadTime(ReloadableSslFactory factory) { return factory.certificatesExpiry() - cfg.getSslHotReloadBeforeExpiry(); @@ -1139,6 +1171,17 @@ private static class DebugLogger extends NullLogger { } } + /** Factory whose source allows loads only on request. */ + private static class ManualReloadOnlyFactory extends SslContextFactory { + /** */ + private static final long serialVersionUID = 0; + + /** {@inheritDoc} */ + @Override public boolean hotReloadAllowed() { + return false; + } + } + /** Factories with the same key store path compare equal and cache their own SSL contexts. */ private static class KeyStorePathFactory extends SslContextFactory { /** */ From ea8a0d6a67ca0644f87f620cf4a06510e217a02a Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 17:11:01 +0300 Subject: [PATCH 40/53] IGNITE-29212 Clarify which TLS factories Ignite schedules --- docs/_docs/security/ssl-tls.adoc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index 01d7573b392df..82fd56e54fb4f 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -233,8 +233,8 @@ Ignite loads the replacements automatically when hot reload is due; no reload co === When Hot Reload Runs -At startup, Ignite checks each factory. -It checks each factory again when its certificates become due, but no later than an hour after the previous check. +When the node starts with hot reload enabled, Ignite checks each factory that allows automatic reload. +For each such factory, Ignite schedules the next check when its certificates become due or in one hour, whichever comes first. After a failed attempt, it retries an hour later. All checks run in one thread, so a slow certificate source can delay the checks of other factories. @@ -250,7 +250,7 @@ If the loaded certificates are still due for hot reload, Ignite records a failed This can happen when the certificates have not changed, only the trust store changed, or the replacements expire within `sslHotReloadBeforeExpiry`. The loaded context remains in use until a later reload replaces it. -After a manual reload, Ignite schedules the next check from the loaded certificates. +After a manual reload of a factory on this schedule, Ignite uses the loaded certificates to schedule its next check. New connections use the loaded certificates; established connections remain open. To confirm a replacement, open a new TLS connection to each affected endpoint and compare its peer certificate with the replacement. From 0139eeffba3499bf936ae7cc4f588a9deb46a2cd Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 17:16:30 +0300 Subject: [PATCH 41/53] IGNITE-29212 Use the node setting for automatic TLS reload The scheduler and the manual command both call init(). Remove the per-factory hotReloadAllowed() check and its dedicated test. --- docs/_docs/security/ssl-tls.adoc | 8 ++- .../processors/ssl/ReloadableSslFactory.java | 10 ---- .../processors/ssl/SslFactoryRegistry.java | 22 +++----- .../ssl/SslFactoryRegistryTest.java | 51 ++----------------- 4 files changed, 15 insertions(+), 76 deletions(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index 82fd56e54fb4f..ef908afa0e2f5 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -233,8 +233,8 @@ Ignite loads the replacements automatically when hot reload is due; no reload co === When Hot Reload Runs -When the node starts with hot reload enabled, Ignite checks each factory that allows automatic reload. -For each such factory, Ignite schedules the next check when its certificates become due or in one hour, whichever comes first. +At startup, Ignite checks each factory. +It checks each factory again when its certificates become due, but no later than an hour after the previous check. After a failed attempt, it retries an hour later. All checks run in one thread, so a slow certificate source can delay the checks of other factories. @@ -250,7 +250,7 @@ If the loaded certificates are still due for hot reload, Ignite records a failed This can happen when the certificates have not changed, only the trust store changed, or the replacements expire within `sslHotReloadBeforeExpiry`. The loaded context remains in use until a later reload replaces it. -After a manual reload of a factory on this schedule, Ignite uses the loaded certificates to schedule its next check. +After a manual reload, Ignite schedules the next check from the loaded certificates. New connections use the loaded certificates; established connections remain open. To confirm a replacement, open a new TLS connection to each affected endpoint and compare its peer certificate with the replacement. @@ -290,8 +290,6 @@ On each load, call this method once with the key store and the key password that Ignite takes the hot reload date from that key store. A factory that does not call this method has no hot reload date, and the node logs a warning. A custom Jetty factory of the HTTP REST endpoint needs no such call: Ignite takes the date from the key store that the Jetty factory loads, for example in `loadKeyStore(Resource)`. -If the source of a custom Ignite factory allows loads only on request, override `hotReloadAllowed()` to return `false`. -Hot reload then skips the factory, and the reload command still reloads it. Limit request duration in custom sources: a blocked load delays other hot reloads and manual reload. == SslContextFactory Properties diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index b6418438f9cb6..f5453c259c399 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -47,16 +47,6 @@ public interface ReloadableSslFactory extends Factory { */ public long certificatesExpiry(); - /** - * Override to return {@code false} if the source of the factory allows loads only on request. Then hot reload skips - * the factory, and only the reload command reloads it. - * - * @return Whether the registry may reload the factory before its certificates expire. - */ - public default boolean hotReloadAllowed() { - return true; - } - /** * @param store Loaded key store. * @return Earliest certificate expiry in the private key chains, or {@code 0} if the store has no private key diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 1fcdae778cfc5..c4601020d70ba 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -103,8 +103,11 @@ public List, String>> factories() { metrics.register("AutomaticHotReloadAttempts", automaticHotReloadAttempts::get, "Number of automatic hot reload attempts."); + if (!ctx.config().isSslHotReloadEnabled()) + return; + for (RegisteredFactory registered : factories) { - if (!registered.hotReloadEnabled()) + if (registered.reloadable == null) continue; if (executor == null) @@ -131,10 +134,9 @@ private long consecutiveHotReloadFailures() { } /** - * Reloads a registered factory. If hot reload is enabled on the node and the factory allows it, waits for the running - * check of the factory, resets its failure count and schedules its next check for the loaded certificates. If they - * are already due, the next check comes after {@link #CHECK_PERIOD}, because a hot reload right away would load - * the same certificates from the source. + * Reloads a registered factory. If hot reload is enabled, waits for the running check of the factory, resets its failure + * count and schedules its next check for the loaded certificates. If they are already due, the next check comes after + * {@link #CHECK_PERIOD}, because a hot reload right away would load the same certificates from the source. * * @param factory Registered factory to reload. */ @@ -292,7 +294,7 @@ private synchronized void reload() { reloadable.init(); - if (!hotReloadEnabled()) + if (!ctx.config().isSslHotReloadEnabled()) return; failures.set(0); @@ -306,14 +308,6 @@ private synchronized void reload() { scheduleCheck(nextCheckDelay == 0 ? CHECK_PERIOD : nextCheckDelay); } - /** - * @return Whether the registry reloads the factory before its certificates expire: hot reload is enabled on - * the node, and the factory allows it. - */ - private boolean hotReloadEnabled() { - return reloadable != null && ctx.config().isSslHotReloadEnabled() && reloadable.hotReloadAllowed(); - } - /** Logs the hot reload time of the loaded certificates if it differs from the one logged last. */ private void logHotReloadTime(long hotReloadTime) { if (hotReloadTime == loggedHotReloadTime) diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index a336a55886175..d81fd4564f759 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -77,7 +77,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.RETURNS_DEFAULTS; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; @@ -240,7 +239,7 @@ public void testFactoryWithoutReloadDoesNotStartHotReload() { */ @Test public void testReloadableFactoryIsHotReloadedAndReloadedManually() { - ReloadableSslFactory rest = reloadableFactory(); + ReloadableSslFactory rest = mock(ReloadableSslFactory.class); when(rest.certificatesExpiry()).thenReturn(due(), at(DAYS.toHours(30))); @@ -368,7 +367,7 @@ public void testFailedCheckIsRetriedAfterCheckPeriod() throws Exception { */ @Test public void testFailedReadOfHotReloadTimeIsRetriedWithoutFailingStart() throws Exception { - ReloadableSslFactory rest = reloadableFactory(); + ReloadableSslFactory rest = mock(ReloadableSslFactory.class); when(rest.certificatesExpiry()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")); writeCertificatesDueIn30Minutes(keys); @@ -446,7 +445,7 @@ public void testNonPositiveLeadTimeIsRejected() { */ @Test public void testCheckRightBeforeHotReloadTimeDoesNotDeferHotReload() { - ReloadableSslFactory rest = reloadableFactory(); + ReloadableSslFactory rest = mock(ReloadableSslFactory.class); long expiry = System.currentTimeMillis() + DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY + MINUTES.toMillis(30); @@ -676,30 +675,6 @@ public void testManualReloadBeforeStartLoadsFactory() throws Exception { assertTrue(communication.certificatesExpiry() > prevTime); } - /** - * Given: hot reload is enabled on the node, and communication and the client connector have due certificates. - * The client connector factory allows loads only on request. - * When: the registry starts, the client connector is reloaded manually, and the scheduled checks run. - * Then: only communication makes an automatic attempt: the client connector gets no scheduled check, either at start - * or after its manual reload. - */ - @Test - public void testFactoryThatAllowsOnlyManualReloadGetsNoChecks() throws Exception { - Path clientKeys = dir.resolve("client-keys.jks"); - SslContextFactory clientConnector = factory(clientKeys, new ManualReloadOnlyFactory()); - - writeDueCertificates(keys); - writeDueCertificates(clientKeys); - registerTransport("communication", factory(keys)); - registerTransport("client connector", clientConnector); - registry.onKernalStart(true); - registry.reload(clientConnector); - runChecks(); - - assertEquals(1, metric("AutomaticHotReloadAttempts")); - assertEquals(1, metric("ManualReloadAttempts")); - } - /** * Given: the node configuration disables hot reload. * When: a manual reload succeeds, and a second one fails because the key store file is deleted. @@ -1083,22 +1058,15 @@ private long metric(String name) { } /** - * Makes the factory mock look like a factory that allows hot reload and has loaded certificates expiring at the given - * time. + * Makes the factory mock look like a factory that has loaded certificates expiring at the given time. * * @param factory Factory mock. * @param expiry Expiry time of the loaded certificates. */ private static void loaded(SslContextFactory factory, long expiry) { - when(factory.hotReloadAllowed()).thenReturn(true); when(factory.certificatesExpiry()).thenReturn(expiry); } - /** @return Mock of a reloadable factory that keeps the default methods of {@link ReloadableSslFactory}. */ - private static ReloadableSslFactory reloadableFactory() { - return mock(ReloadableSslFactory.class, CALLS_REAL_METHODS); - } - /** @return Time when the certificates that the factory has loaded are due for hot reload with the configured lead time. */ private long hotReloadTime(ReloadableSslFactory factory) { return factory.certificatesExpiry() - cfg.getSslHotReloadBeforeExpiry(); @@ -1171,17 +1139,6 @@ private static class DebugLogger extends NullLogger { } } - /** Factory whose source allows loads only on request. */ - private static class ManualReloadOnlyFactory extends SslContextFactory { - /** */ - private static final long serialVersionUID = 0; - - /** {@inheritDoc} */ - @Override public boolean hotReloadAllowed() { - return false; - } - } - /** Factories with the same key store path compare equal and cache their own SSL contexts. */ private static class KeyStorePathFactory extends SslContextFactory { /** */ From 8dfaf3e857aa57577750c7666ef5fa987198d1c1 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Wed, 25 Nov 2026 17:37:06 +0300 Subject: [PATCH 42/53] IGNITE-29212 Retry reading certificate expiry after a manual TLS reload --- docs/_docs/security/ssl-tls.adoc | 12 +++++++----- .../processors/ssl/SslFactoryRegistry.java | 16 ++++++++++++++-- .../ssl/SslFactoryRegistryTest.java | 19 +++++++++++++++++++ 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index ef908afa0e2f5..78cb80b836767 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -164,7 +164,7 @@ It also reloads the link:restapi#https[HTTP REST endpoint] when its Jetty connec External client applications reload their certificates separately. Follow the trust-first order below even if you do not plan to run the command. -<> is enabled by default, so a node can load a replaced key store by itself within an hour once its current certificates are due. +<> is enabled by default, so a node can load a replaced key store on its next check once its current certificates are due. If a peer does not trust the new certificate yet, its new connections to that node fail. . Back up the key and trust store files before replacing them. @@ -233,10 +233,10 @@ Ignite loads the replacements automatically when hot reload is due; no reload co === When Hot Reload Runs -At startup, Ignite checks each factory. -It checks each factory again when its certificates become due, but no later than an hour after the previous check. -After a failed attempt, it retries an hour later. -All checks run in one thread, so a slow certificate source can delay the checks of other factories. +At startup, Ignite schedules a check for each factory. +If a factory's certificates are not yet due, Ignite schedules its next check for the due date or one hour later, whichever comes first. +After a failed attempt, Ignite schedules another check for one hour later. +All checks share one thread, so a slow certificate source can delay checks for other factories. For each factory, hot reload becomes due `sslHotReloadBeforeExpiry` of the node configuration before the earliest certificate expiry in its private key chains. This includes issuing certificates. The lead time is in milliseconds; the default is 7 days, `604800000`. @@ -251,6 +251,8 @@ This can happen when the certificates have not changed, only the trust store cha The loaded context remains in use until a later reload replaces it. After a manual reload, Ignite schedules the next check from the loaded certificates. +If Ignite cannot read their expiry dates, the new certificates stay in use and the command continues. +Ignite logs the error and schedules another check for one hour later. New connections use the loaded certificates; established connections remain open. To confirm a replacement, open a new TLS connection to each affected endpoint and compare its peer certificate with the replacement. diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index c4601020d70ba..4cfb39fc6ed9c 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -44,7 +44,7 @@ /** SSL factories used by running transports. */ public class SslFactoryRegistry extends GridProcessorAdapter { - /** Longest interval between two checks of a factory, and the delay of a retry after a failed check. */ + /** Maximum delay when scheduling a check, also used for retries after a failed check. */ private static final long CHECK_PERIOD = HOURS.toMillis(1); /** */ @@ -299,7 +299,19 @@ private synchronized void reload() { failures.set(0); - long hotReloadTime = hotReloadTime(); + long hotReloadTime; + + try { + hotReloadTime = hotReloadTime(); + } + catch (RuntimeException e) { + log.warning("TLS hot reload could not read certificate expiry after manual reload [transports=" + transports + + ", nextCheck=" + new Date(System.currentTimeMillis() + CHECK_PERIOD) + ']', e); + + scheduleCheck(CHECK_PERIOD); + + return; + } logHotReloadTime(hotReloadTime); diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index d81fd4564f759..af7136b5414e6 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -493,6 +493,25 @@ public void testManualReloadSchedulesCheckAtHotReloadTime() throws Exception { assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); } + /** A manual reload succeeds even if the factory can report certificate expiry only on the next check. */ + @Test + public void testManualReloadRetriesFailedExpiryRead() { + long expiry = System.currentTimeMillis() + DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY + MINUTES.toMillis(30); + + when(factory.certificatesExpiry()).thenThrow(new IgniteException("Certificate expiry unavailable")).thenReturn(expiry); + + registry.register("communication", factory); + registry.onKernalStart(true); + registry.reload(factory); + + assertEquals(HOURS.toMillis(1), nextCheckDelay()); + + runChecks(); + + assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); + verify(factory).init(); + } + /** * Given: the registry has started, and the key store still holds certificates that are due for hot reload. * When: a manual reload loads them. From bfe231ea82083a911d96402ec41174ca5e8dd055 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Thu, 26 Nov 2026 14:00:01 +0300 Subject: [PATCH 43/53] IGNITE-29212 Return the hot reload settings to the SSL factory Each SSL factory again has its own hot reload switch and lead time, so an operator can turn hot reload off for one factory whose source causes problems and keep it for the other transports. Hot reload stays enabled by default. The HTTP REST endpoint takes both settings from the SSL factory of the REST connector, or from the node's factory if the connector sets none. A manual reload still succeeds if the factory cannot report the hot reload time of the loaded certificates: the registry logs the error and checks the factory again in an hour. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/restapi.adoc | 2 + docs/_docs/security/ssl-tls.adoc | 34 +-- .../processors/ssl/ReloadableSslFactory.java | 18 +- .../ignite/ssl/AbstractSslContextFactory.java | 52 ++++- .../configuration/IgniteConfiguration.java | 62 ------ .../protocols/GridRestProtocolAdapter.java | 9 + .../protocols/tcp/GridTcpRestProtocol.java | 11 +- .../processors/ssl/SslFactoryRegistry.java | 30 +-- .../ssl/SslFactoryRegistryTest.java | 202 ++++++++++-------- .../ssl/SslCertificateHotReloadTest.java | 80 +------ .../ssl/SslContextFactoryHotReloadTest.java | 99 ++++++--- .../IgniteConfigurationParityTest.cs | 4 +- .../http/jetty/GridJettyRestProtocol.java | 2 +- .../http/jetty/ReloadableJettySslFactory.java | 37 +++- .../http/jetty/JettyRestHttpsReloadTest.java | 64 ++++-- 15 files changed, 376 insertions(+), 330 deletions(-) diff --git a/docs/_docs/restapi.adoc b/docs/_docs/restapi.adoc index be0dda69a1434..4bc17a88e6337 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -111,6 +111,8 @@ Both the standard Jetty factory and custom subclasses of `SslContextFactory.Serv After you replace the stores, run the link:tools/control-script#reloading-tls-certificates[`--ssl reload` command]. The node also reloads the stores automatically before its certificates expire, as described in link:security/ssl-tls#automatic-certificate-hot-reload[Automatic Certificate Hot Reload]. +Hot reload of the endpoint follows the `hotReloadEnabled` and `hotReloadBeforeExpiryMs` settings of the REST connector's SSL factory: the one set by `ConnectorConfiguration.setSslFactory(...)`, or the node's `IgniteConfiguration.setSslContextFactory(...)` if the connector sets none. +If there is no such factory, or it does not extend `AbstractSslContextFactory`, hot reload is enabled with a lead time of 7 days. Each reload asks the Jetty factory to load its stores again. New connections use the replacement certificates; established connections stay open. If loading fails, the endpoint keeps its current keys and trust settings, and new connections keep working with them. diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index 78cb80b836767..f80ec5c9f337d 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -202,19 +202,21 @@ It does not update external client applications. === Disable Hot Reload -Hot reload is enabled by default for all transports of a node. -To disable it, set `sslHotReloadEnabled` to `false` in the node configuration before starting the node: +Hot reload is enabled by default. +To disable it for a transport, disable it on the transport's factory before starting the node: [source,java] ---- -igniteCfg.setSslHotReloadEnabled(false); +factory.setHotReloadEnabled(false); ---- Changing this setting requires a node restart. -The reload command still reloads the factories. +The reload command still reloads the factory. +The HTTP REST endpoint follows this setting of the REST connector's SSL factory, as described in link:restapi#https[HTTPS]. -The `IgniteConfiguration` of Ignite.NET has no properties for hot reload. -To set `sslHotReloadEnabled` or `sslHotReloadBeforeExpiry` for a .NET node, use the Spring XML file set by `IgniteConfiguration.SpringConfigUrl`. +The `SslContextFactory` of Ignite.NET has no `hotReloadEnabled` or `hotReloadBeforeExpiryMs` property. +To set them for a .NET node, define the SSL factory in the Spring XML file set by `IgniteConfiguration.SpringConfigUrl`. +Leave `IgniteConfiguration.SslContextFactory` unset: it replaces the factory from the XML file. === Supply Replacements @@ -233,21 +235,21 @@ Ignite loads the replacements automatically when hot reload is due; no reload co === When Hot Reload Runs -At startup, Ignite schedules a check for each factory. +At startup, Ignite schedules a check for each factory with hot reload enabled. If a factory's certificates are not yet due, Ignite schedules its next check for the due date or one hour later, whichever comes first. After a failed attempt, Ignite schedules another check for one hour later. All checks share one thread, so a slow certificate source can delay checks for other factories. -For each factory, hot reload becomes due `sslHotReloadBeforeExpiry` of the node configuration before the earliest certificate expiry in its private key chains. -This includes issuing certificates. The lead time is in milliseconds; the default is 7 days, `604800000`. -For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded. +For each factory, hot reload becomes due `hotReloadBeforeExpiryMs` before the earliest certificate expiry in its private key chains. +This includes issuing certificates. The default lead time is 7 days. +For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded, and the lead time from the REST connector's SSL factory, as described in link:restapi#https[HTTPS]. The first check at or after that date attempts a reload, including the startup check. Allow enough time before expiry to supply the replacements and load the stores. Keep the lead time shorter than the lifetime of the replacement certificates, or they will already be due when loaded. -See link:{javadoc_base_url}/org/apache/ignite/configuration/IgniteConfiguration.html#setSslHotReloadBeforeExpiry(long)[setSslHotReloadBeforeExpiry(long), window=_blank] for the calculation. +See link:{javadoc_base_url}/org/apache/ignite/ssl/AbstractSslContextFactory.html#hotReloadTime()[hotReloadTime(), window=_blank] for the calculation. If the loaded certificates are still due for hot reload, Ignite records a failed hot reload attempt even though it installed them. -This can happen when the certificates have not changed, only the trust store changed, or the replacements expire within `sslHotReloadBeforeExpiry`. +This can happen when the certificates have not changed, only the trust store changed, or the replacements expire within `hotReloadBeforeExpiryMs`. The loaded context remains in use until a later reload replaces it. After a manual reload, Ignite schedules the next check from the loaded certificates. @@ -322,6 +324,14 @@ Limit request duration in custom sources: a blocked load delays other hot reload |The protocol for secure transport. https://docs.oracle.com/en/java/javase/11/docs/specs/security/standard-names.html#sslcontext-algorithms[Supported algorithms,window=_blank]. |`TLS` +|`hotReloadEnabled` +|Enables automatic certificate hot reload. See <>. +|`true` + +|`hotReloadBeforeExpiryMs` +|How long before the certificates expire hot reload becomes due, in milliseconds. See <>. +|`604800000` (7 days) + |`trustStoreFilePath` |The path to the trust store file. |`N/A` diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index f5453c259c399..9ce105898653e 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -36,16 +36,22 @@ public interface ReloadableSslFactory extends Factory { public void init(); /** - * The certificates expire when the first certificate in the chains of the private keys that new connections use - * expires. Keys without an X.509 certificate chain are ignored, as TLS cannot use them. A factory that has lost the - * keys of new connections, for example after a failed reload outside the registry, gives a time that has already - * come, so that the next check reloads it. + * The hot reload time is the earliest expiry among the certificate chains of the private keys that new connections + * use, minus the lead time of the factory. A chain expires when any certificate in it expires. + * Keys without an X.509 certificate chain are ignored, as TLS cannot use them. A factory that has lost the keys + * of new connections, for example after a failed reload outside the registry, gives a time that has already come, + * so that the next check reloads it. * - * @return Expiry time in milliseconds since the epoch, or {@code 0} if the factory gives no private key with + * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the factory gives no private key with * an X.509 certificate chain. * @throws IgniteException If the factory cannot give the certificates that new connections use. */ - public long certificatesExpiry(); + public long hotReloadTime(); + + /** @return Whether the registry reloads the factory before its certificates expire. Manual reload works either way. */ + public default boolean isHotReloadEnabled() { + return true; + } /** * @param store Loaded key store. diff --git a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java index 11ce1908152e3..48bd22d9caf0e 100644 --- a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java @@ -21,6 +21,7 @@ import java.security.KeyManagementException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; @@ -34,9 +35,9 @@ /** * Base class for SSL context factories that cache their {@link SSLContext}. {@link #init()} loads a new context, and - * {@link #create()} returns the last one that it loaded, loading one on the first call. The certificates expiry comes - * from the key store that the factory passed to {@link #createKeyManagers(KeyManagerFactory, KeyStore, char[])} during - * the last successful load. + * {@link #create()} returns the last one that it loaded, loading one on the first call. The hot reload time comes + * {@link #getHotReloadBeforeExpiryMs()} before the earliest expiry in the key store that the factory passed to + * {@link #createKeyManagers(KeyManagerFactory, KeyStore, char[])} during the last successful load. */ public abstract class AbstractSslContextFactory implements ReloadableSslFactory { /** */ @@ -45,6 +46,9 @@ public abstract class AbstractSslContextFactory implements ReloadableSslFactory /** Default SSL protocol. */ public static final String DFLT_SSL_PROTOCOL = "TLS"; + /** Default lead time for certificate hot reload: 7 days. */ + public static final long DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS = TimeUnit.DAYS.toMillis(7); + /** SSL protocol. */ protected String proto = DFLT_SSL_PROTOCOL; @@ -57,6 +61,12 @@ public abstract class AbstractSslContextFactory implements ReloadableSslFactory /** Cached instance of an {@link SSLContext}. */ protected final AtomicReference sslCtx = new AtomicReference<>(); + /** */ + private boolean hotReloadEnabled = true; + + /** */ + private volatile long hotReloadBeforeExpiryMs = DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; + /** */ private transient volatile long earliestExpiry; @@ -64,8 +74,40 @@ public abstract class AbstractSslContextFactory implements ReloadableSslFactory private transient long pendingExpiry; /** {@inheritDoc} */ - @Override public long certificatesExpiry() { - return earliestExpiry; + @Override public boolean isHotReloadEnabled() { + return hotReloadEnabled; + } + + /** + * @param enabled Whether automatic certificate hot reload is enabled. It is enabled by default. Changes require + * a node restart. + */ + public void setHotReloadEnabled(boolean enabled) { + hotReloadEnabled = enabled; + } + + /** + * @return How long before the certificates expire hot reload becomes due, in milliseconds. + * Defaults to {@link #DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. + */ + public long getHotReloadBeforeExpiryMs() { + return hotReloadBeforeExpiryMs; + } + + /** + * @param millis How long before the certificates expire hot reload becomes due, in milliseconds. Must be positive. + */ + public void setHotReloadBeforeExpiryMs(long millis) { + A.ensure(millis > 0, "millis > 0"); + + hotReloadBeforeExpiryMs = millis; + } + + /** {@inheritDoc} */ + @Override public long hotReloadTime() { + long expiry = earliestExpiry; + + return expiry == 0 ? 0 : expiry - hotReloadBeforeExpiryMs; } /** diff --git a/modules/core/src/main/java/org/apache/ignite/configuration/IgniteConfiguration.java b/modules/core/src/main/java/org/apache/ignite/configuration/IgniteConfiguration.java index 920fedce37a48..f39d792f924be 100644 --- a/modules/core/src/main/java/org/apache/ignite/configuration/IgniteConfiguration.java +++ b/modules/core/src/main/java/org/apache/ignite/configuration/IgniteConfiguration.java @@ -261,12 +261,6 @@ public class IgniteConfiguration implements IgniteConfigurationDefaults { @Deprecated public static final int DFLT_SQL_QUERY_HISTORY_SIZE = SqlConfiguration.DFLT_SQL_QUERY_HISTORY_SIZE; - /** Default value of {@link #isSslHotReloadEnabled()}. */ - public static final boolean DFLT_SSL_HOT_RELOAD_ENABLED = true; - - /** Default value of {@link #getSslHotReloadBeforeExpiry()}: 7 days. */ - public static final long DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY = 7L * 24 * 60 * 60 * 1000; - /** Optional local Ignite instance name. */ private String igniteInstanceName; @@ -518,12 +512,6 @@ public class IgniteConfiguration implements IgniteConfigurationDefaults { /** SSL connection factory. */ private Factory sslCtxFactory; - /** Whether the node reloads its SSL context factories before their certificates expire. */ - private boolean sslHotReloadEnabled = DFLT_SSL_HOT_RELOAD_ENABLED; - - /** How long before the certificates expire hot reload becomes due, in milliseconds. */ - private long sslHotReloadBeforeExpiry = DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY; - /** Platform configuration. */ private PlatformConfiguration platformCfg; @@ -703,8 +691,6 @@ public IgniteConfiguration(IgniteConfiguration cfg) { sndRetryDelay = cfg.getNetworkSendRetryDelay(); sqlConnCfg = cfg.getSqlConnectorConfiguration(); sslCtxFactory = cfg.getSslContextFactory(); - sslHotReloadBeforeExpiry = cfg.getSslHotReloadBeforeExpiry(); - sslHotReloadEnabled = cfg.isSslHotReloadEnabled(); storeSesLsnrs = cfg.getCacheStoreSessionListenerFactories(); stripedPoolSize = cfg.getStripedPoolSize(); svcCfgs = cfg.getServiceConfiguration(); @@ -1878,54 +1864,6 @@ public Factory getSslContextFactory() { return sslCtxFactory; } - /** - * Sets whether the node reloads the SSL context factories of its transports, including the HTTP REST endpoint, - * before their certificates expire. The TLS reload command reloads them either way. Changes require a node restart. - * - * @param sslHotReloadEnabled Whether automatic certificate hot reload is enabled. - * @return {@code this} for chaining. - */ - public IgniteConfiguration setSslHotReloadEnabled(boolean sslHotReloadEnabled) { - this.sslHotReloadEnabled = sslHotReloadEnabled; - - return this; - } - - /** - * Gets whether automatic certificate hot reload is enabled. Defaults to {@link #DFLT_SSL_HOT_RELOAD_ENABLED}. - * - * @return Whether automatic certificate hot reload is enabled. - */ - public boolean isSslHotReloadEnabled() { - return sslHotReloadEnabled; - } - - /** - * Sets how long before the certificates of an SSL context factory expire the node reloads the factory. Hot reload - * becomes due this long before the earliest expiry among the certificate chains of the private keys that the factory - * loaded. - * - * @param sslHotReloadBeforeExpiry Lead time in milliseconds. Must be positive. - * @return {@code this} for chaining. - */ - public IgniteConfiguration setSslHotReloadBeforeExpiry(long sslHotReloadBeforeExpiry) { - A.ensure(sslHotReloadBeforeExpiry > 0, "sslHotReloadBeforeExpiry > 0"); - - this.sslHotReloadBeforeExpiry = sslHotReloadBeforeExpiry; - - return this; - } - - /** - * Gets how long before the certificates expire hot reload becomes due. Defaults to - * {@link #DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY}. - * - * @return Lead time in milliseconds. - */ - public long getSslHotReloadBeforeExpiry() { - return sslHotReloadBeforeExpiry; - } - /** * Should return fully configured event SPI implementation. If not provided, * {@link NoopEventStorageSpi} will be used. diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java index 0a639c4b1edc6..0f4d40eb6dd7e 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java @@ -27,6 +27,8 @@ import java.util.Collection; import java.util.Collections; import java.util.StringTokenizer; +import javax.cache.configuration.Factory; +import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.configuration.ConnectorConfiguration; @@ -149,6 +151,13 @@ protected ConnectorConfiguration config() { return ctx.config().getConnectorConfiguration(); } + /** @return SSL context factory that the connector configuration sets, or the node's one if the connector sets none. */ + protected Factory sslContextFactory() { + Factory factory = config().getSslFactory(); + + return factory != null ? factory : ctx.config().getSslContextFactory(); + } + /** {@inheritDoc} */ @Override public Collection> getProperties() { try { diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java index d7e7328adca83..9eb169a41121d 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java @@ -168,7 +168,7 @@ private GridNioFilter[] makeFilters(ConnectorConfiguration cfg) throws SSLExcept if (!cfg.isSslEnabled()) return new GridNioFilter[] { codec }; - Factory sslCtxFactory = sslContextFactory(cfg); + Factory sslCtxFactory = sslContextFactory(); if (sslCtxFactory == null) // Thrown SSL exception instead of IgniteCheckedException for writing correct warning message into log. @@ -187,13 +187,6 @@ private GridNioFilter[] makeFilters(ConnectorConfiguration cfg) throws SSLExcept return new GridNioFilter[] { codec, sslFilter }; } - /** */ - private Factory sslContextFactory(ConnectorConfiguration cfg) { - Factory factory = cfg.getSslFactory(); - - return factory != null ? factory : ctx.config().getSslContextFactory(); - } - /** * Tries to start server with given parameters. * @@ -238,7 +231,7 @@ private boolean startTcpServer(InetAddress hostAddr, int port, GridNioServerList ctx.ports().registerPort(port, IgnitePortProtocol.TCP, getClass()); if (cfg.isSslEnabled()) - ctx.ssl().register("binary REST", sslContextFactory(cfg)); + ctx.ssl().register("binary REST", sslContextFactory()); return true; } diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 4cfb39fc6ed9c..f6d69ac240865 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -31,7 +31,6 @@ import javax.cache.configuration.Factory; import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; -import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.GridKernalContext; import org.apache.ignite.internal.processors.GridProcessorAdapter; import org.apache.ignite.internal.processors.metric.MetricRegistryImpl; @@ -103,11 +102,8 @@ public List, String>> factories() { metrics.register("AutomaticHotReloadAttempts", automaticHotReloadAttempts::get, "Number of automatic hot reload attempts."); - if (!ctx.config().isSslHotReloadEnabled()) - return; - for (RegisteredFactory registered : factories) { - if (registered.reloadable == null) + if (registered.reloadable == null || !registered.reloadable.isHotReloadEnabled()) continue; if (executor == null) @@ -134,9 +130,11 @@ private long consecutiveHotReloadFailures() { } /** - * Reloads a registered factory. If hot reload is enabled, waits for the running check of the factory, resets its failure + * Reloads a registered factory. For a factory with hot reload enabled, waits for its running check, resets its failure * count and schedules its next check for the loaded certificates. If they are already due, the next check comes after - * {@link #CHECK_PERIOD}, because a hot reload right away would load the same certificates from the source. + * {@link #CHECK_PERIOD}, because a hot reload right away would load the same certificates from the source. If the + * factory cannot give the hot reload time of the loaded certificates, the reload still succeeds, and the next check + * comes after {@link #CHECK_PERIOD}. * * @param factory Registered factory to reload. */ @@ -213,7 +211,7 @@ else if (log.isDebugEnabled()) * @throws IgniteException If the reload fails or leaves certificates that are still due. */ private long reloadIfDue() { - long hotReloadTime = hotReloadTime(); + long hotReloadTime = reloadable.hotReloadTime(); logHotReloadTime(hotReloadTime); @@ -232,7 +230,7 @@ private long reloadIfDue() { reloadable.init(); - hotReloadTime = hotReloadTime(); + hotReloadTime = reloadable.hotReloadTime(); nextCheckDelay = nextCheckDelay(hotReloadTime); if (nextCheckDelay == 0) { @@ -250,16 +248,6 @@ private long reloadIfDue() { return nextCheckDelay; } - /** - * @return Time when the loaded certificates are due for hot reload: {@link IgniteConfiguration#getSslHotReloadBeforeExpiry()} - * before they expire, or {@code 0} if the factory gives no private key with an X.509 certificate chain. - */ - private long hotReloadTime() { - long expiry = reloadable.certificatesExpiry(); - - return expiry == 0 ? 0 : expiry - ctx.config().getSslHotReloadBeforeExpiry(); - } - /** * @param hotReloadTime Hot reload time of the loaded certificates, or {@code 0} if they have none. * @return Delay until the hot reload time, but no longer than {@link #CHECK_PERIOD}, or {@code 0} if the time has @@ -294,7 +282,7 @@ private synchronized void reload() { reloadable.init(); - if (!ctx.config().isSslHotReloadEnabled()) + if (!reloadable.isHotReloadEnabled()) return; failures.set(0); @@ -302,7 +290,7 @@ private synchronized void reload() { long hotReloadTime; try { - hotReloadTime = hotReloadTime(); + hotReloadTime = reloadable.hotReloadTime(); } catch (RuntimeException e) { log.warning("TLS hot reload could not read certificate expiry after manual reload [transports=" + transports diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index af7136b5414e6..ab1f14753baef 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -39,8 +39,8 @@ import javax.net.ssl.SSLException; import javax.net.ssl.TrustManager; import org.apache.ignite.IgniteException; -import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.GridKernalContext; +import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.processors.metric.GridMetricManager; import org.apache.ignite.internal.processors.metric.MetricRegistryImpl; import org.apache.ignite.internal.thread.context.OperationContext; @@ -65,7 +65,6 @@ import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; -import static org.apache.ignite.configuration.IgniteConfiguration.DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY; import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD; import static org.apache.ignite.ssl.TestCertificateAuthority.save; import static org.apache.ignite.testframework.GridTestUtils.runAsync; @@ -77,6 +76,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.RETURNS_DEFAULTS; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; @@ -103,9 +103,6 @@ public class SslFactoryRegistryTest { /** */ private final GridKernalContext ctx = mock(GridKernalContext.class); - /** Node configuration with the hot reload settings. */ - private final IgniteConfiguration cfg = new IgniteConfiguration(); - /** */ private final ScheduledExecutorService executor = mock(ScheduledExecutorService.class); @@ -149,7 +146,6 @@ public void setUp() throws Exception { when(ctx.metric()).thenReturn(metricMgr); when(metricMgr.registry("ssl")).thenReturn(metrics); when(ctx.log(SslFactoryRegistry.class)).thenReturn(new NullLogger()); - when(ctx.config()).thenReturn(cfg); registry = new SslFactoryRegistry(ctx); @@ -198,16 +194,16 @@ public void testFactoriesAreGroupedInRegistrationOrder() { } /** - * Given: the node configuration disables hot reload, and a factory has valid certificates. + * Given: a factory with hot reload disabled and valid certificates. * When: the registry starts. * Then: no hot reload thread starts, and the failure metric reads zero. */ @Test - public void testDisabledHotReloadDoesNotStart() throws Exception { + public void testDisabledFactoryDoesNotStartHotReload() throws Exception { SslContextFactory communication = factory(keys); writeFreshCertificates(keys); - cfg.setSslHotReloadEnabled(false); + communication.setHotReloadEnabled(false); registerTransport("communication", communication); registry.onKernalStart(true); @@ -239,9 +235,9 @@ public void testFactoryWithoutReloadDoesNotStartHotReload() { */ @Test public void testReloadableFactoryIsHotReloadedAndReloadedManually() { - ReloadableSslFactory rest = mock(ReloadableSslFactory.class); + ReloadableSslFactory rest = httpRestFactory(); - when(rest.certificatesExpiry()).thenReturn(due(), at(DAYS.toHours(30))); + when(rest.hotReloadTime()).thenReturn(due(), at(DAYS.toHours(30))); registry.register("HTTP REST", rest); registry.onKernalStart(true); @@ -272,14 +268,14 @@ public void testEachFactoryInstanceReloadsOnce() throws Exception { registerTransport("client connector", clientConnector); registry.onKernalStart(true); - long prevTime = communication.certificatesExpiry(); + long prevTime = communication.hotReloadTime(); writeFreshCertificates(keys); runChecks(); assertEquals(2, metric("AutomaticHotReloadAttempts")); - assertTrue(communication.certificatesExpiry() > prevTime); - assertEquals(communication.certificatesExpiry(), clientConnector.certificatesExpiry()); + assertTrue(communication.hotReloadTime() > prevTime); + assertEquals(communication.hotReloadTime(), clientConnector.hotReloadTime()); } /** @@ -297,13 +293,13 @@ public void testManualReloadLoadsOnlyItsFactoryInstance() throws Exception { registerTransport("client connector", clientConnector); registry.onKernalStart(true); - long prevTime = communication.certificatesExpiry(); + long prevTime = communication.hotReloadTime(); writeFreshCertificates(keys); registry.reload(clientConnector); - assertTrue(clientConnector.certificatesExpiry() > prevTime); - assertEquals(prevTime, communication.certificatesExpiry()); + assertTrue(clientConnector.hotReloadTime() > prevTime); + assertEquals(prevTime, communication.hotReloadTime()); } /** @@ -330,7 +326,7 @@ public void testStoreWithoutPrivateKeyIsReportedUntilKeysAreReloaded() throws Ex writeFreshCertificates(keys); registry.reload(communication); - assertEquals("TLS hot reload due [transports=communication, hotReloadTime=" + new Date(hotReloadTime(communication)) + ']', + assertEquals("TLS hot reload due [transports=communication, hotReloadTime=" + new Date(communication.hotReloadTime()) + ']', logged.get(logged.size() - 1)); } @@ -367,9 +363,9 @@ public void testFailedCheckIsRetriedAfterCheckPeriod() throws Exception { */ @Test public void testFailedReadOfHotReloadTimeIsRetriedWithoutFailingStart() throws Exception { - ReloadableSslFactory rest = mock(ReloadableSslFactory.class); + ReloadableSslFactory rest = httpRestFactory(); - when(rest.certificatesExpiry()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")); + when(rest.hotReloadTime()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")); writeCertificatesDueIn30Minutes(keys); registry.register("HTTP REST", rest); registerTransport("communication", factory(keys)); @@ -407,36 +403,6 @@ public void testNextCheckComesAtHotReloadTimeButWithinCheckPeriod() throws Excep assertEquals(HOURS.toMillis(1), (long)delays.get(1)); } - /** - * Given: the node configuration sets a hot reload lead time of an hour, and the certificates expire in 90 minutes. - * When: the check at start runs. - * Then: the next check comes in 30 minutes, an hour before the certificates expire. - */ - @Test - public void testHotReloadTimeUsesLeadTimeFromConfiguration() throws Exception { - long now = System.currentTimeMillis(); - - cfg.setSslHotReloadBeforeExpiry(HOURS.toMillis(1)); - save(authority.keyStore("node", now - HOURS.toMillis(1), now + MINUTES.toMillis(90)), keys); - registerTransport("communication", factory(keys)); - registry.onKernalStart(true); - runChecks(); - - assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); - } - - /** - * Given: a node configuration with the default lead time. - * When: the application sets a zero or negative lead time. - * Then: the setter rejects it and keeps the default. - */ - @Test - public void testNonPositiveLeadTimeIsRejected() { - assertThrows(IllegalArgumentException.class, () -> cfg.setSslHotReloadBeforeExpiry(0)); - assertThrows(IllegalArgumentException.class, () -> cfg.setSslHotReloadBeforeExpiry(-1)); - assertEquals(DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY, cfg.getSslHotReloadBeforeExpiry()); - } - /** * Given: the check reads a hot reload time that comes in 30 minutes, and any later read finds that the time has come, * as when the clock passes the hot reload time while the check runs. @@ -445,11 +411,9 @@ public void testNonPositiveLeadTimeIsRejected() { */ @Test public void testCheckRightBeforeHotReloadTimeDoesNotDeferHotReload() { - ReloadableSslFactory rest = mock(ReloadableSslFactory.class); - - long expiry = System.currentTimeMillis() + DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY + MINUTES.toMillis(30); + ReloadableSslFactory rest = httpRestFactory(); - when(rest.certificatesExpiry()).thenReturn(expiry, due()); + when(rest.hotReloadTime()).thenReturn(System.currentTimeMillis() + MINUTES.toMillis(30), due()); registry.register("HTTP REST", rest); registry.onKernalStart(true); @@ -493,12 +457,16 @@ public void testManualReloadSchedulesCheckAtHotReloadTime() throws Exception { assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); } - /** A manual reload succeeds even if the factory can report certificate expiry only on the next check. */ + /** + * Given: a factory fails to report its hot reload time once, and then reports one that comes in 30 minutes. + * When: a manual reload loads the factory, and the next check runs. + * Then: the reload succeeds and schedules a check in an hour, and that check schedules the next one in 30 minutes. + */ @Test - public void testManualReloadRetriesFailedExpiryRead() { - long expiry = System.currentTimeMillis() + DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY + MINUTES.toMillis(30); - - when(factory.certificatesExpiry()).thenThrow(new IgniteException("Certificate expiry unavailable")).thenReturn(expiry); + public void testManualReloadRetriesFailedReadOfHotReloadTime() { + when(factory.isHotReloadEnabled()).thenReturn(true); + when(factory.hotReloadTime()).thenThrow(new IgniteException("Certificate expiry unavailable")) + .thenReturn(System.currentTimeMillis() + MINUTES.toMillis(30)); registry.register("communication", factory); registry.onKernalStart(true); @@ -542,7 +510,7 @@ public void testHotReloadDoesNotInheritStartupContext() throws Exception { OperationContextAttribute reqId = OperationContextAttribute.newInstance(); CompletableFuture reloadReqId = new CompletableFuture<>(); - loaded(factory, due()); + enableHotReload(factory, due()); doAnswer(call -> { reloadReqId.complete(OperationContext.get(reqId)); @@ -569,7 +537,7 @@ public void testErrorFromOneFactoryDoesNotStopCheck() throws Exception { List logged = captureLog(); SslContextFactory clientConnector = factory(keys); - loaded(factory, due()); + enableHotReload(factory, due()); doThrow(new NoClassDefFoundError("Key store provider")).when(factory).init(); writeDueCertificates(keys); registry.register("communication", factory); @@ -598,7 +566,7 @@ public void testLogShowsDueTimeStartAndResultOfAttempts() throws Exception { registerTransport("communication", communication); registry.onKernalStart(true); - long due = hotReloadTime(communication); + long due = communication.hotReloadTime(); Files.delete(keys); runChecks(); @@ -616,7 +584,7 @@ public void testLogShowsDueTimeStartAndResultOfAttempts() throws Exception { assertEquals(List.of("due", "started", "failed", "started", "succeeded", "due"), evts); assertTrue(logged.get(0), logged.get(0).endsWith("hotReloadTime=" + new Date(due) + ']')); assertTrue(logged.get(2), logged.get(2).contains("nextAttempt=")); - assertTrue(logged.get(5), logged.get(5).endsWith("hotReloadTime=" + new Date(hotReloadTime(communication)) + ']')); + assertTrue(logged.get(5), logged.get(5).endsWith("hotReloadTime=" + new Date(communication.hotReloadTime()) + ']')); } /** @@ -686,26 +654,25 @@ public void testManualReloadBeforeStartLoadsFactory() throws Exception { writeDueCertificates(keys); registerTransport("communication", communication); - long prevTime = communication.certificatesExpiry(); + long prevTime = communication.hotReloadTime(); writeFreshCertificates(keys); registry.reload(communication); - assertTrue(communication.certificatesExpiry() > prevTime); + assertTrue(communication.hotReloadTime() > prevTime); } /** - * Given: the node configuration disables hot reload. + * Given: a factory with hot reload disabled. * When: a manual reload succeeds, and a second one fails because the key store file is deleted. - * Then: both count as manual attempts, none counts as automatic, and the log has no hot reload lines. + * Then: both count as manual attempts, and none counts as automatic. */ @Test public void testManualReloadWithoutHotReloadCountsAppliedAndFailedLoads() throws Exception { - List logged = captureLog(); SslContextFactory communication = factory(keys); writeFreshCertificates(keys); - cfg.setSslHotReloadEnabled(false); + communication.setHotReloadEnabled(false); registerTransport("communication", communication); registry.onKernalStart(true); registry.reload(communication); @@ -717,7 +684,28 @@ public void testManualReloadWithoutHotReloadCountsAppliedAndFailedLoads() throws assertThrows(IgniteException.class, () -> registry.reload(communication)); assertEquals(2, metric("ManualReloadAttempts")); assertEquals(0, metric("AutomaticHotReloadAttempts")); - assertTrue(logged.toString(), logged.isEmpty()); + } + + /** + * Given: communication has hot reload disabled and due certificates, and the client connector has hot reload enabled. + * When: communication is reloaded manually, and the scheduled checks run. + * Then: the checks make no automatic attempt, as communication gets no scheduled check. + */ + @Test + public void testManualReloadDoesNotScheduleCheckOfDisabledFactory() throws Exception { + Path clientKeys = dir.resolve("client-keys.jks"); + SslContextFactory communication = factory(keys); + + writeDueCertificates(keys); + writeFreshCertificates(clientKeys); + communication.setHotReloadEnabled(false); + registerTransport("communication", communication); + registerTransport("client connector", factory(clientKeys)); + registry.onKernalStart(true); + registry.reload(communication); + runChecks(); + + assertEquals(0, metric("AutomaticHotReloadAttempts")); } /** @@ -746,7 +734,7 @@ public void testScheduledReloadUsesCustomFactoryKeyStoreAndPassword() throws Exc long expiry = ((X509Certificate)replacement.getCertificate("node")).getNotAfter().getTime(); - assertEquals(expiry, custom.certificatesExpiry()); + assertEquals(expiry - custom.getHotReloadBeforeExpiryMs(), custom.hotReloadTime()); } /** @@ -761,7 +749,7 @@ public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { custom.setKeys(authority.keyStore("node", at(-1), at(10)), PASSWORD); custom.create(); - assertTrue(custom.certificatesExpiry() > 0); + assertTrue(custom.hotReloadTime() > 0); registry.register("communication", custom); registry.onKernalStart(true); @@ -770,7 +758,7 @@ public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { registry.reload(custom); runChecks(); - assertEquals(0, custom.certificatesExpiry()); + assertEquals(0, custom.hotReloadTime()); assertEquals(0, metric("AutomaticHotReloadAttempts")); } @@ -811,6 +799,47 @@ public void testFailedManualReloadKeepsFailures() throws Exception { assertEquals(1, failures()); } + /** + * Given: communication only reloads manually, and the client connector is due for hot reload. + * When: the scheduled check runs while communication is waiting for its certificate source. + * Then: the client connector loads its replacement before the manual reload finishes. + */ + @Test + public void testManualOnlyFactoryDoesNotDelayHotReload() throws Exception { + SslContextFactory clientConnector = factory(keys); + CountDownLatch manualStarted = new CountDownLatch(1); + CountDownLatch finishManual = new CountDownLatch(1); + + doAnswer(call -> { + manualStarted.countDown(); + finishManual.await(); + + return null; + }).when(factory).init(); + + writeDueCertificates(keys); + registry.register("communication", factory); + registerTransport("client connector", clientConnector); + registry.onKernalStart(true); + + long prevTime = clientConnector.hotReloadTime(); + + writeFreshCertificates(keys); + + IgniteInternalFuture manual = runAsync(() -> registry.reload(factory)); + + try { + assertTrue(manualStarted.await(TIMEOUT_MS, MILLISECONDS)); + runAsync(nextCheck()).get(TIMEOUT_MS); + + assertTrue(clientConnector.hotReloadTime() > prevTime); + } + finally { + finishManual.countDown(); + manual.get(TIMEOUT_MS); + } + } + /** * Given: an automatic attempt has started, failed to load a missing key store file, and pauses at its stop check * before it counts the failure. @@ -918,7 +947,7 @@ public void testStopInterruptsActiveAttemptWithoutWaitingForIt() throws Exceptio CountDownLatch attemptInterrupted = new CountDownLatch(1); CountDownLatch allowCompletion = new CountDownLatch(1); - loaded(factory, due()); + enableHotReload(factory, due()); doAnswer(call -> { attemptStarted.countDown(); @@ -959,7 +988,7 @@ public void testStopInterruptsActiveAttemptWithoutWaitingForIt() throws Exceptio public void testAttemptFailingDuringStopIsNotCounted() { List logged = captureLog(true); - loaded(factory, due()); + enableHotReload(factory, due()); doAnswer(call -> { when(executor.isShutdown()).thenReturn(true); @@ -986,8 +1015,8 @@ public void testStopDuringCheckSkipsRemainingFactories() { SslContextFactory clientConnector = mock(SslContextFactory.class); AtomicInteger loads = new AtomicInteger(); - loaded(factory, due()); - loaded(clientConnector, due()); + enableHotReload(factory, due()); + enableHotReload(clientConnector, due()); for (SslContextFactory sslFactory : List.of(factory, clientConnector)) { doAnswer(call -> { @@ -1077,18 +1106,23 @@ private long metric(String name) { } /** - * Makes the factory mock look like a factory that has loaded certificates expiring at the given time. + * Makes the factory mock look like a factory with hot reload enabled and loaded certificates with the given date. + * The mock returns {@code true} from {@code isHotReloadEnabled()} and the date from {@code hotReloadTime()}. * * @param factory Factory mock. - * @param expiry Expiry time of the loaded certificates. + * @param hotReloadTime Hot reload time of the loaded certificates. */ - private static void loaded(SslContextFactory factory, long expiry) { - when(factory.certificatesExpiry()).thenReturn(expiry); + private static void enableHotReload(SslContextFactory factory, long hotReloadTime) { + when(factory.isHotReloadEnabled()).thenReturn(true); + when(factory.hotReloadTime()).thenReturn(hotReloadTime); } - /** @return Time when the certificates that the factory has loaded are due for hot reload with the configured lead time. */ - private long hotReloadTime(ReloadableSslFactory factory) { - return factory.certificatesExpiry() - cfg.getSslHotReloadBeforeExpiry(); + /** + * @return Mock of a factory that is not an Ignite SSL context factory, such as the one of HTTP REST. It keeps the + * default methods of {@link ReloadableSslFactory}, so hot reload is enabled for it. + */ + private static ReloadableSslFactory httpRestFactory() { + return mock(ReloadableSslFactory.class, CALLS_REAL_METHODS); } /** @return Hot reload time that has already come. */ diff --git a/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java b/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java index 6900d7287a235..7c93e451113a4 100644 --- a/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java +++ b/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java @@ -19,7 +19,6 @@ import java.nio.file.Files; import java.nio.file.Path; -import java.util.Date; import java.util.List; import javax.net.ssl.SSLContext; import org.apache.ignite.Ignition; @@ -37,9 +36,7 @@ import org.junit.Test; import static java.util.concurrent.TimeUnit.DAYS; -import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MINUTES; -import static org.apache.ignite.configuration.IgniteConfiguration.DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY; import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD; import static org.apache.ignite.ssl.TestCertificateAuthority.save; import static org.apache.ignite.testframework.GridTestUtils.waitForCondition; @@ -71,7 +68,7 @@ public void testNodeHotReloadsCertificatesForNewConnections() throws Exception { SSLContext initCtx = serverFactory.create(); - assertTrue("Hot reload must be due at startup", serverFactory.certificatesExpiry() - DFLT_SSL_HOT_RELOAD_BEFORE_EXPIRY < now); + assertTrue("Hot reload must be due at startup", serverFactory.hotReloadTime() < now); save(ca2.keyStore("node", now - MINUTES.toMillis(1), now + DAYS.toMillis(10)), keys); save(ca2.trustStore(), trust); @@ -180,81 +177,6 @@ public void testNodeStopEndsHotReloadThread() throws Exception { } } - /** - * Given: the node configuration disables hot reload, and the certificates of a TLS transport are due for hot reload. - * When: the node starts. - * Then: the node starts no hot reload thread. - */ - @Test - public void testNodeWithHotReloadDisabledStartsNoHotReloadThread() throws Exception { - long now = System.currentTimeMillis(); - TestCertificateAuthority ca = new TestCertificateAuthority("ca", now - DAYS.toMillis(1), now + DAYS.toMillis(10)); - Path dir = Files.createTempDirectory("ssl-hot-reload"); - Path keys = dir.resolve("keys.jks"); - Path trust = dir.resolve("trust.jks"); - - try { - save(ca.keyStore("node", now - MINUTES.toMillis(110), now + MINUTES.toMillis(10)), keys); - save(ca.trustStore(), trust); - - SslContextFactory serverFactory = configure(new SslContextFactory(), keys, trust); - - IgniteEx node = startGrid(0, cfg -> { - cfg.setSslHotReloadEnabled(false).setClientConnectorConfiguration(sslClientConnector(serverFactory)); - }); - - for (Thread thread : Thread.getAllStackTraces().keySet()) { - String name = thread.getName(); - - assertFalse(name, name.startsWith("ssl-hot-reload") && name.contains(node.name())); - } - } - finally { - stopAllGrids(); - U.delete(dir); - } - } - - /** - * Given: the node configuration sets a hot reload lead time of an hour, and the certificates of a TLS transport - * expire in 10 days. - * When: the node starts. - * Then: the node logs that hot reload is due an hour before the certificates expire. - */ - @Test - public void testNodeUsesHotReloadLeadTimeFromConfiguration() throws Exception { - long now = System.currentTimeMillis(); - long expiry = now + DAYS.toMillis(10); - TestCertificateAuthority ca = new TestCertificateAuthority("ca", now - DAYS.toMillis(1), now + DAYS.toMillis(20)); - Path dir = Files.createTempDirectory("ssl-hot-reload"); - Path keys = dir.resolve("keys.jks"); - Path trust = dir.resolve("trust.jks"); - ListeningTestLogger nodeLog = new ListeningTestLogger(log); - LogListener due = LogListener.matches("TLS hot reload due [transports=client connector, hotReloadTime=" - + new Date(expiry - HOURS.toMillis(1)) + ']').build(); - - nodeLog.registerListener(due); - - try { - save(ca.keyStore("node", now - DAYS.toMillis(1), expiry), keys); - save(ca.trustStore(), trust); - - SslContextFactory serverFactory = configure(new SslContextFactory(), keys, trust); - - startGrid(0, cfg -> { - cfg.setGridLogger(nodeLog) - .setSslHotReloadBeforeExpiry(HOURS.toMillis(1)) - .setClientConnectorConfiguration(sslClientConnector(serverFactory)); - }); - - assertTrue(due.check(TIMEOUT_MS)); - } - finally { - stopAllGrids(); - U.delete(dir); - } - } - /** * Given: a node with the client connector and REST, which stop their servers in their own {@code onKernalStop}. * When: the node starts its components. diff --git a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java index 72241a3a488a7..503ebf6d79948 100644 --- a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java +++ b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java @@ -43,6 +43,7 @@ import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.apache.ignite.ssl.SslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD; import static org.apache.ignite.ssl.TestCertificateAuthority.merge; import static org.apache.ignite.ssl.TestCertificateAuthority.save; @@ -83,16 +84,56 @@ public void setUp() throws Exception { } /** - * Given: a key store with only a CA certificate. + * Given: a key store with only a CA certificate and the default hot reload setting. * When: the factory loads the store. - * Then: the load succeeds, and the factory gives no certificates expiry, so hot reload does not run for it. + * Then: the load succeeds with hot reload enabled and no scheduled reload date. */ @Test - public void testStoreWithOnlyCaCertificateLoadsWithoutExpiry() throws Exception { + public void testDefaultSettingsAcceptStoreWithoutPrivateKeys() throws Exception { InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.trustStore()); + assertTrue(factory.isHotReloadEnabled()); assertNotNull(factory.create()); - assertEquals(0, factory.certificatesExpiry()); + assertEquals(0, factory.hotReloadTime()); + } + + /** + * Given: a factory has loaded a certificate that expires in 10 days. + * When: the application increases the lead time from the default of 7 days to 14 days before starting the node. + * Then: the same certificate is already due for hot reload. + */ + @Test + public void testHotReloadTimeUsesCurrentLeadTime() throws Exception { + Path keys = tmp.newFile("keys.jks").toPath(); + + save(authority.keyStore("node", at(-1), at(DAYS.toHours(10))), keys); + + SslContextFactory factory = new SslContextFactory(); + + factory.setKeyStoreFilePath(keys.toString()); + factory.setKeyStorePassword(PASSWORD); + factory.setTrustManagers(SslContextFactory.getDisabledTrustManager()); + factory.create(); + + assertEquals(at(DAYS.toHours(3)), factory.hotReloadTime()); + + factory.setHotReloadBeforeExpiryMs(DAYS.toMillis(14)); + + assertEquals(at(-DAYS.toHours(4)), factory.hotReloadTime()); + } + + /** + * Given: a factory with the default lead time. + * When: the application sets a zero or negative lead time. + * Then: the setter rejects it and keeps the default. + */ + @Test + public void testNonPositiveHotReloadBeforeExpiryMsIsRejected() { + SslContextFactory factory = new SslContextFactory(); + + assertThrows(IllegalArgumentException.class, () -> factory.setHotReloadBeforeExpiryMs(0)); + assertThrows(IllegalArgumentException.class, () -> factory.setHotReloadBeforeExpiryMs(-1)); + assertEquals(DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS, factory.getHotReloadBeforeExpiryMs()); } /** @@ -100,10 +141,10 @@ public void testStoreWithOnlyCaCertificateLoadsWithoutExpiry() throws Exception * In one of them, that chain gets its expiry from an issuer that expires before the key certificate. * Other entries are a chain that expires later, a secret key and a key with a certificate chain that is not X.509. * When: the factory loads each key store. - * Then: the certificates expire in 15 hours, with the chain that expires first. + * Then: hot reload is due now, 15 hours before the chain that expires first. */ @Test - public void testExpiryComesFromEarliestExpiringChain() throws Exception { + public void testHotReloadTimeComesFromEarliestExpiringChain() throws Exception { TestCertificateAuthority shortIssuer = new TestCertificateAuthority("short-issuer", now - DAYS.toMillis(365), at(15)); KeyStore node = authority.keyStore("node", at(-85), at(15)); KeyStore withUnusableKeys = KeyStore.getInstance("JCEKS"); @@ -114,17 +155,17 @@ public void testExpiryComesFromEarliestExpiringChain() throws Exception { withUnusableKeys.setKeyEntry("other", node.getKey("node", PASSWORD), PASSWORD, new Certificate[] {new OtherCertificate(node.getCertificate("node").getPublicKey())}); - assertExpiresIn15Hours(node); - assertExpiresIn15Hours(shortIssuer.keyStore("node", at(-85), at(100))); - assertExpiresIn15Hours(merge(authority.keyStore("first", at(-85), at(15)), authority.keyStore("second", at(-200), at(100)))); - assertExpiresIn15Hours(merge(authority.keyStore("first", at(-200), at(100)), authority.keyStore("second", at(-85), at(15)))); - assertExpiresIn15Hours(withUnusableKeys); + assertHotReloadIsDueNow(node); + assertHotReloadIsDueNow(shortIssuer.keyStore("node", at(-85), at(100))); + assertHotReloadIsDueNow(merge(authority.keyStore("first", at(-85), at(15)), authority.keyStore("second", at(-200), at(100)))); + assertHotReloadIsDueNow(merge(authority.keyStore("first", at(-200), at(100)), authority.keyStore("second", at(-85), at(15)))); + assertHotReloadIsDueNow(withUnusableKeys); } /** * Given: a factory and an in-memory key store that counts its reads. * When: the factory loads its certificates. - * Then: it reads the key store once, so the certificates expiry matches the loaded key managers. + * Then: it reads the key store once, so the hot reload date matches the loaded key managers. */ @Test public void testLoadReadsKeyStoreOnce() throws Exception { @@ -138,7 +179,7 @@ public void testLoadReadsKeyStoreOnce() throws Exception { /** * Given: the issuer expired an hour ago, and the key certificate becomes valid in 99 hours. * When: the factory loads the chain for the first time. - * Then: the load succeeds, and the certificates expired an hour ago, with the issuer. + * Then: the load succeeds, and hot reload has been due since 15 hours before the issuer expired. */ @Test public void testFirstLoadAcceptsChainOutsideValidityPeriod() throws Exception { @@ -147,7 +188,7 @@ public void testFirstLoadAcceptsChainOutsideValidityPeriod() throws Exception { factory.create(); - assertEquals(at(-1), factory.certificatesExpiry()); + assertEquals(at(-16), factory.hotReloadTime()); } /** @@ -165,7 +206,7 @@ public void testStoreWithoutPrivateKeyLoadsWithoutHotReloadDate() throws Excepti InMemorySslContextFactory factory = new InMemorySslContextFactory(store); assertNotNull(factory.create()); - assertEquals(0, factory.certificatesExpiry()); + assertEquals(0, factory.hotReloadTime()); } /** @@ -260,7 +301,7 @@ public void testReloadRecoversAfterFailedTrustStoreLoad() throws Exception { factory.useTrustStore(trust.toString()); SSLContext ctx = factory.create(); - long expiry = factory.certificatesExpiry(); + long hotReloadTime = factory.hotReloadTime(); factory.keyStore = authority.keyStore("node", at(-1), at(99)); Files.delete(trust); @@ -269,24 +310,24 @@ public void testReloadRecoversAfterFailedTrustStoreLoad() throws Exception { assertTrue(err.getCause().getMessage(), err.getCause().getMessage().contains("key store file was not found")); assertSame(ctx, factory.create()); - assertEquals(expiry, factory.certificatesExpiry()); + assertEquals(hotReloadTime, factory.hotReloadTime()); save(authority.trustStore(), trust); factory.init(); assertNotSame(ctx, factory.create()); - assertEquals(at(99), factory.certificatesExpiry()); + assertEquals(at(84), factory.hotReloadTime()); } /** * Given: a reload of certificates with a new date blocks on the trust store load. - * When: another thread reads {@link SslContextFactory#certificatesExpiry()} during the reload. + * When: another thread reads {@link SslContextFactory#hotReloadTime()} during the reload. * Then: the read returns the current date without waiting for the reload. */ @Test - public void testCertificatesExpiryRemainsReadableDuringLoad() throws Exception { + public void testHotReloadTimeRemainsReadableDuringLoad() throws Exception { InMemorySslContextFactory factory = spy(dueFactory()); - long expiry = factory.certificatesExpiry(); + long hotReloadTime = factory.hotReloadTime(); factory.keyStore = authority.keyStore("node", at(-1), at(99)); @@ -308,7 +349,7 @@ public void testCertificatesExpiryRemainsReadableDuringLoad() throws Exception { try { assertTrue(trustLoadStarted.await(TIMEOUT_MS, MILLISECONDS)); - assertEquals(expiry, factory.certificatesExpiry()); + assertEquals(hotReloadTime, factory.hotReloadTime()); } finally { finishTrustLoad.countDown(); @@ -320,8 +361,8 @@ public void testCertificatesExpiryRemainsReadableDuringLoad() throws Exception { } /** - * Creates a factory that has loaded certificates that expire in 10 hours, so they are due for hot reload with - * the default lead time. It reads both stores from memory. + * Creates a factory that has loaded certificates due for hot reload 5 hours ago. + * It reads both stores from memory. The certificates expire in 10 hours. */ private InMemorySslContextFactory dueFactory() throws Exception { InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.keyStore("node", at(-90), at(10))); @@ -330,18 +371,18 @@ private InMemorySslContextFactory dueFactory() throws Exception { factory.useTrustStore("memory-trust"); factory.create(); - assertEquals(at(10), factory.certificatesExpiry()); + assertEquals(at(-5), factory.hotReloadTime()); return factory; } - /** Checks that the certificates of the key store expire in 15 hours. */ - private void assertExpiresIn15Hours(KeyStore keys) { + /** */ + private void assertHotReloadIsDueNow(KeyStore keys) { InMemorySslContextFactory factory = new InMemorySslContextFactory(keys); factory.create(); - assertEquals(at(15), factory.certificatesExpiry()); + assertEquals(now, factory.hotReloadTime()); } /** @@ -390,6 +431,7 @@ private long at(long hours) { * A factory that reads its key store from a field instead of a file and counts the reads. * Tests change the field to put new certificates into the source. * By default the factory trusts all peers. Tests can configure a trust store from memory or a file. + * Hot reload is due 15 hours before expiry, so the tests count certificate dates in hours. */ private static class InMemorySslContextFactory extends SslContextFactory { /** */ @@ -411,6 +453,7 @@ private InMemorySslContextFactory(KeyStore keyStore) { setKeyStoreFilePath("memory"); setKeyStorePassword(PASSWORD); setTrustManagers(getDisabledTrustManager()); + setHotReloadBeforeExpiryMs(HOURS.toMillis(15)); } /** Selects the trust store that supplies the factory's trust managers. */ diff --git a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/ApiParity/IgniteConfigurationParityTest.cs b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/ApiParity/IgniteConfigurationParityTest.cs index f5fee4c127eae..313832956f6ff 100644 --- a/modules/platforms/dotnet/Apache.Ignite.Core.Tests/ApiParity/IgniteConfigurationParityTest.cs +++ b/modules/platforms/dotnet/Apache.Ignite.Core.Tests/ApiParity/IgniteConfigurationParityTest.cs @@ -89,9 +89,7 @@ public class IgniteConfigurationParityTest "NetworkCompressionLevel", "PluginProviders", "MetricExporterSpi", - "TracingSpi", - "isSslHotReloadEnabled", - "SslHotReloadBeforeExpiry" + "TracingSpi" }; ///

diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java index ca782cfe399d3..c1c19b672d8cb 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java @@ -172,7 +172,7 @@ else if (log.isDebugEnabled()) Collection sslFactories = connector.getContainedBeans(SslConnectionFactory.class).stream() .map(SslConnectionFactory::getSslContextFactory) .distinct() - .map(ReloadableJettySslFactory::new) + .map(factory -> new ReloadableJettySslFactory(factory, sslContextFactory())) .toList(); for (port = initPort; port <= lastPort; port++) { diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java index afa226c4a98f9..ba1ceb55da25e 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java @@ -24,11 +24,18 @@ import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteException; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; +import org.apache.ignite.ssl.AbstractSslContextFactory; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.jetbrains.annotations.Nullable; +import static org.apache.ignite.ssl.AbstractSslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; + /** * TLS factory of the Jetty HTTPS connector. A failed reload leaves the previous keys and trust settings in use. + * Hot reload follows {@link AbstractSslContextFactory#isHotReloadEnabled()} and + * {@link AbstractSslContextFactory#getHotReloadBeforeExpiryMs()} of the SSL factory of the REST connector. If there is + * no such factory, or it is not an {@link AbstractSslContextFactory}, hot reload is enabled with the lead time + * {@link AbstractSslContextFactory#DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. *

* Jetty's factory guards its TLS state with an internal lock: it loads the state under this lock, and new connections * take the state under it too. Before loading a replacement, Jetty clears the state. So that new connections never see @@ -38,8 +45,8 @@ * Jetty selects certificates for SNI host names from the key store of the state, so the restore keeps SNI selection. * If the restore fails too, the factory has no state until the next successful reload, and the reload error carries * that failure as a suppressed exception. A failed reload outside Ignite, such as one by Jetty's {@code KeyStoreScanner}, - * can also leave the factory without state. Its certificates count as expired, so hot reload is due right away, and - * the reload has nothing to restore: it loads the configured sources. + * can also leave the factory without state. Such a factory is due for hot reload right away, and the reload has nothing + * to restore: it loads the configured sources. *

* After a failed reload, the factory gets back the context and stores set in {@code jetty.xml}, and the next reload * reads its configured sources again. Once the factory has started, its getters return the loaded state rather than @@ -56,13 +63,20 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { /** State set in {@code jetty.xml}. The factory loads a {@code null} part from its configured source. */ private final TlsState configured; - /** @param factory TLS factory of the HTTPS connector before startup, when its getters return the state set in {@code jetty.xml}. */ - ReloadableJettySslFactory(SslContextFactory factory) { + /** SSL factory of the REST connector with the hot reload settings, or {@code null} to use the defaults. */ + @Nullable private final AbstractSslContextFactory hotReloadSettings; + + /** + * @param factory TLS factory of the HTTPS connector before startup, when its getters return the state set in {@code jetty.xml}. + * @param connectorFactory SSL factory of the REST connector. + */ + ReloadableJettySslFactory(SslContextFactory factory, @Nullable Factory connectorFactory) { assert !factory.isStarted(); this.factory = factory; configured = new TlsState(factory); + hotReloadSettings = connectorFactory instanceof AbstractSslContextFactory sslFactory ? sslFactory : null; } /** {@inheritDoc} */ @@ -82,7 +96,12 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { } /** {@inheritDoc} */ - @Override public long certificatesExpiry() { + @Override public boolean isHotReloadEnabled() { + return hotReloadSettings == null || hotReloadSettings.isHotReloadEnabled(); + } + + /** {@inheritDoc} */ + @Override public long hotReloadTime() { TlsState state = currentState(); if (state == null) @@ -90,14 +109,20 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { try { KeyStore store = state.keyStore(); + long expiry = store == null ? 0 : ReloadableSslFactory.keyChainsExpiry(store); - return store == null ? 0 : ReloadableSslFactory.keyChainsExpiry(store); + return expiry == 0 ? 0 : expiry - hotReloadBeforeExpiryMs(); } catch (GeneralSecurityException e) { throw new IgniteException("Failed to read the certificates of the HTTPS connector", e); } } + /** @return How long before the certificates expire hot reload becomes due, in milliseconds. */ + private long hotReloadBeforeExpiryMs() { + return hotReloadSettings == null ? DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS : hotReloadSettings.getHotReloadBeforeExpiryMs(); + } + /** * Reloads the factory and, if loading fails, restores the state that new connections used before, if there was one. * Runs under the factory lock inside {@code unload(...)}, and always throws {@link SkipUnload}. diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index c4d9cf13b6987..929d72ea9334a 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -22,6 +22,7 @@ import java.nio.file.Path; import java.security.KeyStore; import java.security.cert.Certificate; +import java.security.cert.X509Certificate; import java.util.Deque; import java.util.List; import java.util.concurrent.ConcurrentLinkedDeque; @@ -209,32 +210,67 @@ public void testHotReloadedKeysSurviveFailedManualReload() throws Exception { * Given: a custom Jetty factory has loaded certificate A, valid for 30 days. * When: the factory reloads by itself and gets certificate B, which was issued 20 hours ago and expires in an hour. * Then its source fails, and Ignite reloads the factory. - * Then: the factory reports the expiry of the certificate in use: in 30 days for A, in an hour for B. The failed reload - * keeps B's expiry. + * Then: the hot reload date comes 7 days before the certificate in use expires: 23 days ahead for A, 7 days before + * the expiry of B for B. The failed reload keeps B's date. */ @Test - public void testCertificatesExpiryFollowsKeysInUse() throws Exception { + public void testHotReloadTimeFollowsKeysInUse() throws Exception { SourceSslContextFactory.supply(fresh(), due(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); jettyFactory.start(); try { - assertEquals(now + DAYS.toMillis(30), factory.certificatesExpiry()); + assertEquals(now + DAYS.toMillis(23), factory.hotReloadTime()); jettyFactory.reload(f -> { }); - assertEquals(now + HOURS.toMillis(1), factory.certificatesExpiry()); + long dueB = now + HOURS.toMillis(1) - DAYS.toMillis(7); + + assertEquals(dueB, factory.hotReloadTime()); assertThrows(log, factory::init, IgniteException.class, "Source is unavailable"); - assertEquals(now + HOURS.toMillis(1), factory.certificatesExpiry()); + assertEquals(dueB, factory.hotReloadTime()); } finally { jettyFactory.stop(); } } + /** + * Given: the SSL factory of the REST connector disables hot reload and sets a lead time of an hour, and HTTPS serves + * a certificate that expires in 30 days. + * When: the node starts. + * Then: the HTTPS factory follows both settings: its hot reload is disabled, and its hot reload date comes an hour + * before the certificate expires. + */ + @Test + @WithSystemProperty(key = KEY_STORE_PATH, value = "") + public void testHttpsFollowsHotReloadSettingsOfRestConnectorFactory() throws Exception { + KeyStore keys = fresh(); + org.apache.ignite.ssl.SslContextFactory connectorFactory = new org.apache.ignite.ssl.SslContextFactory(); + + keyStoreFile(keys); + connectorFactory.setHotReloadEnabled(false); + connectorFactory.setHotReloadBeforeExpiryMs(HOURS.toMillis(1)); + + IgniteConfiguration cfg = jettyConfig("jetty/https.xml"); + + cfg.getConnectorConfiguration().setSslFactory(connectorFactory); + + IgniteEx node = startGrid(cfg); + ReloadableSslFactory https = (ReloadableSslFactory)node.context().ssl().factories().stream() + .filter(registered -> "HTTP REST".equals(registered.getValue())) + .findFirst() + .orElseThrow() + .getKey(); + long expiry = ((X509Certificate)keys.getCertificate(HOST)).getNotAfter().getTime(); + + assertFalse(https.isHotReloadEnabled()); + assertEquals(expiry - HOURS.toMillis(1), https.hotReloadTime()); + } + /** * Given: a custom Jetty factory has loaded its keys, and its source then throws an error instead of an exception. * When: Ignite reloads the factory. @@ -246,7 +282,7 @@ public void testErrorFromSourceKeepsLastWorkingKeys() throws Exception { SourceSslContextFactory.supply(fresh(), new NoClassDefFoundError("Key store provider")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); jettyFactory.start(); @@ -265,7 +301,7 @@ public void testErrorFromSourceKeepsLastWorkingKeys() throws Exception { * Given: a reload that Ignite did not start, such as one by Jetty's {@code KeyStoreScanner}, has failed and left * the custom Jetty factory without keys. * When: Ignite reloads the factory while the source still fails, and again after the source supplies certificate B. - * Then: the first reload reports the source error, and the certificates of the factory count as expired, so a scheduled + * Then: the first reload reports the source error, and the factory is due for hot reload right away, so a scheduled * check reloads it as the reload command does. The second reload installs B. */ @Test @@ -275,7 +311,7 @@ public void testReloadRecoversFactoryLeftWithoutKeys() throws Exception { SourceSslContextFactory.supply(fresh(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); jettyFactory.start(); @@ -283,9 +319,9 @@ public void testReloadRecoversFactoryLeftWithoutKeys() throws Exception { assertThrows(log, () -> jettyFactory.reload(f -> { }), Exception.class, "Source is unavailable"); assertThrows(log, factory::init, IgniteException.class, "Source is unavailable"); - long expiry = factory.certificatesExpiry(); + long hotReloadTime = factory.hotReloadTime(); - assertTrue(expiry > 0 && expiry <= System.currentTimeMillis()); + assertTrue(hotReloadTime > 0 && hotReloadTime <= System.currentTimeMillis()); SourceSslContextFactory.supply(b); factory.init(); @@ -316,7 +352,7 @@ public void testTrustStoreReloadKeepsConfiguredKeysAfterFailure() throws Excepti jettyFactory.setTrustStoreType("JKS"); jettyFactory.setTrustStorePassword(new String(PASSWORD)); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); jettyFactory.start(); @@ -363,7 +399,7 @@ public void testReloadCallsFactoryReloadOnce() throws Exception { jettyFactory.setKeyStore(fresh()); jettyFactory.setKeyStorePassword(new String(PASSWORD)); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory); + ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); jettyFactory.start(); From 815381e266356958d84e481ebb946ad5c7471ace Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Thu, 26 Nov 2026 14:12:23 +0300 Subject: [PATCH 44/53] IGNITE-29212 Tidy up the factory hot reload switch after self-review Both reloadable factories decide for themselves whether hot reload is enabled, so the interface no longer gives a default. The registry test for a failed expiry read after a manual reload now uses the HTTP REST factory, the only one that can fail that read. The warning names the next check as nextAttempt, like the warning of a failed check. The TLS guide says that disabling hot reload on a factory stops it for every transport that uses this factory. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/security/ssl-tls.adoc | 3 ++- .../processors/ssl/ReloadableSslFactory.java | 4 +-- .../processors/ssl/SslFactoryRegistry.java | 2 +- .../ssl/SslFactoryRegistryTest.java | 26 ++++++++++--------- 4 files changed, 18 insertions(+), 17 deletions(-) diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index f80ec5c9f337d..f005af319a88d 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -203,7 +203,8 @@ It does not update external client applications. === Disable Hot Reload Hot reload is enabled by default. -To disable it for a transport, disable it on the transport's factory before starting the node: +To disable it, call `setHotReloadEnabled(false)` on the factory before starting the node. +Hot reload stops for every transport that uses this factory, and other factories keep it: [source,java] ---- diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index 9ce105898653e..527b9059b5301 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -49,9 +49,7 @@ public interface ReloadableSslFactory extends Factory { public long hotReloadTime(); /** @return Whether the registry reloads the factory before its certificates expire. Manual reload works either way. */ - public default boolean isHotReloadEnabled() { - return true; - } + public boolean isHotReloadEnabled(); /** * @param store Loaded key store. diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index f6d69ac240865..638b43b1a6ca8 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -294,7 +294,7 @@ private synchronized void reload() { } catch (RuntimeException e) { log.warning("TLS hot reload could not read certificate expiry after manual reload [transports=" + transports - + ", nextCheck=" + new Date(System.currentTimeMillis() + CHECK_PERIOD) + ']', e); + + ", nextAttempt=" + new Date(System.currentTimeMillis() + CHECK_PERIOD) + ']', e); scheduleCheck(CHECK_PERIOD); diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index ab1f14753baef..4ecd965b9357a 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -76,7 +76,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.RETURNS_DEFAULTS; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; @@ -458,26 +457,28 @@ public void testManualReloadSchedulesCheckAtHotReloadTime() throws Exception { } /** - * Given: a factory fails to report its hot reload time once, and then reports one that comes in 30 minutes. + * Given: the HTTP REST factory fails to read its certificates once, and then reports a hot reload time that comes + * in 30 minutes. * When: a manual reload loads the factory, and the next check runs. * Then: the reload succeeds and schedules a check in an hour, and that check schedules the next one in 30 minutes. */ @Test public void testManualReloadRetriesFailedReadOfHotReloadTime() { - when(factory.isHotReloadEnabled()).thenReturn(true); - when(factory.hotReloadTime()).thenThrow(new IgniteException("Certificate expiry unavailable")) + ReloadableSslFactory rest = httpRestFactory(); + + when(rest.hotReloadTime()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")) .thenReturn(System.currentTimeMillis() + MINUTES.toMillis(30)); - registry.register("communication", factory); + registry.register("HTTP REST", rest); registry.onKernalStart(true); - registry.reload(factory); + registry.reload(rest); assertEquals(HOURS.toMillis(1), nextCheckDelay()); runChecks(); assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); - verify(factory).init(); + verify(rest).init(); } /** @@ -1117,12 +1118,13 @@ private static void enableHotReload(SslContextFactory factory, long hotReloadTim when(factory.hotReloadTime()).thenReturn(hotReloadTime); } - /** - * @return Mock of a factory that is not an Ignite SSL context factory, such as the one of HTTP REST. It keeps the - * default methods of {@link ReloadableSslFactory}, so hot reload is enabled for it. - */ + /** @return Mock of a factory with hot reload enabled that is not an Ignite SSL context factory, such as the one of HTTP REST. */ private static ReloadableSslFactory httpRestFactory() { - return mock(ReloadableSslFactory.class, CALLS_REAL_METHODS); + ReloadableSslFactory factory = mock(ReloadableSslFactory.class); + + when(factory.isHotReloadEnabled()).thenReturn(true); + + return factory; } /** @return Hot reload time that has already come. */ From e31545b68de2e9d24a694f9abe8cb503b1138d7d Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Thu, 26 Nov 2026 16:20:29 +0300 Subject: [PATCH 45/53] IGNITE-29212 Take the HTTPS hot reload settings from the Jetty factory The HTTP REST endpoint took its hot reload switch and lead time from the SSL factory of binary REST, or from the node's factory. So an operator could not turn hot reload off for one problematic HTTPS source and keep it for binary REST, or for discovery and communication. The Jetty factory of the HTTPS connector now reports its own settings through the new public interface org.apache.ignite.ssl.ReloadableJettySslFactory in ignite-rest-http. A custom subclass of SslContextFactory.Server implements it and has setters, so jetty.xml can set both properties on the factory. Other Jetty factories keep hot reload enabled with the 7-day lead time, and existing jetty.xml files work unchanged. The internal adapter is renamed to JettySslFactoryAdapter, and the REST protocol classes no longer share the connector factory lookup. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/restapi.adoc | 49 ++++- docs/_docs/security/ssl-tls.adoc | 4 +- .../protocols/GridRestProtocolAdapter.java | 9 - .../protocols/tcp/GridTcpRestProtocol.java | 11 +- .../http/jetty/GridJettyRestProtocol.java | 6 +- ...ctory.java => JettySslFactoryAdapter.java} | 18 +- .../ignite/ssl/ReloadableJettySslFactory.java | 36 ++++ .../http/jetty/JettyRestHttpsReloadTest.java | 174 +++++++++++++----- .../META-INF/jetty/https-source-manual.xml | 35 ++++ 9 files changed, 273 insertions(+), 69 deletions(-) rename modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/{ReloadableJettySslFactory.java => JettySslFactoryAdapter.java} (89%) create mode 100644 modules/rest-http/src/main/java/org/apache/ignite/ssl/ReloadableJettySslFactory.java create mode 100644 modules/rest-http/src/test/resources/META-INF/jetty/https-source-manual.xml diff --git a/docs/_docs/restapi.adoc b/docs/_docs/restapi.adoc index 4bc17a88e6337..473fce9741a62 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -111,8 +111,53 @@ Both the standard Jetty factory and custom subclasses of `SslContextFactory.Serv After you replace the stores, run the link:tools/control-script#reloading-tls-certificates[`--ssl reload` command]. The node also reloads the stores automatically before its certificates expire, as described in link:security/ssl-tls#automatic-certificate-hot-reload[Automatic Certificate Hot Reload]. -Hot reload of the endpoint follows the `hotReloadEnabled` and `hotReloadBeforeExpiryMs` settings of the REST connector's SSL factory: the one set by `ConnectorConfiguration.setSslFactory(...)`, or the node's `IgniteConfiguration.setSslContextFactory(...)` if the connector sets none. -If there is no such factory, or it does not extend `AbstractSslContextFactory`, hot reload is enabled with a lead time of 7 days. +By default, hot reload of the Jetty factory is enabled and becomes due 7 days before the earliest certificate expiry in its private key chains. +To change these settings for a factory, configure it with your own subclass of `SslContextFactory.Server` that implements `org.apache.ignite.ssl.ReloadableJettySslFactory` from the `ignite-rest-http` module. +The interface has getters for two properties: `hotReloadEnabled` and `hotReloadBeforeExpiryMs`, the lead time in milliseconds, which must be positive. +Add setters for them, so that the Jetty XML file can set them: + +[source,java] +---- +public class MySslContextFactory extends SslContextFactory.Server implements ReloadableJettySslFactory { + private boolean hotReloadEnabled = true; + + private long hotReloadBeforeExpiryMs = AbstractSslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; + + @Override public boolean isHotReloadEnabled() { + return hotReloadEnabled; + } + + public void setHotReloadEnabled(boolean hotReloadEnabled) { + this.hotReloadEnabled = hotReloadEnabled; + } + + @Override public long getHotReloadBeforeExpiryMs() { + return hotReloadBeforeExpiryMs; + } + + public void setHotReloadBeforeExpiryMs(long hotReloadBeforeExpiryMs) { + this.hotReloadBeforeExpiryMs = hotReloadBeforeExpiryMs; + } +} +---- + +Then set the properties on the factory in the Jetty XML file: + +[source,xml] +---- + + + /opt/ignite/config/https.jks + changeit + false + + +---- + +These settings apply only to this factory: other transports keep their own hot reload settings. +Changing them requires a node restart. +The reload command reloads the factory either way. + Each reload asks the Jetty factory to load its stores again. New connections use the replacement certificates; established connections stay open. If loading fails, the endpoint keeps its current keys and trust settings, and new connections keep working with them. diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index f005af319a88d..7e877d77c8316 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -213,7 +213,7 @@ factory.setHotReloadEnabled(false); Changing this setting requires a node restart. The reload command still reloads the factory. -The HTTP REST endpoint follows this setting of the REST connector's SSL factory, as described in link:restapi#https[HTTPS]. +For the HTTP REST endpoint, set this property on its Jetty factory, as described in link:restapi#https[HTTPS]. The `SslContextFactory` of Ignite.NET has no `hotReloadEnabled` or `hotReloadBeforeExpiryMs` property. To set them for a .NET node, define the SSL factory in the Spring XML file set by `IgniteConfiguration.SpringConfigUrl`. @@ -243,7 +243,7 @@ All checks share one thread, so a slow certificate source can delay checks for o For each factory, hot reload becomes due `hotReloadBeforeExpiryMs` before the earliest certificate expiry in its private key chains. This includes issuing certificates. The default lead time is 7 days. -For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded, and the lead time from the REST connector's SSL factory, as described in link:restapi#https[HTTPS]. +For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded, and the lead time from the same factory, as described in link:restapi#https[HTTPS]. The first check at or after that date attempts a reload, including the startup check. Allow enough time before expiry to supply the replacements and load the stores. Keep the lead time shorter than the lifetime of the replacement certificates, or they will already be due when loaded. diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java index 0f4d40eb6dd7e..0a639c4b1edc6 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/GridRestProtocolAdapter.java @@ -27,8 +27,6 @@ import java.util.Collection; import java.util.Collections; import java.util.StringTokenizer; -import javax.cache.configuration.Factory; -import javax.net.ssl.SSLContext; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.configuration.ConnectorConfiguration; @@ -151,13 +149,6 @@ protected ConnectorConfiguration config() { return ctx.config().getConnectorConfiguration(); } - /** @return SSL context factory that the connector configuration sets, or the node's one if the connector sets none. */ - protected Factory sslContextFactory() { - Factory factory = config().getSslFactory(); - - return factory != null ? factory : ctx.config().getSslContextFactory(); - } - /** {@inheritDoc} */ @Override public Collection> getProperties() { try { diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java index 9eb169a41121d..d7e7328adca83 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/rest/protocols/tcp/GridTcpRestProtocol.java @@ -168,7 +168,7 @@ private GridNioFilter[] makeFilters(ConnectorConfiguration cfg) throws SSLExcept if (!cfg.isSslEnabled()) return new GridNioFilter[] { codec }; - Factory sslCtxFactory = sslContextFactory(); + Factory sslCtxFactory = sslContextFactory(cfg); if (sslCtxFactory == null) // Thrown SSL exception instead of IgniteCheckedException for writing correct warning message into log. @@ -187,6 +187,13 @@ private GridNioFilter[] makeFilters(ConnectorConfiguration cfg) throws SSLExcept return new GridNioFilter[] { codec, sslFilter }; } + /** */ + private Factory sslContextFactory(ConnectorConfiguration cfg) { + Factory factory = cfg.getSslFactory(); + + return factory != null ? factory : ctx.config().getSslContextFactory(); + } + /** * Tries to start server with given parameters. * @@ -231,7 +238,7 @@ private boolean startTcpServer(InetAddress hostAddr, int port, GridNioServerList ctx.ports().registerPort(port, IgnitePortProtocol.TCP, getClass()); if (cfg.isSslEnabled()) - ctx.ssl().register("binary REST", sslContextFactory()); + ctx.ssl().register("binary REST", sslContextFactory(cfg)); return true; } diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java index c1c19b672d8cb..7c3390fced484 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java @@ -169,17 +169,17 @@ else if (log.isDebugEnabled()) int portRange = config().getPortRange(); int lastPort = portRange == 0 ? initPort : initPort + portRange - 1; - Collection sslFactories = connector.getContainedBeans(SslConnectionFactory.class).stream() + Collection sslFactories = connector.getContainedBeans(SslConnectionFactory.class).stream() .map(SslConnectionFactory::getSslContextFactory) .distinct() - .map(factory -> new ReloadableJettySslFactory(factory, sslContextFactory())) + .map(JettySslFactoryAdapter::new) .toList(); for (port = initPort; port <= lastPort; port++) { connector.setPort(port); if (startJetty()) { - for (ReloadableJettySslFactory sslFactory : sslFactories) + for (JettySslFactoryAdapter sslFactory : sslFactories) ctx.ssl().register("HTTP REST", sslFactory); if (log.isInfoEnabled()) { diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java similarity index 89% rename from modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java rename to modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java index ba1ceb55da25e..5f0e4089b6f62 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java @@ -25,6 +25,7 @@ import org.apache.ignite.IgniteException; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; import org.apache.ignite.ssl.AbstractSslContextFactory; +import org.apache.ignite.ssl.ReloadableJettySslFactory; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.jetbrains.annotations.Nullable; @@ -32,10 +33,8 @@ /** * TLS factory of the Jetty HTTPS connector. A failed reload leaves the previous keys and trust settings in use. - * Hot reload follows {@link AbstractSslContextFactory#isHotReloadEnabled()} and - * {@link AbstractSslContextFactory#getHotReloadBeforeExpiryMs()} of the SSL factory of the REST connector. If there is - * no such factory, or it is not an {@link AbstractSslContextFactory}, hot reload is enabled with the lead time - * {@link AbstractSslContextFactory#DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. + * Hot reload follows the settings of the Jetty factory if it implements {@link ReloadableJettySslFactory}. Otherwise + * hot reload is enabled with the lead time {@link AbstractSslContextFactory#DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. *

* Jetty's factory guards its TLS state with an internal lock: it loads the state under this lock, and new connections * take the state under it too. Before loading a replacement, Jetty clears the state. So that new connections never see @@ -53,7 +52,7 @@ * these settings. So the adapter cannot keep a context or store that code sets on the running factory: a failed reload * drops it. */ -class ReloadableJettySslFactory implements ReloadableSslFactory { +class JettySslFactoryAdapter implements ReloadableSslFactory { /** The adapter is serializable only because {@link Factory} is. Serializing it fails, as Jetty's factory is not serializable. */ private static final long serialVersionUID = 0L; @@ -63,20 +62,19 @@ class ReloadableJettySslFactory implements ReloadableSslFactory { /** State set in {@code jetty.xml}. The factory loads a {@code null} part from its configured source. */ private final TlsState configured; - /** SSL factory of the REST connector with the hot reload settings, or {@code null} to use the defaults. */ - @Nullable private final AbstractSslContextFactory hotReloadSettings; + /** Hot reload settings of the factory, or {@code null} to use the defaults. */ + @Nullable private final ReloadableJettySslFactory hotReloadSettings; /** * @param factory TLS factory of the HTTPS connector before startup, when its getters return the state set in {@code jetty.xml}. - * @param connectorFactory SSL factory of the REST connector. */ - ReloadableJettySslFactory(SslContextFactory factory, @Nullable Factory connectorFactory) { + JettySslFactoryAdapter(SslContextFactory factory) { assert !factory.isStarted(); this.factory = factory; configured = new TlsState(factory); - hotReloadSettings = connectorFactory instanceof AbstractSslContextFactory sslFactory ? sslFactory : null; + hotReloadSettings = factory instanceof ReloadableJettySslFactory settings ? settings : null; } /** {@inheritDoc} */ diff --git a/modules/rest-http/src/main/java/org/apache/ignite/ssl/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/ssl/ReloadableJettySslFactory.java new file mode 100644 index 0000000000000..5018c286f2544 --- /dev/null +++ b/modules/rest-http/src/main/java/org/apache/ignite/ssl/ReloadableJettySslFactory.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.apache.ignite.ssl; + +/** + * Hot reload settings of a Jetty SSL context factory that serves HTTPS for the HTTP REST endpoint. To change the settings + * of a factory, implement this interface in a subclass of Jetty's {@code SslContextFactory.Server}, add setters for both + * properties, and set them on the factory in the Jetty XML file. A factory that does not implement this interface keeps + * hot reload enabled with the lead time {@link AbstractSslContextFactory#DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. + * The reload command reloads the factory either way. + */ +public interface ReloadableJettySslFactory { + /** @return Whether Ignite reloads the factory before its certificates expire. Changes require a node restart. */ + public boolean isHotReloadEnabled(); + + /** + * @return How long before the earliest certificate expiry in the private key chains hot reload becomes due, + * in milliseconds. Must be positive. + */ + public long getHotReloadBeforeExpiryMs(); +} diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index 929d72ea9334a..385838f134d6e 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -22,7 +22,6 @@ import java.nio.file.Path; import java.security.KeyStore; import java.security.cert.Certificate; -import java.security.cert.X509Certificate; import java.util.Deque; import java.util.List; import java.util.concurrent.ConcurrentLinkedDeque; @@ -41,6 +40,7 @@ import org.apache.ignite.internal.management.api.NoArg; import org.apache.ignite.internal.management.ssl.SslReloadCommand; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; +import org.apache.ignite.ssl.ReloadableJettySslFactory; import org.apache.ignite.ssl.TestCertificateAuthority; import org.apache.ignite.testframework.junits.WithSystemProperty; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; @@ -52,9 +52,12 @@ import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; +import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.ignite.IgniteSystemProperties.IGNITE_JETTY_PORT; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REST_JETTY_PORT; +import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REST_TCP_PORT; import static org.apache.ignite.internal.processors.rest.protocols.http.jetty.GridJettyRestProtocol.DFLT_JETTY_PORT; +import static org.apache.ignite.ssl.AbstractSslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD; import static org.apache.ignite.ssl.TestCertificateAuthority.save; import static org.apache.ignite.testframework.GridTestUtils.assertThrows; @@ -65,8 +68,9 @@ * TLS reload of the HTTP REST connector configured in Jetty XML. The standard Jetty factory reads its key store from a file * and requires an SNI host name ({@code jetty/https.xml}); {@code jetty/https-detector.xml} reads the same file through * a connector that accepts HTTP and HTTPS on one port. The custom factory ({@code jetty/https-source.xml}) takes its - * key stores from {@link SourceSslContextFactory}. The connectors in these files set no port, so the tests set - * {@code IGNITE_JETTY_PORT}; otherwise the node would publish port 0. + * key stores from {@link SourceSslContextFactory}; {@code jetty/https-source-manual.xml} configures the same source + * with hot reload disabled. The connectors in these files set no port, so the tests set {@code IGNITE_JETTY_PORT}; + * otherwise the node would publish port 0. */ @WithSystemProperty(key = IGNITE_JETTY_PORT, value = DFLT_JETTY_PORT) public class JettyRestHttpsReloadTest extends GridCommonAbstractTest { @@ -218,7 +222,7 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { SourceSslContextFactory.supply(fresh(), due(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); + JettySslFactoryAdapter factory = new JettySslFactoryAdapter(jettyFactory); jettyFactory.start(); @@ -239,36 +243,74 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { } /** - * Given: the SSL factory of the REST connector disables hot reload and sets a lead time of an hour, and HTTPS serves - * a certificate that expires in 30 days. - * When: the node starts. - * Then: the HTTPS factory follows both settings: its hot reload is disabled, and its hot reload date comes an hour - * before the certificate expires. + * Given: binary REST and HTTPS use separate factories and key stores, and the Jetty XML file disables hot reload + * of the HTTPS factory. Both serve certificate A. A of HTTPS is due for hot reload at start, and A of binary + * REST in 5 seconds, so a check of HTTPS would run before the one of binary REST. Both sources hold + * replacement B. + * When: hot reload loads B for binary REST, and then the operator runs the reload command. + * Then: after hot reload, a new binary REST client sees B, and a new HTTPS client still sees A. After the command, + * a new HTTPS client sees B. */ @Test - @WithSystemProperty(key = KEY_STORE_PATH, value = "") - public void testHttpsFollowsHotReloadSettingsOfRestConnectorFactory() throws Exception { - KeyStore keys = fresh(); - org.apache.ignite.ssl.SslContextFactory connectorFactory = new org.apache.ignite.ssl.SslContextFactory(); + public void testHttpsFactoryWithHotReloadDisabledWaitsForReloadCommand() throws Exception { + KeyStore binaryA = ca.keyStore(HOST, now - HOURS.toMillis(1), now + DAYS.toMillis(7) + SECONDS.toMillis(5)); + KeyStore binaryB = fresh(); + KeyStore httpsA = due(); + KeyStore httpsB = fresh(); + Path binaryKeys = tmp.newFile("binary.jks").toPath(); + org.apache.ignite.ssl.SslContextFactory binaryFactory = new org.apache.ignite.ssl.SslContextFactory(); + + save(binaryA, binaryKeys); + binaryFactory.setKeyStoreFilePath(binaryKeys.toString()); + binaryFactory.setKeyStorePassword(PASSWORD); + binaryFactory.setTrustManagers(org.apache.ignite.ssl.SslContextFactory.getDisabledTrustManager()); + binaryFactory.create(); + save(binaryB, binaryKeys); + SourceSslContextFactory.supply(httpsA, httpsB); + + IgniteConfiguration cfg = jettyConfig("jetty/https-source-manual.xml"); + + cfg.getConnectorConfiguration().setSslEnabled(true).setSslFactory(binaryFactory); + + IgniteEx node = startGrid(cfg); + Certificate binaryReplacement = binaryB.getCertificate(HOST); + + assertTrue(waitForCondition(() -> { + try { + return binaryReplacement.equals(binaryRestCertificate(node)); + } + catch (Exception e) { + throw new AssertionError(e); + } + }, TIMEOUT_MS)); - keyStoreFile(keys); - connectorFactory.setHotReloadEnabled(false); - connectorFactory.setHotReloadBeforeExpiryMs(HOURS.toMillis(1)); + assertEquals(httpsA.getCertificate(HOST), serverCertificate(node)); + assertTrue(reload(node).contains(": HTTP REST: reloaded")); + assertEquals(httpsB.getCertificate(HOST), serverCertificate(node)); + } - IgniteConfiguration cfg = jettyConfig("jetty/https.xml"); + /** + * Given: a custom Jetty factory that implements {@link ReloadableJettySslFactory} sets a lead time of an hour, and + * has loaded a certificate valid for 30 days. + * When: Ignite reads the hot reload time of the factory. + * Then: hot reload becomes due an hour before the certificate expires. + */ + @Test + public void testHotReloadTimeUsesLeadTimeOfJettyFactory() throws Exception { + SourceSslContextFactory.supply(fresh()); - cfg.getConnectorConfiguration().setSslFactory(connectorFactory); + ConfigurableSourceSslContextFactory jettyFactory = new ConfigurableSourceSslContextFactory(); + JettySslFactoryAdapter factory = new JettySslFactoryAdapter(jettyFactory); - IgniteEx node = startGrid(cfg); - ReloadableSslFactory https = (ReloadableSslFactory)node.context().ssl().factories().stream() - .filter(registered -> "HTTP REST".equals(registered.getValue())) - .findFirst() - .orElseThrow() - .getKey(); - long expiry = ((X509Certificate)keys.getCertificate(HOST)).getNotAfter().getTime(); - - assertFalse(https.isHotReloadEnabled()); - assertEquals(expiry - HOURS.toMillis(1), https.hotReloadTime()); + jettyFactory.setHotReloadBeforeExpiryMs(HOURS.toMillis(1)); + jettyFactory.start(); + + try { + assertEquals(now + DAYS.toMillis(30) - HOURS.toMillis(1), factory.hotReloadTime()); + } + finally { + jettyFactory.stop(); + } } /** @@ -282,7 +324,7 @@ public void testErrorFromSourceKeepsLastWorkingKeys() throws Exception { SourceSslContextFactory.supply(fresh(), new NoClassDefFoundError("Key store provider")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); + JettySslFactoryAdapter factory = new JettySslFactoryAdapter(jettyFactory); jettyFactory.start(); @@ -311,7 +353,7 @@ public void testReloadRecoversFactoryLeftWithoutKeys() throws Exception { SourceSslContextFactory.supply(fresh(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); + JettySslFactoryAdapter factory = new JettySslFactoryAdapter(jettyFactory); jettyFactory.start(); @@ -352,7 +394,7 @@ public void testTrustStoreReloadKeepsConfiguredKeysAfterFailure() throws Excepti jettyFactory.setTrustStoreType("JKS"); jettyFactory.setTrustStorePassword(new String(PASSWORD)); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); + JettySslFactoryAdapter factory = new JettySslFactoryAdapter(jettyFactory); jettyFactory.start(); @@ -399,7 +441,7 @@ public void testReloadCallsFactoryReloadOnce() throws Exception { jettyFactory.setKeyStore(fresh()); jettyFactory.setKeyStorePassword(new String(PASSWORD)); - ReloadableJettySslFactory factory = new ReloadableJettySslFactory(jettyFactory, null); + JettySslFactoryAdapter factory = new JettySslFactoryAdapter(jettyFactory); jettyFactory.start(); @@ -448,17 +490,9 @@ private static String reload(IgniteEx node) throws Exception { * the host name. The JDK sends no SNI host name for {@code localhost} by itself, so the client sets it. */ private Certificate serverCertificate(IgniteEx node) throws Exception { - TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - - tmf.init(ca.trustStore()); - - SSLContext client = SSLContext.getInstance("TLS"); - - client.init(null, tmf.getTrustManagers(), null); - int port = node.localNode().attribute(ATTR_REST_JETTY_PORT); - try (SSLSocket sock = (SSLSocket)client.getSocketFactory().createSocket(HOST, port)) { + try (SSLSocket sock = (SSLSocket)clientContext().getSocketFactory().createSocket(HOST, port)) { SSLParameters params = sock.getSSLParameters(); params.setServerNames(List.of(new SNIHostName(HOST))); @@ -469,6 +503,30 @@ private Certificate serverCertificate(IgniteEx node) throws Exception { } } + /** Returns the certificate that binary REST presents to a new client that trusts the test CA. */ + private Certificate binaryRestCertificate(IgniteEx node) throws Exception { + int port = node.localNode().attribute(ATTR_REST_TCP_PORT); + + try (SSLSocket sock = (SSLSocket)clientContext().getSocketFactory().createSocket(node.configuration().getLocalHost(), port)) { + sock.startHandshake(); + + return sock.getSession().getPeerCertificates()[0]; + } + } + + /** @return Client context that trusts the test CA. */ + private SSLContext clientContext() throws Exception { + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + + tmf.init(ca.trustStore()); + + SSLContext client = SSLContext.getInstance("TLS"); + + client.init(null, tmf.getTrustManagers(), null); + + return client; + } + /** * Custom Jetty factory that takes its key stores from a source in memory instead of a file. * Each load takes the next key store or throws the next exception or error that the test supplied. The last one repeats. @@ -506,4 +564,38 @@ public SourceSslContextFactory() throws Exception { return (KeyStore)load; } } + + /** Custom Jetty factory of {@link SourceSslContextFactory} with hot reload settings that the Jetty XML file can set. */ + public static class ConfigurableSourceSslContextFactory extends SourceSslContextFactory implements ReloadableJettySslFactory { + /** */ + private boolean hotReloadEnabled = true; + + /** */ + private long hotReloadBeforeExpiryMs = DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; + + /** */ + public ConfigurableSourceSslContextFactory() throws Exception { + // No-op. + } + + /** {@inheritDoc} */ + @Override public boolean isHotReloadEnabled() { + return hotReloadEnabled; + } + + /** */ + public void setHotReloadEnabled(boolean hotReloadEnabled) { + this.hotReloadEnabled = hotReloadEnabled; + } + + /** {@inheritDoc} */ + @Override public long getHotReloadBeforeExpiryMs() { + return hotReloadBeforeExpiryMs; + } + + /** */ + public void setHotReloadBeforeExpiryMs(long hotReloadBeforeExpiryMs) { + this.hotReloadBeforeExpiryMs = hotReloadBeforeExpiryMs; + } + } } diff --git a/modules/rest-http/src/test/resources/META-INF/jetty/https-source-manual.xml b/modules/rest-http/src/test/resources/META-INF/jetty/https-source-manual.xml new file mode 100644 index 0000000000000..34b423914d689 --- /dev/null +++ b/modules/rest-http/src/test/resources/META-INF/jetty/https-source-manual.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + false + + + + + + From 3808c238765b3fdad9b474b2da37f6e0ecbf93e7 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Thu, 26 Nov 2026 16:37:06 +0300 Subject: [PATCH 46/53] IGNITE-29212 Move the Jetty hot reload settings to their own package ReloadableJettySslFactory sat in org.apache.ignite.ssl, a package that ignite-core already ships. With both jars on the module path, Java fails with ResolutionException before Ignite starts, and an OSGi loader takes the package from ignite-commons and cannot find the interface. The interface now lives in org.apache.ignite.ssl.jetty, which the Security group of the Javadoc includes. The two-transport test lets the HTTPS source load only at start and on the reload command, so a later automatic load of HTTPS makes the command fail instead of passing unnoticed. The example factory in the REST docs rejects a lead time that is not positive, as the Ignite factory does. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/restapi.adoc | 5 +++- .../http/jetty/JettySslFactoryAdapter.java | 2 +- .../ReloadableJettySslFactory.java | 4 +++- .../apache/ignite/ssl/jetty/package-info.java | 23 +++++++++++++++++++ .../http/jetty/JettyRestHttpsReloadTest.java | 7 +++--- parent/pom.xml | 2 +- 6 files changed, 36 insertions(+), 7 deletions(-) rename modules/rest-http/src/main/java/org/apache/ignite/ssl/{ => jetty}/ReloadableJettySslFactory.java (94%) create mode 100644 modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/package-info.java diff --git a/docs/_docs/restapi.adoc b/docs/_docs/restapi.adoc index 473fce9741a62..3df3f3dfdd213 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -112,7 +112,7 @@ Both the standard Jetty factory and custom subclasses of `SslContextFactory.Serv After you replace the stores, run the link:tools/control-script#reloading-tls-certificates[`--ssl reload` command]. The node also reloads the stores automatically before its certificates expire, as described in link:security/ssl-tls#automatic-certificate-hot-reload[Automatic Certificate Hot Reload]. By default, hot reload of the Jetty factory is enabled and becomes due 7 days before the earliest certificate expiry in its private key chains. -To change these settings for a factory, configure it with your own subclass of `SslContextFactory.Server` that implements `org.apache.ignite.ssl.ReloadableJettySslFactory` from the `ignite-rest-http` module. +To change these settings for a factory, configure it with your own subclass of `SslContextFactory.Server` that implements `org.apache.ignite.ssl.jetty.ReloadableJettySslFactory` from the `ignite-rest-http` module. The interface has getters for two properties: `hotReloadEnabled` and `hotReloadBeforeExpiryMs`, the lead time in milliseconds, which must be positive. Add setters for them, so that the Jetty XML file can set them: @@ -136,6 +136,9 @@ public class MySslContextFactory extends SslContextFactory.Server implements Rel } public void setHotReloadBeforeExpiryMs(long hotReloadBeforeExpiryMs) { + if (hotReloadBeforeExpiryMs <= 0) + throw new IllegalArgumentException("hotReloadBeforeExpiryMs must be positive: " + hotReloadBeforeExpiryMs); + this.hotReloadBeforeExpiryMs = hotReloadBeforeExpiryMs; } } diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java index 5f0e4089b6f62..bd4ce0eac424a 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java @@ -25,7 +25,7 @@ import org.apache.ignite.IgniteException; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; import org.apache.ignite.ssl.AbstractSslContextFactory; -import org.apache.ignite.ssl.ReloadableJettySslFactory; +import org.apache.ignite.ssl.jetty.ReloadableJettySslFactory; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.jetbrains.annotations.Nullable; diff --git a/modules/rest-http/src/main/java/org/apache/ignite/ssl/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/ReloadableJettySslFactory.java similarity index 94% rename from modules/rest-http/src/main/java/org/apache/ignite/ssl/ReloadableJettySslFactory.java rename to modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/ReloadableJettySslFactory.java index 5018c286f2544..dbe26848d4ecc 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/ssl/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/ReloadableJettySslFactory.java @@ -15,7 +15,9 @@ * limitations under the License. */ -package org.apache.ignite.ssl; +package org.apache.ignite.ssl.jetty; + +import org.apache.ignite.ssl.AbstractSslContextFactory; /** * Hot reload settings of a Jetty SSL context factory that serves HTTPS for the HTTP REST endpoint. To change the settings diff --git a/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/package-info.java b/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/package-info.java new file mode 100644 index 0000000000000..f1918e167b916 --- /dev/null +++ b/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/package-info.java @@ -0,0 +1,23 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ + +/** + * + * Contains hot reload settings of Jetty SSL context factories that serve HTTPS for the HTTP REST endpoint. + */ + +package org.apache.ignite.ssl.jetty; diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index 385838f134d6e..d215f7d0ee9d8 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -40,8 +40,8 @@ import org.apache.ignite.internal.management.api.NoArg; import org.apache.ignite.internal.management.ssl.SslReloadCommand; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; -import org.apache.ignite.ssl.ReloadableJettySslFactory; import org.apache.ignite.ssl.TestCertificateAuthority; +import org.apache.ignite.ssl.jetty.ReloadableJettySslFactory; import org.apache.ignite.testframework.junits.WithSystemProperty; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.eclipse.jetty.util.resource.Resource; @@ -246,7 +246,8 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { * Given: binary REST and HTTPS use separate factories and key stores, and the Jetty XML file disables hot reload * of the HTTPS factory. Both serve certificate A. A of HTTPS is due for hot reload at start, and A of binary * REST in 5 seconds, so a check of HTTPS would run before the one of binary REST. Both sources hold - * replacement B. + * replacement B. The HTTPS source fails any load after the second one, so an automatic load of HTTPS before + * the command makes the command fail. * When: hot reload loads B for binary REST, and then the operator runs the reload command. * Then: after hot reload, a new binary REST client sees B, and a new HTTPS client still sees A. After the command, * a new HTTPS client sees B. @@ -266,7 +267,7 @@ public void testHttpsFactoryWithHotReloadDisabledWaitsForReloadCommand() throws binaryFactory.setTrustManagers(org.apache.ignite.ssl.SslContextFactory.getDisabledTrustManager()); binaryFactory.create(); save(binaryB, binaryKeys); - SourceSslContextFactory.supply(httpsA, httpsB); + SourceSslContextFactory.supply(httpsA, httpsB, new AssertionError("Unexpected third key store load")); IgniteConfiguration cfg = jettyConfig("jetty/https-source-manual.xml"); diff --git a/parent/pom.xml b/parent/pom.xml index 46cb1de7fe40b..429e2929b85bb 100644 --- a/parent/pom.xml +++ b/parent/pom.xml @@ -393,7 +393,7 @@ Security APIs - org.apache.ignite.plugin.security:org.apache.ignite.ssl:org.apache.ignite.spi.encryption* + org.apache.ignite.plugin.security:org.apache.ignite.ssl*:org.apache.ignite.spi.encryption* Maintenance and Monitoring APIs From c61f6722ef8521b2515a6cd49f3d0b31fd5612aa Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Thu, 26 Nov 2026 16:44:53 +0300 Subject: [PATCH 47/53] IGNITE-29212 Do not promise the check order in the two-transport test The 5 seconds until binary REST becomes due start when the test creates the certificate, before the node starts. On a slow start both are due at once, and binary REST may reload first. The test description now says that the order holds only on a usual start; the guard against a third load of the HTTPS source covers the rest. Co-Authored-By: Claude Opus 5.5 --- .../protocols/http/jetty/JettyRestHttpsReloadTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index d215f7d0ee9d8..6f3bf7b8f5de9 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -244,10 +244,10 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { /** * Given: binary REST and HTTPS use separate factories and key stores, and the Jetty XML file disables hot reload - * of the HTTPS factory. Both serve certificate A. A of HTTPS is due for hot reload at start, and A of binary - * REST in 5 seconds, so a check of HTTPS would run before the one of binary REST. Both sources hold - * replacement B. The HTTPS source fails any load after the second one, so an automatic load of HTTPS before - * the command makes the command fail. + * of the HTTPS factory. Both serve certificate A. A of HTTPS is due for hot reload at start. A of binary REST + * becomes due 5 seconds after the test creates it, so on a usual start binary REST reloads after any check of + * HTTPS at start. Both sources hold replacement B. The HTTPS source fails any load after the second one, so + * an automatic load of HTTPS before the command makes the command fail. * When: hot reload loads B for binary REST, and then the operator runs the reload command. * Then: after hot reload, a new binary REST client sees B, and a new HTTPS client still sees A. After the command, * a new HTTPS client sees B. From 13bf79b06bc759b0083e115f3b5905f2aa77b35c Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Thu, 26 Nov 2026 17:00:21 +0300 Subject: [PATCH 48/53] IGNITE-29212 Name the Jetty adapter and its variables after what they hold The adapter kept a hotReloadSettings field from the design where it held the SSL factory of the REST connector. It now held the same Jetty factory as the factory field, cast to ReloadableJettySslFactory. The adapter now checks the factory itself, and the field is gone. Variables that hold adapters are named adapter and adapters instead of factory and sslFactories, which read like the Jetty factories they wrap. The class description says that it is an adapter. Co-Authored-By: Claude Opus 5.5 --- .../http/jetty/GridJettyRestProtocol.java | 6 ++-- .../http/jetty/JettySslFactoryAdapter.java | 13 ++++--- .../http/jetty/JettyRestHttpsReloadTest.java | 36 +++++++++---------- 3 files changed, 27 insertions(+), 28 deletions(-) diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java index 7c3390fced484..c3e43a50ae29f 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/GridJettyRestProtocol.java @@ -169,7 +169,7 @@ else if (log.isDebugEnabled()) int portRange = config().getPortRange(); int lastPort = portRange == 0 ? initPort : initPort + portRange - 1; - Collection sslFactories = connector.getContainedBeans(SslConnectionFactory.class).stream() + Collection adapters = connector.getContainedBeans(SslConnectionFactory.class).stream() .map(SslConnectionFactory::getSslContextFactory) .distinct() .map(JettySslFactoryAdapter::new) @@ -179,8 +179,8 @@ else if (log.isDebugEnabled()) connector.setPort(port); if (startJetty()) { - for (JettySslFactoryAdapter sslFactory : sslFactories) - ctx.ssl().register("HTTP REST", sslFactory); + for (JettySslFactoryAdapter adapter : adapters) + ctx.ssl().register("HTTP REST", adapter); if (log.isInfoEnabled()) { log.info(startInfo()); diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java index bd4ce0eac424a..04554b7259bdb 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java @@ -32,7 +32,8 @@ import static org.apache.ignite.ssl.AbstractSslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; /** - * TLS factory of the Jetty HTTPS connector. A failed reload leaves the previous keys and trust settings in use. + * Adapter through which the SSL factory registry reloads the TLS factory of the Jetty HTTPS connector. A failed reload + * leaves the previous keys and trust settings in use. * Hot reload follows the settings of the Jetty factory if it implements {@link ReloadableJettySslFactory}. Otherwise * hot reload is enabled with the lead time {@link AbstractSslContextFactory#DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. *

@@ -62,9 +63,6 @@ class JettySslFactoryAdapter implements ReloadableSslFactory { /** State set in {@code jetty.xml}. The factory loads a {@code null} part from its configured source. */ private final TlsState configured; - /** Hot reload settings of the factory, or {@code null} to use the defaults. */ - @Nullable private final ReloadableJettySslFactory hotReloadSettings; - /** * @param factory TLS factory of the HTTPS connector before startup, when its getters return the state set in {@code jetty.xml}. */ @@ -74,7 +72,6 @@ class JettySslFactoryAdapter implements ReloadableSslFactory { this.factory = factory; configured = new TlsState(factory); - hotReloadSettings = factory instanceof ReloadableJettySslFactory settings ? settings : null; } /** {@inheritDoc} */ @@ -95,7 +92,7 @@ class JettySslFactoryAdapter implements ReloadableSslFactory { /** {@inheritDoc} */ @Override public boolean isHotReloadEnabled() { - return hotReloadSettings == null || hotReloadSettings.isHotReloadEnabled(); + return !(factory instanceof ReloadableJettySslFactory reloadable) || reloadable.isHotReloadEnabled(); } /** {@inheritDoc} */ @@ -118,7 +115,9 @@ class JettySslFactoryAdapter implements ReloadableSslFactory { /** @return How long before the certificates expire hot reload becomes due, in milliseconds. */ private long hotReloadBeforeExpiryMs() { - return hotReloadSettings == null ? DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS : hotReloadSettings.getHotReloadBeforeExpiryMs(); + return factory instanceof ReloadableJettySslFactory reloadable + ? reloadable.getHotReloadBeforeExpiryMs() + : DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; } /** diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index 6f3bf7b8f5de9..53572b5c692d2 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -222,20 +222,20 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { SourceSslContextFactory.supply(fresh(), due(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - JettySslFactoryAdapter factory = new JettySslFactoryAdapter(jettyFactory); + JettySslFactoryAdapter adapter = new JettySslFactoryAdapter(jettyFactory); jettyFactory.start(); try { - assertEquals(now + DAYS.toMillis(23), factory.hotReloadTime()); + assertEquals(now + DAYS.toMillis(23), adapter.hotReloadTime()); jettyFactory.reload(f -> { }); long dueB = now + HOURS.toMillis(1) - DAYS.toMillis(7); - assertEquals(dueB, factory.hotReloadTime()); - assertThrows(log, factory::init, IgniteException.class, "Source is unavailable"); - assertEquals(dueB, factory.hotReloadTime()); + assertEquals(dueB, adapter.hotReloadTime()); + assertThrows(log, adapter::init, IgniteException.class, "Source is unavailable"); + assertEquals(dueB, adapter.hotReloadTime()); } finally { jettyFactory.stop(); @@ -301,13 +301,13 @@ public void testHotReloadTimeUsesLeadTimeOfJettyFactory() throws Exception { SourceSslContextFactory.supply(fresh()); ConfigurableSourceSslContextFactory jettyFactory = new ConfigurableSourceSslContextFactory(); - JettySslFactoryAdapter factory = new JettySslFactoryAdapter(jettyFactory); + JettySslFactoryAdapter adapter = new JettySslFactoryAdapter(jettyFactory); jettyFactory.setHotReloadBeforeExpiryMs(HOURS.toMillis(1)); jettyFactory.start(); try { - assertEquals(now + DAYS.toMillis(30) - HOURS.toMillis(1), factory.hotReloadTime()); + assertEquals(now + DAYS.toMillis(30) - HOURS.toMillis(1), adapter.hotReloadTime()); } finally { jettyFactory.stop(); @@ -325,14 +325,14 @@ public void testErrorFromSourceKeepsLastWorkingKeys() throws Exception { SourceSslContextFactory.supply(fresh(), new NoClassDefFoundError("Key store provider")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - JettySslFactoryAdapter factory = new JettySslFactoryAdapter(jettyFactory); + JettySslFactoryAdapter adapter = new JettySslFactoryAdapter(jettyFactory); jettyFactory.start(); try { SSLContext ctx = jettyFactory.getSslContext(); - assertThrows(log, factory::init, IgniteException.class, "Key store provider"); + assertThrows(log, adapter::init, IgniteException.class, "Key store provider"); assertSame(ctx, jettyFactory.getSslContext()); } finally { @@ -354,20 +354,20 @@ public void testReloadRecoversFactoryLeftWithoutKeys() throws Exception { SourceSslContextFactory.supply(fresh(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); - JettySslFactoryAdapter factory = new JettySslFactoryAdapter(jettyFactory); + JettySslFactoryAdapter adapter = new JettySslFactoryAdapter(jettyFactory); jettyFactory.start(); try { assertThrows(log, () -> jettyFactory.reload(f -> { }), Exception.class, "Source is unavailable"); - assertThrows(log, factory::init, IgniteException.class, "Source is unavailable"); + assertThrows(log, adapter::init, IgniteException.class, "Source is unavailable"); - long hotReloadTime = factory.hotReloadTime(); + long hotReloadTime = adapter.hotReloadTime(); assertTrue(hotReloadTime > 0 && hotReloadTime <= System.currentTimeMillis()); SourceSslContextFactory.supply(b); - factory.init(); + adapter.init(); assertEquals(b.getCertificate(HOST), jettyFactory.getKeyStore().getCertificate(HOST)); } @@ -395,7 +395,7 @@ public void testTrustStoreReloadKeepsConfiguredKeysAfterFailure() throws Excepti jettyFactory.setTrustStoreType("JKS"); jettyFactory.setTrustStorePassword(new String(PASSWORD)); - JettySslFactoryAdapter factory = new JettySslFactoryAdapter(jettyFactory); + JettySslFactoryAdapter adapter = new JettySslFactoryAdapter(jettyFactory); jettyFactory.start(); @@ -404,14 +404,14 @@ public void testTrustStoreReloadKeepsConfiguredKeysAfterFailure() throws Excepti Files.writeString(trust, "not a trust store"); - assertThrows(log, factory::init, IgniteException.class, null); + assertThrows(log, adapter::init, IgniteException.class, null); assertSame(ctx, jettyFactory.getSslContext()); Certificate cert = keys.getCertificate(HOST); trusted.setCertificateEntry(HOST, cert); save(trusted, trust); - factory.init(); + adapter.init(); assertSame(keys, jettyFactory.getKeyStore()); assertEquals(cert, jettyFactory.getTrustStore().getCertificate(HOST)); @@ -442,12 +442,12 @@ public void testReloadCallsFactoryReloadOnce() throws Exception { jettyFactory.setKeyStore(fresh()); jettyFactory.setKeyStorePassword(new String(PASSWORD)); - JettySslFactoryAdapter factory = new JettySslFactoryAdapter(jettyFactory); + JettySslFactoryAdapter adapter = new JettySslFactoryAdapter(jettyFactory); jettyFactory.start(); try { - factory.init(); + adapter.init(); assertEquals(1, reloads.get()); } From 76e2ce42d403126100a24a0e52966b76de2c21c3 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Thu, 26 Nov 2026 17:11:39 +0300 Subject: [PATCH 49/53] IGNITE-29212 Call the scheduled certificate reload auto reload "Hot reload" also fits the reload command, which reloads without a restart too, so hotReloadEnabled=false read as if it turned off every reload. Only the scheduled reload depends on these settings, so the settings, metrics, logs, reload thread and docs now call it auto reload: - AbstractSslContextFactory: isAutoReloadEnabled/setAutoReloadEnabled, getAutoReloadBeforeExpiryMs/setAutoReloadBeforeExpiryMs, DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS and autoReloadTime(); - the public Jetty interface is AutoReloadJettySslFactory; - ssl metrics ConsecutiveAutoReloadFailures and AutoReloadAttempts; - the reload thread ssl-auto-reload. The manual reload keeps its names. None of the renamed names has been released. Co-Authored-By: Claude Opus 5.5 --- .../_docs/monitoring-metrics/new-metrics.adoc | 8 +- docs/_docs/restapi.adoc | 40 ++-- docs/_docs/security/ssl-tls.adoc | 66 +++--- .../processors/ssl/ReloadableSslFactory.java | 8 +- .../ignite/ssl/AbstractSslContextFactory.java | 42 ++-- .../processors/ssl/SslFactoryRegistry.java | 98 ++++---- .../ssl/SslFactoryRegistryTest.java | 214 +++++++++--------- .../ssl/SslCertificateHotReloadTest.java | 44 ++-- .../ssl/SslContextFactoryHotReloadTest.java | 80 +++---- .../http/jetty/JettySslFactoryAdapter.java | 28 +-- ...ry.java => AutoReloadJettySslFactory.java} | 12 +- .../apache/ignite/ssl/jetty/package-info.java | 2 +- .../http/jetty/JettyRestHttpsReloadTest.java | 78 +++---- .../META-INF/jetty/https-source-manual.xml | 2 +- 14 files changed, 361 insertions(+), 361 deletions(-) rename modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/{ReloadableJettySslFactory.java => AutoReloadJettySslFactory.java} (76%) diff --git a/docs/_docs/monitoring-metrics/new-metrics.adoc b/docs/_docs/monitoring-metrics/new-metrics.adoc index 3d6c6085234db..1919fa8f610af 100644 --- a/docs/_docs/monitoring-metrics/new-metrics.adoc +++ b/docs/_docs/monitoring-metrics/new-metrics.adoc @@ -433,19 +433,19 @@ Register name: `communication.tcp.{node_consistent_id}` |sentMessagesToNode | long | Total number of messages sent by current node to the given node. |=== -== Certificate Hot Reload +== Automatic Certificate Reload Register name: `ssl` [cols="2,1,3",opts="header"] |=== |Name | Type | Description -|ConsecutiveHotReloadFailures | long | Number of consecutive automatic hot reload failures. +|ConsecutiveAutoReloadFailures | long | Number of consecutive automatic reload failures. |ManualReloadAttempts | long | Number of manual reload attempts. -|AutomaticHotReloadAttempts | long | Number of automatic hot reload attempts. +|AutoReloadAttempts | long | Number of automatic reload attempts. |=== -See link:security/ssl-tls#automatic-certificate-hot-reload[Automatic Certificate Hot Reload] for configuration and recovery. +See link:security/ssl-tls#automatic-certificate-reload[Automatic Certificate Reload] for configuration and recovery. == Communication Connection Pool diff --git a/docs/_docs/restapi.adoc b/docs/_docs/restapi.adoc index 3df3f3dfdd213..442b463d3efa9 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -110,36 +110,36 @@ Configure the HTTPS connector, its SSL context factory, and its key and trust st Both the standard Jetty factory and custom subclasses of `SslContextFactory.Server` work. After you replace the stores, run the link:tools/control-script#reloading-tls-certificates[`--ssl reload` command]. -The node also reloads the stores automatically before its certificates expire, as described in link:security/ssl-tls#automatic-certificate-hot-reload[Automatic Certificate Hot Reload]. -By default, hot reload of the Jetty factory is enabled and becomes due 7 days before the earliest certificate expiry in its private key chains. -To change these settings for a factory, configure it with your own subclass of `SslContextFactory.Server` that implements `org.apache.ignite.ssl.jetty.ReloadableJettySslFactory` from the `ignite-rest-http` module. -The interface has getters for two properties: `hotReloadEnabled` and `hotReloadBeforeExpiryMs`, the lead time in milliseconds, which must be positive. +The node also reloads the stores automatically before its certificates expire, as described in link:security/ssl-tls#automatic-certificate-reload[Automatic Certificate Reload]. +By default, automatic reload of the Jetty factory is enabled and becomes due 7 days before the earliest certificate expiry in its private key chains. +To change these settings for a factory, configure it with your own subclass of `SslContextFactory.Server` that implements `org.apache.ignite.ssl.jetty.AutoReloadJettySslFactory` from the `ignite-rest-http` module. +The interface has getters for two properties: `autoReloadEnabled` and `autoReloadBeforeExpiryMs`, the lead time in milliseconds, which must be positive. Add setters for them, so that the Jetty XML file can set them: [source,java] ---- -public class MySslContextFactory extends SslContextFactory.Server implements ReloadableJettySslFactory { - private boolean hotReloadEnabled = true; +public class MySslContextFactory extends SslContextFactory.Server implements AutoReloadJettySslFactory { + private boolean autoReloadEnabled = true; - private long hotReloadBeforeExpiryMs = AbstractSslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; + private long autoReloadBeforeExpiryMs = AbstractSslContextFactory.DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS; - @Override public boolean isHotReloadEnabled() { - return hotReloadEnabled; + @Override public boolean isAutoReloadEnabled() { + return autoReloadEnabled; } - public void setHotReloadEnabled(boolean hotReloadEnabled) { - this.hotReloadEnabled = hotReloadEnabled; + public void setAutoReloadEnabled(boolean autoReloadEnabled) { + this.autoReloadEnabled = autoReloadEnabled; } - @Override public long getHotReloadBeforeExpiryMs() { - return hotReloadBeforeExpiryMs; + @Override public long getAutoReloadBeforeExpiryMs() { + return autoReloadBeforeExpiryMs; } - public void setHotReloadBeforeExpiryMs(long hotReloadBeforeExpiryMs) { - if (hotReloadBeforeExpiryMs <= 0) - throw new IllegalArgumentException("hotReloadBeforeExpiryMs must be positive: " + hotReloadBeforeExpiryMs); + public void setAutoReloadBeforeExpiryMs(long autoReloadBeforeExpiryMs) { + if (autoReloadBeforeExpiryMs <= 0) + throw new IllegalArgumentException("autoReloadBeforeExpiryMs must be positive: " + autoReloadBeforeExpiryMs); - this.hotReloadBeforeExpiryMs = hotReloadBeforeExpiryMs; + this.autoReloadBeforeExpiryMs = autoReloadBeforeExpiryMs; } } ---- @@ -152,12 +152,12 @@ Then set the properties on the factory in the Jetty XML file: /opt/ignite/config/https.jks changeit - false + false ---- -These settings apply only to this factory: other transports keep their own hot reload settings. +These settings apply only to this factory: other transports keep their own automatic reload settings. Changing them requires a node restart. The reload command reloads the factory either way. @@ -166,7 +166,7 @@ New connections use the replacement certificates; established connections stay o If loading fails, the endpoint keeps its current keys and trust settings, and new connections keep working with them. Correct the stores and run the command again. A failed reload by Jetty's own `KeyStoreScanner` leaves the endpoint without keys. -Correct the stores, then run the command or, if hot reload is enabled, wait for its next check, as described in link:security/ssl-tls#when-hot-reload-runs[When Hot Reload Runs]. +Correct the stores, then run the command or, if automatic reload is enabled, wait for its next check, as described in link:security/ssl-tls#when-automatic-reload-runs[When Automatic Reload Runs]. Keep the stores in the sources that the factory loads: the store paths in the Jetty XML file, or the `loadKeyStore(Resource)` and `loadTrustStore(Resource)` methods of a custom subclass. A store that your code sets on the running factory, for example with `setKeyStore(KeyStore)`, does not survive a failed reload: the next reload loads the stores configured in the Jetty XML file instead. diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index 7e877d77c8316..bdcf5ce68ced7 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -164,7 +164,7 @@ It also reloads the link:restapi#https[HTTP REST endpoint] when its Jetty connec External client applications reload their certificates separately. Follow the trust-first order below even if you do not plan to run the command. -<> is enabled by default, so a node can load a replaced key store on its next check once its current certificates are due. +<> is enabled by default, so a node can load a replaced key store on its next check once its current certificates are due. If a peer does not trust the new certificate yet, its new connections to that node fail. . Back up the key and trust store files before replacing them. @@ -193,29 +193,29 @@ If any of these transports uses another type of factory, the command reports it For these factories, follow the same trust-first sequence and restart affected nodes one at a time instead of running reload. If you configured `trustManagers` directly, the command reuses them instead of reloading a trust store. -== Automatic Certificate Hot Reload +== Automatic Certificate Reload -Automatic hot reload lets nodes load replacement certificates without a reload command. +Automatic reload lets nodes load replacement certificates without a reload command. You must supply the replacements: Ignite reads them from the configured source and does not issue certificates. -Hot reload covers the same transports as <>, including the HTTP REST endpoint. +Automatic reload covers the same transports as <>, including the HTTP REST endpoint. It does not update external client applications. -=== Disable Hot Reload +=== Disable Automatic Reload -Hot reload is enabled by default. -To disable it, call `setHotReloadEnabled(false)` on the factory before starting the node. -Hot reload stops for every transport that uses this factory, and other factories keep it: +Automatic reload is enabled by default. +To disable it, call `setAutoReloadEnabled(false)` on the factory before starting the node. +Automatic reload stops for every transport that uses this factory, and other factories keep it: [source,java] ---- -factory.setHotReloadEnabled(false); +factory.setAutoReloadEnabled(false); ---- Changing this setting requires a node restart. The reload command still reloads the factory. For the HTTP REST endpoint, set this property on its Jetty factory, as described in link:restapi#https[HTTPS]. -The `SslContextFactory` of Ignite.NET has no `hotReloadEnabled` or `hotReloadBeforeExpiryMs` property. +The `SslContextFactory` of Ignite.NET has no `autoReloadEnabled` or `autoReloadBeforeExpiryMs` property. To set them for a .NET node, define the SSL factory in the Spring XML file set by `IgniteConfiguration.SpringConfigUrl`. Leave `IgniteConfiguration.SslContextFactory` unset: it replaces the factory from the XML file. @@ -224,33 +224,33 @@ Leave `IgniteConfiguration.SslContextFactory` unset: it replaces the factory fro The key store must contain a private key with an X.509 certificate chain. A chain contains the key's certificate and the certificates of its issuers. Ignite ignores keys without such a chain, as TLS does. -If the key store has no such key, the node logs a warning and skips hot reload. -After a manual reload of a key store with such a key, hot reload works again. +If the key store has no such key, the node logs a warning and skips automatic reload. +After a manual reload of a key store with such a key, automatic reload works again. Before replacing key stores, prepare peers' trust stores as described in <>. Once every affected peer trusts the replacement certificates, put the replacement key stores in the configured source. Put only certificates whose validity period has already started. Ignite installs the replacements without checking their dates, and peers may reject certificates that are not yet valid. Keep the configured paths, store types and passwords unchanged. -Ignite loads the replacements automatically when hot reload is due; no reload command is needed for this step. +Ignite loads the replacements when automatic reload is due; no reload command is needed for this step. -=== When Hot Reload Runs +=== When Automatic Reload Runs -At startup, Ignite schedules a check for each factory with hot reload enabled. +At startup, Ignite schedules a check for each factory with automatic reload enabled. If a factory's certificates are not yet due, Ignite schedules its next check for the due date or one hour later, whichever comes first. After a failed attempt, Ignite schedules another check for one hour later. All checks share one thread, so a slow certificate source can delay checks for other factories. -For each factory, hot reload becomes due `hotReloadBeforeExpiryMs` before the earliest certificate expiry in its private key chains. +For each factory, automatic reload becomes due `autoReloadBeforeExpiryMs` before the earliest certificate expiry in its private key chains. This includes issuing certificates. The default lead time is 7 days. For the HTTP REST endpoint, Ignite takes the certificates from the key store that the Jetty factory has loaded, and the lead time from the same factory, as described in link:restapi#https[HTTPS]. The first check at or after that date attempts a reload, including the startup check. Allow enough time before expiry to supply the replacements and load the stores. Keep the lead time shorter than the lifetime of the replacement certificates, or they will already be due when loaded. -See link:{javadoc_base_url}/org/apache/ignite/ssl/AbstractSslContextFactory.html#hotReloadTime()[hotReloadTime(), window=_blank] for the calculation. +See link:{javadoc_base_url}/org/apache/ignite/ssl/AbstractSslContextFactory.html#autoReloadTime()[autoReloadTime(), window=_blank] for the calculation. -If the loaded certificates are still due for hot reload, Ignite records a failed hot reload attempt even though it installed them. -This can happen when the certificates have not changed, only the trust store changed, or the replacements expire within `hotReloadBeforeExpiryMs`. +If the loaded certificates are still due for automatic reload, Ignite records a failed automatic reload attempt even though it installed them. +This can happen when the certificates have not changed, only the trust store changed, or the replacements expire within `autoReloadBeforeExpiryMs`. The loaded context remains in use until a later reload replaces it. After a manual reload, Ignite schedules the next check from the loaded certificates. @@ -264,22 +264,22 @@ To confirm a replacement, open a new TLS connection to each affected endpoint an If loading the stores or creating the TLS context fails, Ignite keeps the current certificates and retries on the next check, even after they expire. Keeping expired certificates does not extend their validity, so new connections may fail until a valid replacement is available. -If the replacements appear after hot reload is due, the next retry loads them. +If the replacements appear after automatic reload is due, the next retry loads them. The node log shows the affected transports. -At `INFO` level it shows when the loaded certificates are due for hot reload, when an attempt starts and when it succeeds. +At `INFO` level it shows when the loaded certificates are due for automatic reload, when an attempt starts and when it succeeds. At `WARN` level it shows why an attempt failed and when the node retries automatically. At `DEBUG` level it also shows the start of each check. -The `ssl.ConsecutiveHotReloadFailures` metric sums consecutive failed automatic attempts across the node's factories. -Each factory's count resets after a successful manual reload or when a check finds that the loaded certificates are no longer due for hot reload. +The `ssl.ConsecutiveAutoReloadFailures` metric sums consecutive failed automatic attempts across the node's factories. +Each factory's count resets after a successful manual reload or when a check finds that the loaded certificates are no longer due for automatic reload. To recover without waiting for the next retry: . Correct the replacement stores and run link:tools/control-script#reloading-tls-certificates[`control.sh --ssl reload`]. . Check the command result and verify a new connection with the replacement certificates. -*What happens to automatic hot reload.* -If enabled, automatic hot reload continues after manual reload, as described in <>. +*What happens to automatic reload.* +If enabled, automatic reload continues after manual reload, as described in <>. A failed automatic attempt does not undo the manual reload. *If the command cannot connect.* @@ -290,12 +290,12 @@ Otherwise, or to load the corrected stores without waiting, restart the affected === Custom Certificate Sources -For automatic hot reload, a custom Ignite factory creates its key managers with `createKeyManagers(KeyManagerFactory, KeyStore, char[])` of javadoc:org.apache.ignite.ssl.AbstractSslContextFactory[]. +For automatic reload, a custom Ignite factory creates its key managers with `createKeyManagers(KeyManagerFactory, KeyStore, char[])` of javadoc:org.apache.ignite.ssl.AbstractSslContextFactory[]. On each load, call this method once with the key store and the key password that your source returned. -Ignite takes the hot reload date from that key store. -A factory that does not call this method has no hot reload date, and the node logs a warning. +Ignite takes the automatic reload date from that key store. +A factory that does not call this method has no automatic reload date, and the node logs a warning. A custom Jetty factory of the HTTP REST endpoint needs no such call: Ignite takes the date from the key store that the Jetty factory loads, for example in `loadKeyStore(Resource)`. -Limit request duration in custom sources: a blocked load delays other hot reloads and manual reload. +Limit request duration in custom sources: a blocked load delays other automatic reloads and manual reload. == SslContextFactory Properties @@ -325,12 +325,12 @@ Limit request duration in custom sources: a blocked load delays other hot reload |The protocol for secure transport. https://docs.oracle.com/en/java/javase/11/docs/specs/security/standard-names.html#sslcontext-algorithms[Supported algorithms,window=_blank]. |`TLS` -|`hotReloadEnabled` -|Enables automatic certificate hot reload. See <>. +|`autoReloadEnabled` +|Enables automatic certificate reload. See <>. |`true` -|`hotReloadBeforeExpiryMs` -|How long before the certificates expire hot reload becomes due, in milliseconds. See <>. +|`autoReloadBeforeExpiryMs` +|How long before the certificates expire automatic reload becomes due, in milliseconds. See <>. |`604800000` (7 days) |`trustStoreFilePath` diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index 527b9059b5301..0f2223bafdc8f 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -36,20 +36,20 @@ public interface ReloadableSslFactory extends Factory { public void init(); /** - * The hot reload time is the earliest expiry among the certificate chains of the private keys that new connections + * The automatic reload time is the earliest expiry among the certificate chains of the private keys that new connections * use, minus the lead time of the factory. A chain expires when any certificate in it expires. * Keys without an X.509 certificate chain are ignored, as TLS cannot use them. A factory that has lost the keys * of new connections, for example after a failed reload outside the registry, gives a time that has already come, * so that the next check reloads it. * - * @return Hot reload time in milliseconds since the epoch, or {@code 0} if the factory gives no private key with + * @return Automatic reload time in milliseconds since the epoch, or {@code 0} if the factory gives no private key with * an X.509 certificate chain. * @throws IgniteException If the factory cannot give the certificates that new connections use. */ - public long hotReloadTime(); + public long autoReloadTime(); /** @return Whether the registry reloads the factory before its certificates expire. Manual reload works either way. */ - public boolean isHotReloadEnabled(); + public boolean isAutoReloadEnabled(); /** * @param store Loaded key store. diff --git a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java index 48bd22d9caf0e..f8870e99c0914 100644 --- a/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/ssl/AbstractSslContextFactory.java @@ -35,8 +35,8 @@ /** * Base class for SSL context factories that cache their {@link SSLContext}. {@link #init()} loads a new context, and - * {@link #create()} returns the last one that it loaded, loading one on the first call. The hot reload time comes - * {@link #getHotReloadBeforeExpiryMs()} before the earliest expiry in the key store that the factory passed to + * {@link #create()} returns the last one that it loaded, loading one on the first call. The automatic reload time comes + * {@link #getAutoReloadBeforeExpiryMs()} before the earliest expiry in the key store that the factory passed to * {@link #createKeyManagers(KeyManagerFactory, KeyStore, char[])} during the last successful load. */ public abstract class AbstractSslContextFactory implements ReloadableSslFactory { @@ -46,8 +46,8 @@ public abstract class AbstractSslContextFactory implements ReloadableSslFactory /** Default SSL protocol. */ public static final String DFLT_SSL_PROTOCOL = "TLS"; - /** Default lead time for certificate hot reload: 7 days. */ - public static final long DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS = TimeUnit.DAYS.toMillis(7); + /** Default lead time for automatic certificate reload: 7 days. */ + public static final long DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS = TimeUnit.DAYS.toMillis(7); /** SSL protocol. */ protected String proto = DFLT_SSL_PROTOCOL; @@ -62,10 +62,10 @@ public abstract class AbstractSslContextFactory implements ReloadableSslFactory protected final AtomicReference sslCtx = new AtomicReference<>(); /** */ - private boolean hotReloadEnabled = true; + private boolean autoReloadEnabled = true; /** */ - private volatile long hotReloadBeforeExpiryMs = DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; + private volatile long autoReloadBeforeExpiryMs = DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS; /** */ private transient volatile long earliestExpiry; @@ -74,40 +74,40 @@ public abstract class AbstractSslContextFactory implements ReloadableSslFactory private transient long pendingExpiry; /** {@inheritDoc} */ - @Override public boolean isHotReloadEnabled() { - return hotReloadEnabled; + @Override public boolean isAutoReloadEnabled() { + return autoReloadEnabled; } /** - * @param enabled Whether automatic certificate hot reload is enabled. It is enabled by default. Changes require + * @param enabled Whether automatic certificate reload is enabled. It is enabled by default. Changes require * a node restart. */ - public void setHotReloadEnabled(boolean enabled) { - hotReloadEnabled = enabled; + public void setAutoReloadEnabled(boolean enabled) { + autoReloadEnabled = enabled; } /** - * @return How long before the certificates expire hot reload becomes due, in milliseconds. - * Defaults to {@link #DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. + * @return How long before the certificates expire automatic reload becomes due, in milliseconds. + * Defaults to {@link #DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS}. */ - public long getHotReloadBeforeExpiryMs() { - return hotReloadBeforeExpiryMs; + public long getAutoReloadBeforeExpiryMs() { + return autoReloadBeforeExpiryMs; } /** - * @param millis How long before the certificates expire hot reload becomes due, in milliseconds. Must be positive. + * @param millis How long before the certificates expire automatic reload becomes due, in milliseconds. Must be positive. */ - public void setHotReloadBeforeExpiryMs(long millis) { + public void setAutoReloadBeforeExpiryMs(long millis) { A.ensure(millis > 0, "millis > 0"); - hotReloadBeforeExpiryMs = millis; + autoReloadBeforeExpiryMs = millis; } /** {@inheritDoc} */ - @Override public long hotReloadTime() { + @Override public long autoReloadTime() { long expiry = earliestExpiry; - return expiry == 0 ? 0 : expiry - hotReloadBeforeExpiryMs; + return expiry == 0 ? 0 : expiry - autoReloadBeforeExpiryMs; } /** @@ -234,7 +234,7 @@ protected void checkNullParameter(Object param, String name) throws SSLException protected abstract KeyManager[] createKeyManagers() throws SSLException; /** - * Creates key managers from the key store. For the hot reload date, call it once per load with the key store that + * Creates key managers from the key store. For the automatic reload date, call it once per load with the key store that * supplies the key managers. * * @param keyMgrFactory Key manager factory. diff --git a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java index 638b43b1a6ca8..3c750cdfd33f1 100644 --- a/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java +++ b/modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java @@ -56,7 +56,7 @@ public class SslFactoryRegistry extends GridProcessorAdapter { private final AtomicLong manualReloadAttempts = new AtomicLong(); /** */ - private final AtomicLong automaticHotReloadAttempts = new AtomicLong(); + private final AtomicLong autoReloadAttempts = new AtomicLong(); /** @param ctx Kernal context. */ public SslFactoryRegistry(GridKernalContext ctx) { @@ -96,25 +96,25 @@ public List, String>> factories() { @Override public void onKernalStart(boolean active) { MetricRegistryImpl metrics = ctx.metric().registry("ssl"); - metrics.register("ConsecutiveHotReloadFailures", this::consecutiveHotReloadFailures, - "Number of consecutive automatic hot reload failures."); + metrics.register("ConsecutiveAutoReloadFailures", this::consecutiveAutoReloadFailures, + "Number of consecutive automatic reload failures."); metrics.register("ManualReloadAttempts", manualReloadAttempts::get, "Number of manual reload attempts."); - metrics.register("AutomaticHotReloadAttempts", automaticHotReloadAttempts::get, - "Number of automatic hot reload attempts."); + metrics.register("AutoReloadAttempts", autoReloadAttempts::get, + "Number of automatic reload attempts."); for (RegisteredFactory registered : factories) { - if (registered.reloadable == null || !registered.reloadable.isHotReloadEnabled()) + if (registered.reloadable == null || !registered.reloadable.isAutoReloadEnabled()) continue; if (executor == null) - executor = newSingleThreadScheduledExecutor("ssl-hot-reload", ctx.igniteInstanceName()); + executor = newSingleThreadScheduledExecutor("ssl-auto-reload", ctx.igniteInstanceName()); registered.scheduleCheck(0); } } - /** @return Sum of consecutive automatic hot reload failures across factories. */ - private long consecutiveHotReloadFailures() { + /** @return Sum of consecutive automatic reload failures across factories. */ + private long consecutiveAutoReloadFailures() { long sum = 0; for (RegisteredFactory registered : factories) @@ -130,10 +130,10 @@ private long consecutiveHotReloadFailures() { } /** - * Reloads a registered factory. For a factory with hot reload enabled, waits for its running check, resets its failure + * Reloads a registered factory. For a factory with automatic reload enabled, waits for its running check, resets its failure * count and schedules its next check for the loaded certificates. If they are already due, the next check comes after - * {@link #CHECK_PERIOD}, because a hot reload right away would load the same certificates from the source. If the - * factory cannot give the hot reload time of the loaded certificates, the reload still succeeds, and the next check + * {@link #CHECK_PERIOD}, because an automatic reload right away would load the same certificates from the source. If the + * factory cannot give the automatic reload time of the loaded certificates, the reload still succeeds, and the next check * comes after {@link #CHECK_PERIOD}. * * @param factory Registered factory to reload. @@ -145,7 +145,7 @@ public void reload(ReloadableSslFactory factory) { } } - /** Registered factory with its transports and hot reload state. Its checks and manual reload hold its monitor. */ + /** Registered factory with its transports and automatic reload state. Its checks and manual reload hold its monitor. */ private class RegisteredFactory { /** */ private final Factory factory; @@ -162,8 +162,8 @@ private class RegisteredFactory { /** */ @Nullable private ScheduledFuture nextCheck; - /** Hot reload time that the registry logged last, or {@code -1} before the first log. */ - private long loggedHotReloadTime = -1; + /** Automatic reload time that the registry logged last, or {@code -1} before the first log. */ + private long loggedAutoReloadTime = -1; /** */ private RegisteredFactory(Factory factory, String transports) { @@ -183,7 +183,7 @@ private synchronized void check() { return; if (log.isDebugEnabled()) - log.debug("TLS hot reload check started [transports=" + transports + ']'); + log.debug("TLS automatic reload check started [transports=" + transports + ']'); long nextCheckDelay = CHECK_PERIOD; @@ -194,28 +194,28 @@ private synchronized void check() { if (!executor.isShutdown()) { failures.incrementAndGet(); - log.warning("TLS hot reload failed [transports=" + transports + ", nextAttempt=" + log.warning("TLS automatic reload failed [transports=" + transports + ", nextAttempt=" + new Date(System.currentTimeMillis() + CHECK_PERIOD) + ']', e); } else if (log.isDebugEnabled()) - log.debug("TLS hot reload failed during node stop [transports=" + transports + ", err=" + e + ']'); + log.debug("TLS automatic reload failed during node stop [transports=" + transports + ", err=" + e + ']'); } scheduleCheck(nextCheckDelay); } /** - * Reloads the factory if its hot reload time has come, and ends the failure streak if it has not. + * Reloads the factory if its automatic reload time has come, and ends the failure streak if it has not. * * @return Delay of the next check. * @throws IgniteException If the reload fails or leaves certificates that are still due. */ private long reloadIfDue() { - long hotReloadTime = reloadable.hotReloadTime(); + long autoReloadTime = reloadable.autoReloadTime(); - logHotReloadTime(hotReloadTime); + logAutoReloadTime(autoReloadTime); - long nextCheckDelay = nextCheckDelay(hotReloadTime); + long nextCheckDelay = nextCheckDelay(autoReloadTime); if (nextCheckDelay != 0) { failures.set(0); @@ -223,41 +223,41 @@ private long reloadIfDue() { return nextCheckDelay; } - automaticHotReloadAttempts.incrementAndGet(); + autoReloadAttempts.incrementAndGet(); if (log.isInfoEnabled()) - log.info("TLS hot reload started [transports=" + transports + ']'); + log.info("TLS automatic reload started [transports=" + transports + ']'); reloadable.init(); - hotReloadTime = reloadable.hotReloadTime(); - nextCheckDelay = nextCheckDelay(hotReloadTime); + autoReloadTime = reloadable.autoReloadTime(); + nextCheckDelay = nextCheckDelay(autoReloadTime); if (nextCheckDelay == 0) { - throw new IgniteException("Loaded certificates are still due for hot reload [hotReloadTime=" - + new Date(hotReloadTime) + ']'); + throw new IgniteException("Loaded certificates are still due for automatic reload [autoReloadTime=" + + new Date(autoReloadTime) + ']'); } failures.set(0); if (log.isInfoEnabled()) - log.info("TLS hot reload succeeded [transports=" + transports + ']'); + log.info("TLS automatic reload succeeded [transports=" + transports + ']'); - logHotReloadTime(hotReloadTime); + logAutoReloadTime(autoReloadTime); return nextCheckDelay; } /** - * @param hotReloadTime Hot reload time of the loaded certificates, or {@code 0} if they have none. - * @return Delay until the hot reload time, but no longer than {@link #CHECK_PERIOD}, or {@code 0} if the time has - * come. Certificates without a hot reload time are checked again after the full period. + * @param autoReloadTime Automatic reload time of the loaded certificates, or {@code 0} if they have none. + * @return Delay until the automatic reload time, but no longer than {@link #CHECK_PERIOD}, or {@code 0} if the time has + * come. Certificates without an automatic reload time are checked again after the full period. */ - private static long nextCheckDelay(long hotReloadTime) { - if (hotReloadTime == 0) + private static long nextCheckDelay(long autoReloadTime) { + if (autoReloadTime == 0) return CHECK_PERIOD; - return Math.max(0, Math.min(hotReloadTime - System.currentTimeMillis(), CHECK_PERIOD)); + return Math.max(0, Math.min(autoReloadTime - System.currentTimeMillis(), CHECK_PERIOD)); } /** Replaces the scheduled check of the factory with one after the given delay, once the registry has started. */ @@ -282,18 +282,18 @@ private synchronized void reload() { reloadable.init(); - if (!reloadable.isHotReloadEnabled()) + if (!reloadable.isAutoReloadEnabled()) return; failures.set(0); - long hotReloadTime; + long autoReloadTime; try { - hotReloadTime = reloadable.hotReloadTime(); + autoReloadTime = reloadable.autoReloadTime(); } catch (RuntimeException e) { - log.warning("TLS hot reload could not read certificate expiry after manual reload [transports=" + transports + log.warning("TLS automatic reload could not read certificate expiry after manual reload [transports=" + transports + ", nextAttempt=" + new Date(System.currentTimeMillis() + CHECK_PERIOD) + ']', e); scheduleCheck(CHECK_PERIOD); @@ -301,26 +301,26 @@ private synchronized void reload() { return; } - logHotReloadTime(hotReloadTime); + logAutoReloadTime(autoReloadTime); - long nextCheckDelay = nextCheckDelay(hotReloadTime); + long nextCheckDelay = nextCheckDelay(autoReloadTime); scheduleCheck(nextCheckDelay == 0 ? CHECK_PERIOD : nextCheckDelay); } - /** Logs the hot reload time of the loaded certificates if it differs from the one logged last. */ - private void logHotReloadTime(long hotReloadTime) { - if (hotReloadTime == loggedHotReloadTime) + /** Logs the automatic reload time of the loaded certificates if it differs from the one logged last. */ + private void logAutoReloadTime(long autoReloadTime) { + if (autoReloadTime == loggedAutoReloadTime) return; - loggedHotReloadTime = hotReloadTime; + loggedAutoReloadTime = autoReloadTime; - if (hotReloadTime == 0) { - log.warning("TLS hot reload will not run: no private key with an X.509 certificate chain was found [transports=" + if (autoReloadTime == 0) { + log.warning("TLS automatic reload will not run: no private key with an X.509 certificate chain was found [transports=" + transports + ']'); } else if (log.isInfoEnabled()) - log.info("TLS hot reload due [transports=" + transports + ", hotReloadTime=" + new Date(hotReloadTime) + ']'); + log.info("TLS automatic reload due [transports=" + transports + ", autoReloadTime=" + new Date(autoReloadTime) + ']'); } } } diff --git a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java index 4ecd965b9357a..c7ded1f510d48 100644 --- a/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java +++ b/modules/core/src/test/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistryTest.java @@ -87,7 +87,7 @@ /** * A manual reload is {@link SslFactoryRegistry#reload}, which the TLS reload command calls. - * An attempt is an automatic hot reload attempt that a scheduled check makes. + * An attempt is an automatic reload attempt that a scheduled check makes. */ public class SslFactoryRegistryTest { /** Upper bound for waiting for an event that must happen. */ @@ -127,7 +127,7 @@ public class SslFactoryRegistryTest { private TestCertificateAuthority authority; /** - * Each test gets a registry whose hot reload executor records the scheduled checks instead of running them. + * Each test gets a registry whose automatic reload executor records the scheduled checks instead of running them. * Tests run the checks themselves. * The setup also writes the trust store of a test CA to a temporary directory and stubs the node metrics and logger. */ @@ -193,16 +193,16 @@ public void testFactoriesAreGroupedInRegistrationOrder() { } /** - * Given: a factory with hot reload disabled and valid certificates. + * Given: a factory with automatic reload disabled and valid certificates. * When: the registry starts. - * Then: no hot reload thread starts, and the failure metric reads zero. + * Then: no automatic reload thread starts, and the failure metric reads zero. */ @Test - public void testDisabledFactoryDoesNotStartHotReload() throws Exception { + public void testDisabledFactoryDoesNotStartAutoReload() throws Exception { SslContextFactory communication = factory(keys); writeFreshCertificates(keys); - communication.setHotReloadEnabled(false); + communication.setAutoReloadEnabled(false); registerTransport("communication", communication); registry.onKernalStart(true); @@ -213,10 +213,10 @@ public void testDisabledFactoryDoesNotStartHotReload() throws Exception { /** * Given: a transport registers a factory that only creates contexts and cannot reload them. * When: the registry starts. - * Then: no hot reload thread starts, and the failure metric reads zero. + * Then: no automatic reload thread starts, and the failure metric reads zero. */ @Test - public void testFactoryWithoutReloadDoesNotStartHotReload() { + public void testFactoryWithoutReloadDoesNotStartAutoReload() { Factory createOnly = () -> null; registry.register("communication", createOnly); @@ -227,16 +227,16 @@ public void testFactoryWithoutReloadDoesNotStartHotReload() { } /** - * Given: HTTP REST registers a factory that is not an Ignite SSL context factory, with certificates due for hot reload. + * Given: HTTP REST registers a factory that is not an Ignite SSL context factory, with certificates due for automatic reload. * When: the periodic check runs and loads certificates that are not due, and then a manual reload runs. * Then: the automatic attempt succeeds, the registry reloads the factory each time and counts one automatic * and one manual attempt. */ @Test - public void testReloadableFactoryIsHotReloadedAndReloadedManually() { + public void testReloadableFactoryIsAutoReloadedAndReloadedManually() { ReloadableSslFactory rest = httpRestFactory(); - when(rest.hotReloadTime()).thenReturn(due(), at(DAYS.toHours(30))); + when(rest.autoReloadTime()).thenReturn(due(), at(DAYS.toHours(30))); registry.register("HTTP REST", rest); registry.onKernalStart(true); @@ -247,7 +247,7 @@ public void testReloadableFactoryIsHotReloadedAndReloadedManually() { registry.reload(rest); verify(rest, times(2)).init(); - assertEquals(1, metric("AutomaticHotReloadAttempts")); + assertEquals(1, metric("AutoReloadAttempts")); assertEquals(1, metric("ManualReloadAttempts")); } @@ -267,14 +267,14 @@ public void testEachFactoryInstanceReloadsOnce() throws Exception { registerTransport("client connector", clientConnector); registry.onKernalStart(true); - long prevTime = communication.hotReloadTime(); + long prevTime = communication.autoReloadTime(); writeFreshCertificates(keys); runChecks(); - assertEquals(2, metric("AutomaticHotReloadAttempts")); - assertTrue(communication.hotReloadTime() > prevTime); - assertEquals(communication.hotReloadTime(), clientConnector.hotReloadTime()); + assertEquals(2, metric("AutoReloadAttempts")); + assertTrue(communication.autoReloadTime() > prevTime); + assertEquals(communication.autoReloadTime(), clientConnector.autoReloadTime()); } /** @@ -292,21 +292,21 @@ public void testManualReloadLoadsOnlyItsFactoryInstance() throws Exception { registerTransport("client connector", clientConnector); registry.onKernalStart(true); - long prevTime = communication.hotReloadTime(); + long prevTime = communication.autoReloadTime(); writeFreshCertificates(keys); registry.reload(clientConnector); - assertTrue(clientConnector.hotReloadTime() > prevTime); - assertEquals(prevTime, communication.hotReloadTime()); + assertTrue(clientConnector.autoReloadTime() > prevTime); + assertEquals(prevTime, communication.autoReloadTime()); } /** * Given: the key store holds only a CA certificate. * When: the registry starts and the periodic check runs, then the operator puts a key store with a private key in place * and reloads it. - * Then: the registry logs that hot reload will not run, and the check makes no attempt. - * After the reload, the log shows when hot reload is due. + * Then: the registry logs that automatic reload will not run, and the check makes no attempt. + * After the reload, the log shows when automatic reload is due. */ @Test public void testStoreWithoutPrivateKeyIsReportedUntilKeysAreReloaded() throws Exception { @@ -319,18 +319,18 @@ public void testStoreWithoutPrivateKeyIsReportedUntilKeysAreReloaded() throws Ex runChecks(); assertEquals(1, logged.size()); - assertTrue(logged.get(0), logged.get(0).startsWith("TLS hot reload will not run")); - assertEquals(0, metric("AutomaticHotReloadAttempts")); + assertTrue(logged.get(0), logged.get(0).startsWith("TLS automatic reload will not run")); + assertEquals(0, metric("AutoReloadAttempts")); writeFreshCertificates(keys); registry.reload(communication); - assertEquals("TLS hot reload due [transports=communication, hotReloadTime=" + new Date(communication.hotReloadTime()) + ']', + assertEquals("TLS automatic reload due [transports=communication, autoReloadTime=" + new Date(communication.autoReloadTime()) + ']', logged.get(logged.size() - 1)); } /** - * Given: the loaded certificates are due for hot reload, and the key store file is deleted after start. + * Given: the loaded certificates are due for automatic reload, and the key store file is deleted after start. * When: the scheduled check runs three times. * Then: the first check runs at start, each failed check schedules a retry in an hour, and each run counts one more * failed attempt. @@ -355,16 +355,16 @@ public void testFailedCheckIsRetriedAfterCheckPeriod() throws Exception { } /** - * Given: two factories, and reading the hot reload time of the first one fails. + * Given: two factories, and reading the automatic reload time of the first one fails. * When: the registry starts and its checks run. * Then: the start completes, the check of the first factory fails and is retried in an hour, and the second factory - * gets its next check at its hot reload time. + * gets its next check at its automatic reload time. */ @Test - public void testFailedReadOfHotReloadTimeIsRetriedWithoutFailingStart() throws Exception { + public void testFailedReadOfAutoReloadTimeIsRetriedWithoutFailingStart() throws Exception { ReloadableSslFactory rest = httpRestFactory(); - when(rest.hotReloadTime()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")); + when(rest.autoReloadTime()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")); writeCertificatesDueIn30Minutes(keys); registry.register("HTTP REST", rest); registerTransport("communication", factory(keys)); @@ -379,14 +379,14 @@ public void testFailedReadOfHotReloadTimeIsRetriedWithoutFailingStart() throws E } /** - * Given: communication has certificates that are due for hot reload in 30 minutes, and the client connector has + * Given: communication has certificates that are due for automatic reload in 30 minutes, and the client connector has * certificates that are due in 23 days. * When: the checks at start run. - * Then: the next check of communication comes at its hot reload time, and the next check of the client connector + * Then: the next check of communication comes at its automatic reload time, and the next check of the client connector * comes in an hour, the longest interval between checks. */ @Test - public void testNextCheckComesAtHotReloadTimeButWithinCheckPeriod() throws Exception { + public void testNextCheckComesAtAutoReloadTimeButWithinCheckPeriod() throws Exception { Path clientKeys = dir.resolve("client-keys.jks"); writeCertificatesDueIn30Minutes(keys); @@ -403,16 +403,16 @@ public void testNextCheckComesAtHotReloadTimeButWithinCheckPeriod() throws Excep } /** - * Given: the check reads a hot reload time that comes in 30 minutes, and any later read finds that the time has come, - * as when the clock passes the hot reload time while the check runs. + * Given: the check reads an automatic reload time that comes in 30 minutes, and any later read finds that the time has come, + * as when the clock passes the automatic reload time while the check runs. * When: the check at start runs. - * Then: the next check comes in 30 minutes, at the hot reload time that the check read, not after the full hour. + * Then: the next check comes in 30 minutes, at the automatic reload time that the check read, not after the full hour. */ @Test - public void testCheckRightBeforeHotReloadTimeDoesNotDeferHotReload() { + public void testCheckRightBeforeAutoReloadTimeDoesNotDeferAutoReload() { ReloadableSslFactory rest = httpRestFactory(); - when(rest.hotReloadTime()).thenReturn(System.currentTimeMillis() + MINUTES.toMillis(30), due()); + when(rest.autoReloadTime()).thenReturn(System.currentTimeMillis() + MINUTES.toMillis(30), due()); registry.register("HTTP REST", rest); registry.onKernalStart(true); @@ -422,12 +422,12 @@ public void testCheckRightBeforeHotReloadTimeDoesNotDeferHotReload() { } /** - * Given: the loaded certificates are due for hot reload, and the key store gets certificates that are due in 30 minutes. + * Given: the loaded certificates are due for automatic reload, and the key store gets certificates that are due in 30 minutes. * When: the scheduled check loads them. * Then: the next check of the factory comes in 30 minutes. */ @Test - public void testHotReloadSchedulesCheckAtNewHotReloadTime() throws Exception { + public void testAutoReloadSchedulesCheckAtNewAutoReloadTime() throws Exception { writeDueCertificates(keys); registerTransport("communication", factory(keys)); registry.onKernalStart(true); @@ -439,12 +439,12 @@ public void testHotReloadSchedulesCheckAtNewHotReloadTime() throws Exception { } /** - * Given: the registry has started, and the key store gets certificates that are due for hot reload in 30 minutes. + * Given: the registry has started, and the key store gets certificates that are due for automatic reload in 30 minutes. * When: a manual reload loads them. * Then: the check that the registry scheduled at start is replaced by one in 30 minutes. */ @Test - public void testManualReloadSchedulesCheckAtHotReloadTime() throws Exception { + public void testManualReloadSchedulesCheckAtAutoReloadTime() throws Exception { SslContextFactory communication = factory(keys); writeFreshCertificates(keys); @@ -457,16 +457,16 @@ public void testManualReloadSchedulesCheckAtHotReloadTime() throws Exception { } /** - * Given: the HTTP REST factory fails to read its certificates once, and then reports a hot reload time that comes + * Given: the HTTP REST factory fails to read its certificates once, and then reports an automatic reload time that comes * in 30 minutes. * When: a manual reload loads the factory, and the next check runs. * Then: the reload succeeds and schedules a check in an hour, and that check schedules the next one in 30 minutes. */ @Test - public void testManualReloadRetriesFailedReadOfHotReloadTime() { + public void testManualReloadRetriesFailedReadOfAutoReloadTime() { ReloadableSslFactory rest = httpRestFactory(); - when(rest.hotReloadTime()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")) + when(rest.autoReloadTime()).thenThrow(new IgniteException("Failed to read the certificates of the HTTPS connector")) .thenReturn(System.currentTimeMillis() + MINUTES.toMillis(30)); registry.register("HTTP REST", rest); @@ -482,7 +482,7 @@ public void testManualReloadRetriesFailedReadOfHotReloadTime() { } /** - * Given: the registry has started, and the key store still holds certificates that are due for hot reload. + * Given: the registry has started, and the key store still holds certificates that are due for automatic reload. * When: a manual reload loads them. * Then: the failure count is zero, and the next check comes in an hour rather than right away. */ @@ -505,13 +505,13 @@ public void testManualReloadOfDueCertificatesDefersNextCheck() throws Exception * Then: the factory sees no request ID from the operation that started the registry. */ @Test - public void testHotReloadDoesNotInheritStartupContext() throws Exception { + public void testAutoReloadDoesNotInheritStartupContext() throws Exception { executorFactory.when(() -> IgniteScheduledThreadPoolExecutor.newSingleThreadScheduledExecutor(any(), any())).thenCallRealMethod(); OperationContextAttribute reqId = OperationContextAttribute.newInstance(); CompletableFuture reloadReqId = new CompletableFuture<>(); - enableHotReload(factory, due()); + enableAutoReload(factory, due()); doAnswer(call -> { reloadReqId.complete(OperationContext.get(reqId)); @@ -538,7 +538,7 @@ public void testErrorFromOneFactoryDoesNotStopCheck() throws Exception { List logged = captureLog(); SslContextFactory clientConnector = factory(keys); - enableHotReload(factory, due()); + enableAutoReload(factory, due()); doThrow(new NoClassDefFoundError("Key store provider")).when(factory).init(); writeDueCertificates(keys); registry.register("communication", factory); @@ -548,15 +548,15 @@ public void testErrorFromOneFactoryDoesNotStopCheck() throws Exception { runChecks(); assertEquals(1, failures()); - assertEquals(2, metric("AutomaticHotReloadAttempts")); - assertTrue(logged.toString(), logged.contains("TLS hot reload succeeded [transports=client connector]")); - assertTrue(logged.toString(), logged.toString().contains("TLS hot reload failed [transports=communication,")); + assertEquals(2, metric("AutoReloadAttempts")); + assertTrue(logged.toString(), logged.contains("TLS automatic reload succeeded [transports=client connector]")); + assertTrue(logged.toString(), logged.toString().contains("TLS automatic reload failed [transports=communication,")); } /** - * Given: the loaded certificates are due for hot reload, and the key store file is deleted after start. + * Given: the loaded certificates are due for automatic reload, and the key store file is deleted after start. * When: one automatic attempt fails, and the next one loads fresh certificates. - * Then: the log shows when the loaded certificates are due for hot reload, and the start and result of each attempt. + * Then: the log shows when the loaded certificates are due for automatic reload, and the start and result of each attempt. */ @Test public void testLogShowsDueTimeStartAndResultOfAttempts() throws Exception { @@ -567,7 +567,7 @@ public void testLogShowsDueTimeStartAndResultOfAttempts() throws Exception { registerTransport("communication", communication); registry.onKernalStart(true); - long due = communication.hotReloadTime(); + long due = communication.autoReloadTime(); Files.delete(keys); runChecks(); @@ -579,18 +579,18 @@ public void testLogShowsDueTimeStartAndResultOfAttempts() throws Exception { for (String line : logged) { assertTrue(line, line.contains("[transports=communication")); - evts.add(line.substring("TLS hot reload ".length(), line.indexOf(" ["))); + evts.add(line.substring("TLS automatic reload ".length(), line.indexOf(" ["))); } assertEquals(List.of("due", "started", "failed", "started", "succeeded", "due"), evts); - assertTrue(logged.get(0), logged.get(0).endsWith("hotReloadTime=" + new Date(due) + ']')); + assertTrue(logged.get(0), logged.get(0).endsWith("autoReloadTime=" + new Date(due) + ']')); assertTrue(logged.get(2), logged.get(2).contains("nextAttempt=")); - assertTrue(logged.get(5), logged.get(5).endsWith("hotReloadTime=" + new Date(communication.hotReloadTime()) + ']')); + assertTrue(logged.get(5), logged.get(5).endsWith("autoReloadTime=" + new Date(communication.autoReloadTime()) + ']')); } /** - * Given: the loaded certificates are due for hot reload, and the key store file is deleted after start. - * When: one check fails, the source then gets certificates due for hot reload in 23 days, the next check loads them, + * Given: the loaded certificates are due for automatic reload, and the key store file is deleted after start. + * When: one check fails, the source then gets certificates due for automatic reload in 23 days, the next check loads them, * and the check runs again. * Then: both attempts are counted, the success resets the failure count, and the last check makes no attempt. */ @@ -605,17 +605,17 @@ public void testSuccessResetsFailuresAndLaterChecksWait() throws Exception { runChecks(); assertEquals(1, failures()); - assertEquals(1, metric("AutomaticHotReloadAttempts")); + assertEquals(1, metric("AutoReloadAttempts")); writeFreshCertificates(keys); runChecks(); assertEquals(0, failures()); - assertEquals(2, metric("AutomaticHotReloadAttempts")); + assertEquals(2, metric("AutoReloadAttempts")); runChecks(); - assertEquals(2, metric("AutomaticHotReloadAttempts")); + assertEquals(2, metric("AutoReloadAttempts")); } /** @@ -640,7 +640,7 @@ public void testCheckResetsFailuresWhenFactoryIsNoLongerDue() throws Exception { runChecks(); assertEquals(0, failures()); - assertEquals(1, metric("AutomaticHotReloadAttempts")); + assertEquals(1, metric("AutoReloadAttempts")); } /** @@ -655,25 +655,25 @@ public void testManualReloadBeforeStartLoadsFactory() throws Exception { writeDueCertificates(keys); registerTransport("communication", communication); - long prevTime = communication.hotReloadTime(); + long prevTime = communication.autoReloadTime(); writeFreshCertificates(keys); registry.reload(communication); - assertTrue(communication.hotReloadTime() > prevTime); + assertTrue(communication.autoReloadTime() > prevTime); } /** - * Given: a factory with hot reload disabled. + * Given: a factory with automatic reload disabled. * When: a manual reload succeeds, and a second one fails because the key store file is deleted. * Then: both count as manual attempts, and none counts as automatic. */ @Test - public void testManualReloadWithoutHotReloadCountsAppliedAndFailedLoads() throws Exception { + public void testManualReloadWithoutAutoReloadCountsAppliedAndFailedLoads() throws Exception { SslContextFactory communication = factory(keys); writeFreshCertificates(keys); - communication.setHotReloadEnabled(false); + communication.setAutoReloadEnabled(false); registerTransport("communication", communication); registry.onKernalStart(true); registry.reload(communication); @@ -684,11 +684,11 @@ public void testManualReloadWithoutHotReloadCountsAppliedAndFailedLoads() throws assertThrows(IgniteException.class, () -> registry.reload(communication)); assertEquals(2, metric("ManualReloadAttempts")); - assertEquals(0, metric("AutomaticHotReloadAttempts")); + assertEquals(0, metric("AutoReloadAttempts")); } /** - * Given: communication has hot reload disabled and due certificates, and the client connector has hot reload enabled. + * Given: communication has automatic reload disabled and due certificates, and the client connector has automatic reload enabled. * When: communication is reloaded manually, and the scheduled checks run. * Then: the checks make no automatic attempt, as communication gets no scheduled check. */ @@ -699,18 +699,18 @@ public void testManualReloadDoesNotScheduleCheckOfDisabledFactory() throws Excep writeDueCertificates(keys); writeFreshCertificates(clientKeys); - communication.setHotReloadEnabled(false); + communication.setAutoReloadEnabled(false); registerTransport("communication", communication); registerTransport("client connector", factory(clientKeys)); registry.onKernalStart(true); registry.reload(communication); runChecks(); - assertEquals(0, metric("AutomaticHotReloadAttempts")); + assertEquals(0, metric("AutoReloadAttempts")); } /** - * Given: a custom factory has loaded a certificate that is due for hot reload. + * Given: a custom factory has loaded a certificate that is due for automatic reload. * When: the source supplies a new key store and password and the scheduled check runs. * Then: the factory installs the replacement context and schedules its next reload from the new certificate. */ @@ -735,22 +735,22 @@ public void testScheduledReloadUsesCustomFactoryKeyStoreAndPassword() throws Exc long expiry = ((X509Certificate)replacement.getCertificate("node")).getNotAfter().getTime(); - assertEquals(expiry - custom.getHotReloadBeforeExpiryMs(), custom.hotReloadTime()); + assertEquals(expiry - custom.getAutoReloadBeforeExpiryMs(), custom.autoReloadTime()); } /** * Given: a custom factory has loaded a key store with due certificates. * When: a manual reload creates the context without a key store, and the scheduled check runs. - * Then: the factory has no hot reload date, and the check makes no attempt. + * Then: the factory has no automatic reload date, and the check makes no attempt. */ @Test - public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { + public void testLoadWithoutKeyStoreClearsAutoReloadDate() throws Exception { SourceSslContextFactory custom = new SourceSslContextFactory(); custom.setKeys(authority.keyStore("node", at(-1), at(10)), PASSWORD); custom.create(); - assertTrue(custom.hotReloadTime() > 0); + assertTrue(custom.autoReloadTime() > 0); registry.register("communication", custom); registry.onKernalStart(true); @@ -759,8 +759,8 @@ public void testLoadWithoutKeyStoreClearsHotReloadDate() throws Exception { registry.reload(custom); runChecks(); - assertEquals(0, custom.hotReloadTime()); - assertEquals(0, metric("AutomaticHotReloadAttempts")); + assertEquals(0, custom.autoReloadTime()); + assertEquals(0, metric("AutoReloadAttempts")); } /** @@ -801,12 +801,12 @@ public void testFailedManualReloadKeepsFailures() throws Exception { } /** - * Given: communication only reloads manually, and the client connector is due for hot reload. + * Given: communication only reloads manually, and the client connector is due for automatic reload. * When: the scheduled check runs while communication is waiting for its certificate source. * Then: the client connector loads its replacement before the manual reload finishes. */ @Test - public void testManualOnlyFactoryDoesNotDelayHotReload() throws Exception { + public void testManualOnlyFactoryDoesNotDelayAutoReload() throws Exception { SslContextFactory clientConnector = factory(keys); CountDownLatch manualStarted = new CountDownLatch(1); CountDownLatch finishManual = new CountDownLatch(1); @@ -823,7 +823,7 @@ public void testManualOnlyFactoryDoesNotDelayHotReload() throws Exception { registerTransport("client connector", clientConnector); registry.onKernalStart(true); - long prevTime = clientConnector.hotReloadTime(); + long prevTime = clientConnector.autoReloadTime(); writeFreshCertificates(keys); @@ -833,7 +833,7 @@ public void testManualOnlyFactoryDoesNotDelayHotReload() throws Exception { assertTrue(manualStarted.await(TIMEOUT_MS, MILLISECONDS)); runAsync(nextCheck()).get(TIMEOUT_MS); - assertTrue(clientConnector.hotReloadTime() > prevTime); + assertTrue(clientConnector.autoReloadTime() > prevTime); } finally { finishManual.countDown(); @@ -859,7 +859,7 @@ public void testManualReloadWaitsForRunningAttempt() throws Exception { Files.delete(keys); when(executor.isShutdown()).thenAnswer(call -> { - if (metric("AutomaticHotReloadAttempts") > 0) { + if (metric("AutoReloadAttempts") > 0) { attemptFailed.countDown(); assertTrue(resumeAttempt.await(TIMEOUT_MS, MILLISECONDS)); @@ -942,13 +942,13 @@ public void testManualReloadResetsOnlyItsFactoryFailures() throws Exception { @Test public void testStopInterruptsActiveAttemptWithoutWaitingForIt() throws Exception { executorFactory.when(() -> IgniteScheduledThreadPoolExecutor.newSingleThreadScheduledExecutor(any(), any())) - .thenReturn(new IgniteScheduledThreadPoolExecutor("ssl-hot-reload", null, 1)); + .thenReturn(new IgniteScheduledThreadPoolExecutor("ssl-auto-reload", null, 1)); CountDownLatch attemptStarted = new CountDownLatch(1); CountDownLatch attemptInterrupted = new CountDownLatch(1); CountDownLatch allowCompletion = new CountDownLatch(1); - enableHotReload(factory, due()); + enableAutoReload(factory, due()); doAnswer(call -> { attemptStarted.countDown(); @@ -989,7 +989,7 @@ public void testStopInterruptsActiveAttemptWithoutWaitingForIt() throws Exceptio public void testAttemptFailingDuringStopIsNotCounted() { List logged = captureLog(true); - enableHotReload(factory, due()); + enableAutoReload(factory, due()); doAnswer(call -> { when(executor.isShutdown()).thenReturn(true); @@ -1001,9 +1001,9 @@ public void testAttemptFailingDuringStopIsNotCounted() { runChecks(); assertEquals(0, failures()); - assertTrue(logged.toString(), logged.contains("TLS hot reload check started [transports=communication]")); + assertTrue(logged.toString(), logged.contains("TLS automatic reload check started [transports=communication]")); assertTrue(logged.toString(), - logged.toString().contains("TLS hot reload failed during node stop [transports=communication, err=")); + logged.toString().contains("TLS automatic reload failed during node stop [transports=communication, err=")); } /** @@ -1016,8 +1016,8 @@ public void testStopDuringCheckSkipsRemainingFactories() { SslContextFactory clientConnector = mock(SslContextFactory.class); AtomicInteger loads = new AtomicInteger(); - enableHotReload(factory, due()); - enableHotReload(clientConnector, due()); + enableAutoReload(factory, due()); + enableAutoReload(clientConnector, due()); for (SslContextFactory sslFactory : List.of(factory, clientConnector)) { doAnswer(call -> { @@ -1036,13 +1036,13 @@ public void testStopDuringCheckSkipsRemainingFactories() { assertEquals(1, loads.get()); } - /** Replaces the registry with one that logs to a listener and returns its hot reload lines at info level and above. */ + /** Replaces the registry with one that logs to a listener and returns its automatic reload lines at info level and above. */ private List captureLog() { return captureLog(false); } /** - * Replaces the registry with one that logs to a listener and returns the hot reload lines it logs, in order. + * Replaces the registry with one that logs to a listener and returns the automatic reload lines it logs, in order. * Tests call it before they register factories. * * @param debug Whether the registry logs debug lines too. @@ -1052,7 +1052,7 @@ private List captureLog(boolean debug) { List logged = new ArrayList<>(); log.registerListener(line -> { - if (line.startsWith("TLS hot reload ")) + if (line.startsWith("TLS automatic reload ")) logged.add(line); }); when(ctx.log(SslFactoryRegistry.class)).thenReturn(log); @@ -1098,7 +1098,7 @@ private void registerTransport(String transport, SslContextFactory factory) { /** */ private long failures() { - return metric("ConsecutiveHotReloadFailures"); + return metric("ConsecutiveAutoReloadFailures"); } /** */ @@ -1107,27 +1107,27 @@ private long metric(String name) { } /** - * Makes the factory mock look like a factory with hot reload enabled and loaded certificates with the given date. - * The mock returns {@code true} from {@code isHotReloadEnabled()} and the date from {@code hotReloadTime()}. + * Makes the factory mock look like a factory with automatic reload enabled and loaded certificates with the given date. + * The mock returns {@code true} from {@code isAutoReloadEnabled()} and the date from {@code autoReloadTime()}. * * @param factory Factory mock. - * @param hotReloadTime Hot reload time of the loaded certificates. + * @param autoReloadTime Automatic reload time of the loaded certificates. */ - private static void enableHotReload(SslContextFactory factory, long hotReloadTime) { - when(factory.isHotReloadEnabled()).thenReturn(true); - when(factory.hotReloadTime()).thenReturn(hotReloadTime); + private static void enableAutoReload(SslContextFactory factory, long autoReloadTime) { + when(factory.isAutoReloadEnabled()).thenReturn(true); + when(factory.autoReloadTime()).thenReturn(autoReloadTime); } - /** @return Mock of a factory with hot reload enabled that is not an Ignite SSL context factory, such as the one of HTTP REST. */ + /** @return Mock of a factory with automatic reload enabled that is not an Ignite SSL context factory, such as the one of HTTP REST. */ private static ReloadableSslFactory httpRestFactory() { ReloadableSslFactory factory = mock(ReloadableSslFactory.class); - when(factory.isHotReloadEnabled()).thenReturn(true); + when(factory.isAutoReloadEnabled()).thenReturn(true); return factory; } - /** @return Hot reload time that has already come. */ + /** @return Automatic reload time that has already come. */ private static long due() { return System.currentTimeMillis(); } @@ -1151,7 +1151,7 @@ private SslContextFactory factory(Path keyStore, SslContextFactory sslFactory) { } /** - * Writes a key store that is already due for hot reload with the default lead time. + * Writes a key store that is already due for automatic reload with the default lead time. * Its certificate expires in 10 hours. */ private void writeDueCertificates(Path keyStore) throws Exception { @@ -1159,7 +1159,7 @@ private void writeDueCertificates(Path keyStore) throws Exception { } /** - * Writes a key store that is due for hot reload in 30 minutes with the default lead time. + * Writes a key store that is due for automatic reload in 30 minutes with the default lead time. * Its certificate became valid an hour ago and expires in 7 days and 30 minutes. */ private void writeCertificatesDueIn30Minutes(Path keyStore) throws Exception { @@ -1174,7 +1174,7 @@ private static boolean isAbout30Minutes(long delay) { } /** - * Writes a key store that is due for hot reload in 23 days with the default lead time. + * Writes a key store that is due for automatic reload in 23 days with the default lead time. * Its certificate became valid an hour ago and expires in 30 days. */ private void writeFreshCertificates(Path keyStore) throws Exception { diff --git a/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java b/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java index 7c93e451113a4..fa7b3cad45666 100644 --- a/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java +++ b/modules/core/src/test/java/org/apache/ignite/ssl/SslCertificateHotReloadTest.java @@ -48,15 +48,15 @@ public class SslCertificateHotReloadTest extends GridCommonAbstractTest { /** * Given: the factory has loaded due certificates of one CA, and the files then get certificates of another CA. - * When: the node starts, and its hot reload attempt runs. + * When: the node starts, and its automatic reload attempt runs. * Then: the node installs the new certificates, and a client that trusts and presents only them connects. */ @Test - public void testNodeHotReloadsCertificatesForNewConnections() throws Exception { + public void testNodeAutoReloadsCertificatesForNewConnections() throws Exception { long now = System.currentTimeMillis(); TestCertificateAuthority ca1 = new TestCertificateAuthority("ca1", now - DAYS.toMillis(1), now + DAYS.toMillis(10)); TestCertificateAuthority ca2 = new TestCertificateAuthority("ca2", now - DAYS.toMillis(1), now + DAYS.toMillis(10)); - Path dir = Files.createTempDirectory("ssl-hot-reload"); + Path dir = Files.createTempDirectory("ssl-auto-reload"); Path keys = dir.resolve("keys.jks"); Path trust = dir.resolve("trust.jks"); @@ -68,7 +68,7 @@ public void testNodeHotReloadsCertificatesForNewConnections() throws Exception { SSLContext initCtx = serverFactory.create(); - assertTrue("Hot reload must be due at startup", serverFactory.hotReloadTime() < now); + assertTrue("Automatic reload must be due at startup", serverFactory.autoReloadTime() < now); save(ca2.keyStore("node", now - MINUTES.toMillis(1), now + DAYS.toMillis(10)), keys); save(ca2.trustStore(), trust); @@ -95,20 +95,20 @@ public void testNodeHotReloadsCertificatesForNewConnections() throws Exception { } /** - * Given: a node starts with expired certificates, so hot reload stays due. + * Given: a node starts with expired certificates, so automatic reload stays due. * When: the automatic attempt reloads the same certificates. * Then: the node counts the failure and logs the transport and the reason. */ @Test - public void testNodeReportsHotReloadFailureForExpiredCertificates() throws Exception { + public void testNodeReportsAutoReloadFailureForExpiredCertificates() throws Exception { long now = System.currentTimeMillis(); TestCertificateAuthority ca = new TestCertificateAuthority("ca", now - DAYS.toMillis(1), now + DAYS.toMillis(10)); - Path dir = Files.createTempDirectory("ssl-hot-reload"); + Path dir = Files.createTempDirectory("ssl-auto-reload"); Path keys = dir.resolve("keys.jks"); Path trust = dir.resolve("trust.jks"); ListeningTestLogger nodeLog = new ListeningTestLogger(log); - LogListener failure = LogListener.matches("TLS hot reload failed [transports=client connector").build(); - LogListener reason = LogListener.matches("Loaded certificates are still due for hot reload").build(); + LogListener failure = LogListener.matches("TLS automatic reload failed [transports=client connector").build(); + LogListener reason = LogListener.matches("Loaded certificates are still due for automatic reload").build(); nodeLog.registerListener(failure); nodeLog.registerListener(reason); @@ -122,7 +122,7 @@ public void testNodeReportsHotReloadFailureForExpiredCertificates() throws Excep IgniteEx node = startGrid(0, cfg -> { cfg.setGridLogger(nodeLog).setClientConnectorConfiguration(sslClientConnector(serverFactory)); }); - LongMetric failures = node.context().metric().registry("ssl").findMetric("ConsecutiveHotReloadFailures"); + LongMetric failures = node.context().metric().registry("ssl").findMetric("ConsecutiveAutoReloadFailures"); assertTrue("The automatic attempt did not fail", waitForCondition(() -> failures.value() > 0, TIMEOUT_MS)); assertTrue(failure.check(TIMEOUT_MS)); @@ -135,15 +135,15 @@ public void testNodeReportsHotReloadFailureForExpiredCertificates() throws Excep } /** - * Given: a node with a TLS transport runs its hot reload thread. + * Given: a node with a TLS transport runs its automatic reload thread. * When: the node stops. - * Then: the hot reload thread ends. + * Then: the automatic reload thread ends. */ @Test - public void testNodeStopEndsHotReloadThread() throws Exception { + public void testNodeStopEndsAutoReloadThread() throws Exception { long now = System.currentTimeMillis(); TestCertificateAuthority ca = new TestCertificateAuthority("ca", now - DAYS.toMillis(1), now + DAYS.toMillis(10)); - Path dir = Files.createTempDirectory("ssl-hot-reload"); + Path dir = Files.createTempDirectory("ssl-auto-reload"); Path keys = dir.resolve("keys.jks"); Path trust = dir.resolve("trust.jks"); @@ -157,19 +157,19 @@ public void testNodeStopEndsHotReloadThread() throws Exception { cfg.setClientConnectorConfiguration(sslClientConnector(serverFactory)); }); - Thread hotReload = null; + Thread autoReload = null; for (Thread thread : Thread.getAllStackTraces().keySet()) { - if (thread.getName().startsWith("ssl-hot-reload") && thread.getName().contains(node.name())) - hotReload = thread; + if (thread.getName().startsWith("ssl-auto-reload") && thread.getName().contains(node.name())) + autoReload = thread; } - assertNotNull("The hot reload thread is not running", hotReload); + assertNotNull("The automatic reload thread is not running", autoReload); stopAllGrids(); - hotReload.join(TIMEOUT_MS); + autoReload.join(TIMEOUT_MS); - assertFalse("The hot reload thread is still running", hotReload.isAlive()); + assertFalse("The automatic reload thread is still running", autoReload.isAlive()); } finally { stopAllGrids(); @@ -181,10 +181,10 @@ public void testNodeStopEndsHotReloadThread() throws Exception { * Given: a node with the client connector and REST, which stop their servers in their own {@code onKernalStop}. * When: the node starts its components. * Then: the SSL factory registry comes after both, so the node, which stops components in reverse order, - * stops hot reload before them. + * stops automatic reload before them. */ @Test - public void testHotReloadStopsBeforeClientConnectorAndRest() throws Exception { + public void testAutoReloadStopsBeforeClientConnectorAndRest() throws Exception { IgniteEx node = startGrid(0); try { diff --git a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java index 503ebf6d79948..ae9431e1fbc61 100644 --- a/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java +++ b/modules/core/src/test/java/org/apache/ignite/ssl/SslContextFactoryHotReloadTest.java @@ -43,7 +43,7 @@ import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.apache.ignite.ssl.SslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; +import static org.apache.ignite.ssl.SslContextFactory.DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS; import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD; import static org.apache.ignite.ssl.TestCertificateAuthority.merge; import static org.apache.ignite.ssl.TestCertificateAuthority.save; @@ -84,26 +84,26 @@ public void setUp() throws Exception { } /** - * Given: a key store with only a CA certificate and the default hot reload setting. + * Given: a key store with only a CA certificate and the default automatic reload setting. * When: the factory loads the store. - * Then: the load succeeds with hot reload enabled and no scheduled reload date. + * Then: the load succeeds with automatic reload enabled and no scheduled reload date. */ @Test public void testDefaultSettingsAcceptStoreWithoutPrivateKeys() throws Exception { InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.trustStore()); - assertTrue(factory.isHotReloadEnabled()); + assertTrue(factory.isAutoReloadEnabled()); assertNotNull(factory.create()); - assertEquals(0, factory.hotReloadTime()); + assertEquals(0, factory.autoReloadTime()); } /** * Given: a factory has loaded a certificate that expires in 10 days. * When: the application increases the lead time from the default of 7 days to 14 days before starting the node. - * Then: the same certificate is already due for hot reload. + * Then: the same certificate is already due for automatic reload. */ @Test - public void testHotReloadTimeUsesCurrentLeadTime() throws Exception { + public void testAutoReloadTimeUsesCurrentLeadTime() throws Exception { Path keys = tmp.newFile("keys.jks").toPath(); save(authority.keyStore("node", at(-1), at(DAYS.toHours(10))), keys); @@ -115,11 +115,11 @@ public void testHotReloadTimeUsesCurrentLeadTime() throws Exception { factory.setTrustManagers(SslContextFactory.getDisabledTrustManager()); factory.create(); - assertEquals(at(DAYS.toHours(3)), factory.hotReloadTime()); + assertEquals(at(DAYS.toHours(3)), factory.autoReloadTime()); - factory.setHotReloadBeforeExpiryMs(DAYS.toMillis(14)); + factory.setAutoReloadBeforeExpiryMs(DAYS.toMillis(14)); - assertEquals(at(-DAYS.toHours(4)), factory.hotReloadTime()); + assertEquals(at(-DAYS.toHours(4)), factory.autoReloadTime()); } /** @@ -128,12 +128,12 @@ public void testHotReloadTimeUsesCurrentLeadTime() throws Exception { * Then: the setter rejects it and keeps the default. */ @Test - public void testNonPositiveHotReloadBeforeExpiryMsIsRejected() { + public void testNonPositiveAutoReloadBeforeExpiryMsIsRejected() { SslContextFactory factory = new SslContextFactory(); - assertThrows(IllegalArgumentException.class, () -> factory.setHotReloadBeforeExpiryMs(0)); - assertThrows(IllegalArgumentException.class, () -> factory.setHotReloadBeforeExpiryMs(-1)); - assertEquals(DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS, factory.getHotReloadBeforeExpiryMs()); + assertThrows(IllegalArgumentException.class, () -> factory.setAutoReloadBeforeExpiryMs(0)); + assertThrows(IllegalArgumentException.class, () -> factory.setAutoReloadBeforeExpiryMs(-1)); + assertEquals(DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS, factory.getAutoReloadBeforeExpiryMs()); } /** @@ -141,10 +141,10 @@ public void testNonPositiveHotReloadBeforeExpiryMsIsRejected() { * In one of them, that chain gets its expiry from an issuer that expires before the key certificate. * Other entries are a chain that expires later, a secret key and a key with a certificate chain that is not X.509. * When: the factory loads each key store. - * Then: hot reload is due now, 15 hours before the chain that expires first. + * Then: automatic reload is due now, 15 hours before the chain that expires first. */ @Test - public void testHotReloadTimeComesFromEarliestExpiringChain() throws Exception { + public void testAutoReloadTimeComesFromEarliestExpiringChain() throws Exception { TestCertificateAuthority shortIssuer = new TestCertificateAuthority("short-issuer", now - DAYS.toMillis(365), at(15)); KeyStore node = authority.keyStore("node", at(-85), at(15)); KeyStore withUnusableKeys = KeyStore.getInstance("JCEKS"); @@ -155,17 +155,17 @@ public void testHotReloadTimeComesFromEarliestExpiringChain() throws Exception { withUnusableKeys.setKeyEntry("other", node.getKey("node", PASSWORD), PASSWORD, new Certificate[] {new OtherCertificate(node.getCertificate("node").getPublicKey())}); - assertHotReloadIsDueNow(node); - assertHotReloadIsDueNow(shortIssuer.keyStore("node", at(-85), at(100))); - assertHotReloadIsDueNow(merge(authority.keyStore("first", at(-85), at(15)), authority.keyStore("second", at(-200), at(100)))); - assertHotReloadIsDueNow(merge(authority.keyStore("first", at(-200), at(100)), authority.keyStore("second", at(-85), at(15)))); - assertHotReloadIsDueNow(withUnusableKeys); + assertAutoReloadIsDueNow(node); + assertAutoReloadIsDueNow(shortIssuer.keyStore("node", at(-85), at(100))); + assertAutoReloadIsDueNow(merge(authority.keyStore("first", at(-85), at(15)), authority.keyStore("second", at(-200), at(100)))); + assertAutoReloadIsDueNow(merge(authority.keyStore("first", at(-200), at(100)), authority.keyStore("second", at(-85), at(15)))); + assertAutoReloadIsDueNow(withUnusableKeys); } /** * Given: a factory and an in-memory key store that counts its reads. * When: the factory loads its certificates. - * Then: it reads the key store once, so the hot reload date matches the loaded key managers. + * Then: it reads the key store once, so the automatic reload date matches the loaded key managers. */ @Test public void testLoadReadsKeyStoreOnce() throws Exception { @@ -179,7 +179,7 @@ public void testLoadReadsKeyStoreOnce() throws Exception { /** * Given: the issuer expired an hour ago, and the key certificate becomes valid in 99 hours. * When: the factory loads the chain for the first time. - * Then: the load succeeds, and hot reload has been due since 15 hours before the issuer expired. + * Then: the load succeeds, and automatic reload has been due since 15 hours before the issuer expired. */ @Test public void testFirstLoadAcceptsChainOutsideValidityPeriod() throws Exception { @@ -188,16 +188,16 @@ public void testFirstLoadAcceptsChainOutsideValidityPeriod() throws Exception { factory.create(); - assertEquals(at(-16), factory.hotReloadTime()); + assertEquals(at(-16), factory.autoReloadTime()); } /** * Given: the key store returns a certificate chain for an entry without a private key, as Windows-MY does. * When: the factory loads the key store. - * Then: the load succeeds, and the factory has no hot reload date. + * Then: the load succeeds, and the factory has no automatic reload date. */ @Test - public void testStoreWithoutPrivateKeyLoadsWithoutHotReloadDate() throws Exception { + public void testStoreWithoutPrivateKeyLoadsWithoutAutoReloadDate() throws Exception { KeyStore store = spy(authority.trustStore()); String alias = store.aliases().nextElement(); @@ -206,7 +206,7 @@ public void testStoreWithoutPrivateKeyLoadsWithoutHotReloadDate() throws Excepti InMemorySslContextFactory factory = new InMemorySslContextFactory(store); assertNotNull(factory.create()); - assertEquals(0, factory.hotReloadTime()); + assertEquals(0, factory.autoReloadTime()); } /** @@ -301,7 +301,7 @@ public void testReloadRecoversAfterFailedTrustStoreLoad() throws Exception { factory.useTrustStore(trust.toString()); SSLContext ctx = factory.create(); - long hotReloadTime = factory.hotReloadTime(); + long autoReloadTime = factory.autoReloadTime(); factory.keyStore = authority.keyStore("node", at(-1), at(99)); Files.delete(trust); @@ -310,24 +310,24 @@ public void testReloadRecoversAfterFailedTrustStoreLoad() throws Exception { assertTrue(err.getCause().getMessage(), err.getCause().getMessage().contains("key store file was not found")); assertSame(ctx, factory.create()); - assertEquals(hotReloadTime, factory.hotReloadTime()); + assertEquals(autoReloadTime, factory.autoReloadTime()); save(authority.trustStore(), trust); factory.init(); assertNotSame(ctx, factory.create()); - assertEquals(at(84), factory.hotReloadTime()); + assertEquals(at(84), factory.autoReloadTime()); } /** * Given: a reload of certificates with a new date blocks on the trust store load. - * When: another thread reads {@link SslContextFactory#hotReloadTime()} during the reload. + * When: another thread reads {@link SslContextFactory#autoReloadTime()} during the reload. * Then: the read returns the current date without waiting for the reload. */ @Test - public void testHotReloadTimeRemainsReadableDuringLoad() throws Exception { + public void testAutoReloadTimeRemainsReadableDuringLoad() throws Exception { InMemorySslContextFactory factory = spy(dueFactory()); - long hotReloadTime = factory.hotReloadTime(); + long autoReloadTime = factory.autoReloadTime(); factory.keyStore = authority.keyStore("node", at(-1), at(99)); @@ -349,7 +349,7 @@ public void testHotReloadTimeRemainsReadableDuringLoad() throws Exception { try { assertTrue(trustLoadStarted.await(TIMEOUT_MS, MILLISECONDS)); - assertEquals(hotReloadTime, factory.hotReloadTime()); + assertEquals(autoReloadTime, factory.autoReloadTime()); } finally { finishTrustLoad.countDown(); @@ -361,7 +361,7 @@ public void testHotReloadTimeRemainsReadableDuringLoad() throws Exception { } /** - * Creates a factory that has loaded certificates due for hot reload 5 hours ago. + * Creates a factory that has loaded certificates due for automatic reload 5 hours ago. * It reads both stores from memory. The certificates expire in 10 hours. */ private InMemorySslContextFactory dueFactory() throws Exception { @@ -371,18 +371,18 @@ private InMemorySslContextFactory dueFactory() throws Exception { factory.useTrustStore("memory-trust"); factory.create(); - assertEquals(at(-5), factory.hotReloadTime()); + assertEquals(at(-5), factory.autoReloadTime()); return factory; } /** */ - private void assertHotReloadIsDueNow(KeyStore keys) { + private void assertAutoReloadIsDueNow(KeyStore keys) { InMemorySslContextFactory factory = new InMemorySslContextFactory(keys); factory.create(); - assertEquals(now, factory.hotReloadTime()); + assertEquals(now, factory.autoReloadTime()); } /** @@ -431,7 +431,7 @@ private long at(long hours) { * A factory that reads its key store from a field instead of a file and counts the reads. * Tests change the field to put new certificates into the source. * By default the factory trusts all peers. Tests can configure a trust store from memory or a file. - * Hot reload is due 15 hours before expiry, so the tests count certificate dates in hours. + * Automatic reload is due 15 hours before expiry, so the tests count certificate dates in hours. */ private static class InMemorySslContextFactory extends SslContextFactory { /** */ @@ -453,7 +453,7 @@ private InMemorySslContextFactory(KeyStore keyStore) { setKeyStoreFilePath("memory"); setKeyStorePassword(PASSWORD); setTrustManagers(getDisabledTrustManager()); - setHotReloadBeforeExpiryMs(HOURS.toMillis(15)); + setAutoReloadBeforeExpiryMs(HOURS.toMillis(15)); } /** Selects the trust store that supplies the factory's trust managers. */ diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java index 04554b7259bdb..47002fc8cfa6d 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java @@ -25,17 +25,17 @@ import org.apache.ignite.IgniteException; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; import org.apache.ignite.ssl.AbstractSslContextFactory; -import org.apache.ignite.ssl.jetty.ReloadableJettySslFactory; +import org.apache.ignite.ssl.jetty.AutoReloadJettySslFactory; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.jetbrains.annotations.Nullable; -import static org.apache.ignite.ssl.AbstractSslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; +import static org.apache.ignite.ssl.AbstractSslContextFactory.DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS; /** * Adapter through which the SSL factory registry reloads the TLS factory of the Jetty HTTPS connector. A failed reload * leaves the previous keys and trust settings in use. - * Hot reload follows the settings of the Jetty factory if it implements {@link ReloadableJettySslFactory}. Otherwise - * hot reload is enabled with the lead time {@link AbstractSslContextFactory#DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. + * Automatic reload follows the settings of the Jetty factory if it implements {@link AutoReloadJettySslFactory}. Otherwise + * automatic reload is enabled with the lead time {@link AbstractSslContextFactory#DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS}. *

* Jetty's factory guards its TLS state with an internal lock: it loads the state under this lock, and new connections * take the state under it too. Before loading a replacement, Jetty clears the state. So that new connections never see @@ -45,7 +45,7 @@ * Jetty selects certificates for SNI host names from the key store of the state, so the restore keeps SNI selection. * If the restore fails too, the factory has no state until the next successful reload, and the reload error carries * that failure as a suppressed exception. A failed reload outside Ignite, such as one by Jetty's {@code KeyStoreScanner}, - * can also leave the factory without state. Such a factory is due for hot reload right away, and the reload has nothing + * can also leave the factory without state. Such a factory is due for automatic reload right away, and the reload has nothing * to restore: it loads the configured sources. *

* After a failed reload, the factory gets back the context and stores set in {@code jetty.xml}, and the next reload @@ -91,12 +91,12 @@ class JettySslFactoryAdapter implements ReloadableSslFactory { } /** {@inheritDoc} */ - @Override public boolean isHotReloadEnabled() { - return !(factory instanceof ReloadableJettySslFactory reloadable) || reloadable.isHotReloadEnabled(); + @Override public boolean isAutoReloadEnabled() { + return !(factory instanceof AutoReloadJettySslFactory reloadable) || reloadable.isAutoReloadEnabled(); } /** {@inheritDoc} */ - @Override public long hotReloadTime() { + @Override public long autoReloadTime() { TlsState state = currentState(); if (state == null) @@ -106,18 +106,18 @@ class JettySslFactoryAdapter implements ReloadableSslFactory { KeyStore store = state.keyStore(); long expiry = store == null ? 0 : ReloadableSslFactory.keyChainsExpiry(store); - return expiry == 0 ? 0 : expiry - hotReloadBeforeExpiryMs(); + return expiry == 0 ? 0 : expiry - autoReloadBeforeExpiryMs(); } catch (GeneralSecurityException e) { throw new IgniteException("Failed to read the certificates of the HTTPS connector", e); } } - /** @return How long before the certificates expire hot reload becomes due, in milliseconds. */ - private long hotReloadBeforeExpiryMs() { - return factory instanceof ReloadableJettySslFactory reloadable - ? reloadable.getHotReloadBeforeExpiryMs() - : DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; + /** @return How long before the certificates expire automatic reload becomes due, in milliseconds. */ + private long autoReloadBeforeExpiryMs() { + return factory instanceof AutoReloadJettySslFactory reloadable + ? reloadable.getAutoReloadBeforeExpiryMs() + : DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS; } /** diff --git a/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/ReloadableJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/AutoReloadJettySslFactory.java similarity index 76% rename from modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/ReloadableJettySslFactory.java rename to modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/AutoReloadJettySslFactory.java index dbe26848d4ecc..ee3c739a89450 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/ReloadableJettySslFactory.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/AutoReloadJettySslFactory.java @@ -20,19 +20,19 @@ import org.apache.ignite.ssl.AbstractSslContextFactory; /** - * Hot reload settings of a Jetty SSL context factory that serves HTTPS for the HTTP REST endpoint. To change the settings + * Automatic reload settings of a Jetty SSL context factory that serves HTTPS for the HTTP REST endpoint. To change the settings * of a factory, implement this interface in a subclass of Jetty's {@code SslContextFactory.Server}, add setters for both * properties, and set them on the factory in the Jetty XML file. A factory that does not implement this interface keeps - * hot reload enabled with the lead time {@link AbstractSslContextFactory#DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS}. + * automatic reload enabled with the lead time {@link AbstractSslContextFactory#DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS}. * The reload command reloads the factory either way. */ -public interface ReloadableJettySslFactory { +public interface AutoReloadJettySslFactory { /** @return Whether Ignite reloads the factory before its certificates expire. Changes require a node restart. */ - public boolean isHotReloadEnabled(); + public boolean isAutoReloadEnabled(); /** - * @return How long before the earliest certificate expiry in the private key chains hot reload becomes due, + * @return How long before the earliest certificate expiry in the private key chains automatic reload becomes due, * in milliseconds. Must be positive. */ - public long getHotReloadBeforeExpiryMs(); + public long getAutoReloadBeforeExpiryMs(); } diff --git a/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/package-info.java b/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/package-info.java index f1918e167b916..4fe92d391540d 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/package-info.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/package-info.java @@ -17,7 +17,7 @@ /** * - * Contains hot reload settings of Jetty SSL context factories that serve HTTPS for the HTTP REST endpoint. + * Contains automatic reload settings of Jetty SSL context factories that serve HTTPS for the HTTP REST endpoint. */ package org.apache.ignite.ssl.jetty; diff --git a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java index 53572b5c692d2..d0306a40d1bac 100644 --- a/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -41,7 +41,7 @@ import org.apache.ignite.internal.management.ssl.SslReloadCommand; import org.apache.ignite.internal.processors.ssl.ReloadableSslFactory; import org.apache.ignite.ssl.TestCertificateAuthority; -import org.apache.ignite.ssl.jetty.ReloadableJettySslFactory; +import org.apache.ignite.ssl.jetty.AutoReloadJettySslFactory; import org.apache.ignite.testframework.junits.WithSystemProperty; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.eclipse.jetty.util.resource.Resource; @@ -57,7 +57,7 @@ import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REST_JETTY_PORT; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_REST_TCP_PORT; import static org.apache.ignite.internal.processors.rest.protocols.http.jetty.GridJettyRestProtocol.DFLT_JETTY_PORT; -import static org.apache.ignite.ssl.AbstractSslContextFactory.DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; +import static org.apache.ignite.ssl.AbstractSslContextFactory.DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS; import static org.apache.ignite.ssl.TestCertificateAuthority.PASSWORD; import static org.apache.ignite.ssl.TestCertificateAuthority.save; import static org.apache.ignite.testframework.GridTestUtils.assertThrows; @@ -69,7 +69,7 @@ * and requires an SNI host name ({@code jetty/https.xml}); {@code jetty/https-detector.xml} reads the same file through * a connector that accepts HTTP and HTTPS on one port. The custom factory ({@code jetty/https-source.xml}) takes its * key stores from {@link SourceSslContextFactory}; {@code jetty/https-source-manual.xml} configures the same source - * with hot reload disabled. The connectors in these files set no port, so the tests set {@code IGNITE_JETTY_PORT}; + * with automatic reload disabled. The connectors in these files set no port, so the tests set {@code IGNITE_JETTY_PORT}; * otherwise the node would publish port 0. */ @WithSystemProperty(key = IGNITE_JETTY_PORT, value = DFLT_JETTY_PORT) @@ -181,12 +181,12 @@ public void testFailedReloadKeepsLastWorkingKeys() throws Exception { } /** - * Given: a custom Jetty factory starts with certificate A, which is due for hot reload, and its source then supplies B. - * When: the node runs its hot reload check at startup, then the source fails and the operator runs the reload command. + * Given: a custom Jetty factory starts with certificate A, which is due for automatic reload, and its source then supplies B. + * When: the node runs its automatic reload check at startup, then the source fails and the operator runs the reload command. * Then: a new client sees B after the check. The command fails, and a new client still sees B. */ @Test - public void testHotReloadedKeysSurviveFailedManualReload() throws Exception { + public void testAutoReloadedKeysSurviveFailedManualReload() throws Exception { KeyStore a = due(); KeyStore b = fresh(); @@ -214,11 +214,11 @@ public void testHotReloadedKeysSurviveFailedManualReload() throws Exception { * Given: a custom Jetty factory has loaded certificate A, valid for 30 days. * When: the factory reloads by itself and gets certificate B, which was issued 20 hours ago and expires in an hour. * Then its source fails, and Ignite reloads the factory. - * Then: the hot reload date comes 7 days before the certificate in use expires: 23 days ahead for A, 7 days before + * Then: the automatic reload date comes 7 days before the certificate in use expires: 23 days ahead for A, 7 days before * the expiry of B for B. The failed reload keeps B's date. */ @Test - public void testHotReloadTimeFollowsKeysInUse() throws Exception { + public void testAutoReloadTimeFollowsKeysInUse() throws Exception { SourceSslContextFactory.supply(fresh(), due(), new IOException("Source is unavailable")); SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); @@ -227,15 +227,15 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { jettyFactory.start(); try { - assertEquals(now + DAYS.toMillis(23), adapter.hotReloadTime()); + assertEquals(now + DAYS.toMillis(23), adapter.autoReloadTime()); jettyFactory.reload(f -> { }); long dueB = now + HOURS.toMillis(1) - DAYS.toMillis(7); - assertEquals(dueB, adapter.hotReloadTime()); + assertEquals(dueB, adapter.autoReloadTime()); assertThrows(log, adapter::init, IgniteException.class, "Source is unavailable"); - assertEquals(dueB, adapter.hotReloadTime()); + assertEquals(dueB, adapter.autoReloadTime()); } finally { jettyFactory.stop(); @@ -243,17 +243,17 @@ public void testHotReloadTimeFollowsKeysInUse() throws Exception { } /** - * Given: binary REST and HTTPS use separate factories and key stores, and the Jetty XML file disables hot reload - * of the HTTPS factory. Both serve certificate A. A of HTTPS is due for hot reload at start. A of binary REST + * Given: binary REST and HTTPS use separate factories and key stores, and the Jetty XML file disables automatic reload + * of the HTTPS factory. Both serve certificate A. A of HTTPS is due for automatic reload at start. A of binary REST * becomes due 5 seconds after the test creates it, so on a usual start binary REST reloads after any check of * HTTPS at start. Both sources hold replacement B. The HTTPS source fails any load after the second one, so * an automatic load of HTTPS before the command makes the command fail. - * When: hot reload loads B for binary REST, and then the operator runs the reload command. - * Then: after hot reload, a new binary REST client sees B, and a new HTTPS client still sees A. After the command, + * When: automatic reload loads B for binary REST, and then the operator runs the reload command. + * Then: after automatic reload, a new binary REST client sees B, and a new HTTPS client still sees A. After the command, * a new HTTPS client sees B. */ @Test - public void testHttpsFactoryWithHotReloadDisabledWaitsForReloadCommand() throws Exception { + public void testHttpsFactoryWithAutoReloadDisabledWaitsForReloadCommand() throws Exception { KeyStore binaryA = ca.keyStore(HOST, now - HOURS.toMillis(1), now + DAYS.toMillis(7) + SECONDS.toMillis(5)); KeyStore binaryB = fresh(); KeyStore httpsA = due(); @@ -291,23 +291,23 @@ public void testHttpsFactoryWithHotReloadDisabledWaitsForReloadCommand() throws } /** - * Given: a custom Jetty factory that implements {@link ReloadableJettySslFactory} sets a lead time of an hour, and + * Given: a custom Jetty factory that implements {@link AutoReloadJettySslFactory} sets a lead time of an hour, and * has loaded a certificate valid for 30 days. - * When: Ignite reads the hot reload time of the factory. - * Then: hot reload becomes due an hour before the certificate expires. + * When: Ignite reads the automatic reload time of the factory. + * Then: automatic reload becomes due an hour before the certificate expires. */ @Test - public void testHotReloadTimeUsesLeadTimeOfJettyFactory() throws Exception { + public void testAutoReloadTimeUsesLeadTimeOfJettyFactory() throws Exception { SourceSslContextFactory.supply(fresh()); ConfigurableSourceSslContextFactory jettyFactory = new ConfigurableSourceSslContextFactory(); JettySslFactoryAdapter adapter = new JettySslFactoryAdapter(jettyFactory); - jettyFactory.setHotReloadBeforeExpiryMs(HOURS.toMillis(1)); + jettyFactory.setAutoReloadBeforeExpiryMs(HOURS.toMillis(1)); jettyFactory.start(); try { - assertEquals(now + DAYS.toMillis(30) - HOURS.toMillis(1), adapter.hotReloadTime()); + assertEquals(now + DAYS.toMillis(30) - HOURS.toMillis(1), adapter.autoReloadTime()); } finally { jettyFactory.stop(); @@ -344,7 +344,7 @@ public void testErrorFromSourceKeepsLastWorkingKeys() throws Exception { * Given: a reload that Ignite did not start, such as one by Jetty's {@code KeyStoreScanner}, has failed and left * the custom Jetty factory without keys. * When: Ignite reloads the factory while the source still fails, and again after the source supplies certificate B. - * Then: the first reload reports the source error, and the factory is due for hot reload right away, so a scheduled + * Then: the first reload reports the source error, and the factory is due for automatic reload right away, so a scheduled * check reloads it as the reload command does. The second reload installs B. */ @Test @@ -362,9 +362,9 @@ public void testReloadRecoversFactoryLeftWithoutKeys() throws Exception { assertThrows(log, () -> jettyFactory.reload(f -> { }), Exception.class, "Source is unavailable"); assertThrows(log, adapter::init, IgniteException.class, "Source is unavailable"); - long hotReloadTime = adapter.hotReloadTime(); + long autoReloadTime = adapter.autoReloadTime(); - assertTrue(hotReloadTime > 0 && hotReloadTime <= System.currentTimeMillis()); + assertTrue(autoReloadTime > 0 && autoReloadTime <= System.currentTimeMillis()); SourceSslContextFactory.supply(b); adapter.init(); @@ -456,12 +456,12 @@ public void testReloadCallsFactoryReloadOnce() throws Exception { } } - /** @return Key store with a server certificate valid for 30 days, which is not due for hot reload. */ + /** @return Key store with a server certificate valid for 30 days, which is not due for automatic reload. */ private KeyStore fresh() throws Exception { return ca.keyStore(HOST, now - HOURS.toMillis(1), now + DAYS.toMillis(30)); } - /** @return Key store with a server certificate that expires in an hour, so it is due for hot reload. */ + /** @return Key store with a server certificate that expires in an hour, so it is due for automatic reload. */ private KeyStore due() throws Exception { return ca.keyStore(HOST, now - HOURS.toMillis(20), now + HOURS.toMillis(1)); } @@ -566,13 +566,13 @@ public SourceSslContextFactory() throws Exception { } } - /** Custom Jetty factory of {@link SourceSslContextFactory} with hot reload settings that the Jetty XML file can set. */ - public static class ConfigurableSourceSslContextFactory extends SourceSslContextFactory implements ReloadableJettySslFactory { + /** Custom Jetty factory of {@link SourceSslContextFactory} with automatic reload settings that the Jetty XML file can set. */ + public static class ConfigurableSourceSslContextFactory extends SourceSslContextFactory implements AutoReloadJettySslFactory { /** */ - private boolean hotReloadEnabled = true; + private boolean autoReloadEnabled = true; /** */ - private long hotReloadBeforeExpiryMs = DFLT_HOT_RELOAD_BEFORE_EXPIRY_MS; + private long autoReloadBeforeExpiryMs = DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS; /** */ public ConfigurableSourceSslContextFactory() throws Exception { @@ -580,23 +580,23 @@ public ConfigurableSourceSslContextFactory() throws Exception { } /** {@inheritDoc} */ - @Override public boolean isHotReloadEnabled() { - return hotReloadEnabled; + @Override public boolean isAutoReloadEnabled() { + return autoReloadEnabled; } /** */ - public void setHotReloadEnabled(boolean hotReloadEnabled) { - this.hotReloadEnabled = hotReloadEnabled; + public void setAutoReloadEnabled(boolean autoReloadEnabled) { + this.autoReloadEnabled = autoReloadEnabled; } /** {@inheritDoc} */ - @Override public long getHotReloadBeforeExpiryMs() { - return hotReloadBeforeExpiryMs; + @Override public long getAutoReloadBeforeExpiryMs() { + return autoReloadBeforeExpiryMs; } /** */ - public void setHotReloadBeforeExpiryMs(long hotReloadBeforeExpiryMs) { - this.hotReloadBeforeExpiryMs = hotReloadBeforeExpiryMs; + public void setAutoReloadBeforeExpiryMs(long autoReloadBeforeExpiryMs) { + this.autoReloadBeforeExpiryMs = autoReloadBeforeExpiryMs; } } } diff --git a/modules/rest-http/src/test/resources/META-INF/jetty/https-source-manual.xml b/modules/rest-http/src/test/resources/META-INF/jetty/https-source-manual.xml index 34b423914d689..f162ef5e94bbc 100644 --- a/modules/rest-http/src/test/resources/META-INF/jetty/https-source-manual.xml +++ b/modules/rest-http/src/test/resources/META-INF/jetty/https-source-manual.xml @@ -26,7 +26,7 @@ - false + false From 3424e40862195c11417236c6ba0f62efa5d849d2 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Thu, 26 Nov 2026 17:22:26 +0300 Subject: [PATCH 50/53] IGNITE-29212 Spell out the Jetty settings check in the adapter The negated pattern match read as if the adapter checked whether the factory could be reloaded at all. Both settings methods now say what they do: a Jetty factory that implements AutoReloadJettySslFactory gives its own value, and any other factory gets the default. Co-Authored-By: Claude Opus 5.5 --- .../protocols/http/jetty/JettySslFactoryAdapter.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java index 47002fc8cfa6d..49689da439a05 100644 --- a/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java @@ -92,7 +92,10 @@ class JettySslFactoryAdapter implements ReloadableSslFactory { /** {@inheritDoc} */ @Override public boolean isAutoReloadEnabled() { - return !(factory instanceof AutoReloadJettySslFactory reloadable) || reloadable.isAutoReloadEnabled(); + if (factory instanceof AutoReloadJettySslFactory autoReloadFactory) + return autoReloadFactory.isAutoReloadEnabled(); + + return true; } /** {@inheritDoc} */ @@ -115,9 +118,10 @@ class JettySslFactoryAdapter implements ReloadableSslFactory { /** @return How long before the certificates expire automatic reload becomes due, in milliseconds. */ private long autoReloadBeforeExpiryMs() { - return factory instanceof AutoReloadJettySslFactory reloadable - ? reloadable.getAutoReloadBeforeExpiryMs() - : DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS; + if (factory instanceof AutoReloadJettySslFactory autoReloadFactory) + return autoReloadFactory.getAutoReloadBeforeExpiryMs(); + + return DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS; } /** From b05835747446fb8f963823d4b584f37dac889add Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Fri, 27 Nov 2026 16:45:20 +0300 Subject: [PATCH 51/53] IGNITE-29212 Say which factory check applies to HTTP REST in the command docs The reload command docs listed the transports whose factories must extend AbstractSslContextFactory, but did not say what the check means for the HTTP REST endpoint. It passes with any Jetty factory, standard or custom. Co-Authored-By: Claude Opus 5.5 --- docs/_docs/tools/control-script.adoc | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/_docs/tools/control-script.adoc b/docs/_docs/tools/control-script.adoc index a1cd83e7d68cb..19269f636df51 100644 --- a/docs/_docs/tools/control-script.adoc +++ b/docs/_docs/tools/control-script.adoc @@ -190,6 +190,7 @@ This is the control-script user, or the node receiving a JMX call. The report lists every target node, even if none of its TCP transports use TLS. Each node first checks that the factories of discovery, communication, client connector, and binary REST extend `AbstractSslContextFactory`. +The HTTP REST endpoint passes this check with any Jetty factory, standard or custom, as described in link:restapi#https[HTTPS]. If any factory is unsupported, that node reloads none of its factories. Otherwise, it reloads them until the first failure and reports the error. Other nodes continue independently. From 7af11c49db8b7444eb3f32ec858c50a5bc9907a1 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Fri, 27 Nov 2026 17:25:11 +0300 Subject: [PATCH 52/53] IGNITE-29212 Name the X.509 certificate variable in the chain expiry Co-Authored-By: Claude Opus 5.5 --- .../ignite/internal/processors/ssl/ReloadableSslFactory.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java index 0f2223bafdc8f..4b49879e1e2db 100644 --- a/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -84,10 +84,10 @@ private static long chainExpiry(Certificate[] chain) { return expiry; for (Certificate cert : chain) { - if (!(cert instanceof X509Certificate x509)) + if (!(cert instanceof X509Certificate x509Cert)) return Long.MAX_VALUE; - expiry = Math.min(expiry, x509.getNotAfter().getTime()); + expiry = Math.min(expiry, x509Cert.getNotAfter().getTime()); } return expiry; From 660c7ccba5b0b4cb87b1621e134ba9a2207931a0 Mon Sep 17 00:00:00 2001 From: Anton Vinogradov Date: Fri, 27 Nov 2026 18:52:05 +0300 Subject: [PATCH 53/53] IGNITE-29212 Clarify manual and automatic certificate hot reload in the docs --- docs/_docs/monitoring-metrics/new-metrics.adoc | 2 +- docs/_docs/security/ssl-tls.adoc | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/_docs/monitoring-metrics/new-metrics.adoc b/docs/_docs/monitoring-metrics/new-metrics.adoc index 1919fa8f610af..8dfd610c6d7fd 100644 --- a/docs/_docs/monitoring-metrics/new-metrics.adoc +++ b/docs/_docs/monitoring-metrics/new-metrics.adoc @@ -433,7 +433,7 @@ Register name: `communication.tcp.{node_consistent_id}` |sentMessagesToNode | long | Total number of messages sent by current node to the given node. |=== -== Automatic Certificate Reload +== Certificate Hot Reload Register name: `ssl` diff --git a/docs/_docs/security/ssl-tls.adoc b/docs/_docs/security/ssl-tls.adoc index bdcf5ce68ced7..163227b1aae58 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -158,7 +158,8 @@ include::{javaFile}[tag=disable-validation,indent=0] == Upgrading Certificates -You can replace certificate files and reload them without restarting nodes that use `SslContextFactory`. +Certificate hot reload lets nodes that use `SslContextFactory` load replacement certificates without restarting. +You can request a reload immediately or let Ignite reload certificates automatically before they expire. The link:tools/control-script#reloading-tls-certificates[`--ssl reload` command] updates TCP transports on all server and thick-client nodes. It also reloads the link:restapi#https[HTTP REST endpoint] when its Jetty connector uses HTTPS. External client applications reload their certificates separately.