diff --git a/docs/_docs/monitoring-metrics/new-metrics.adoc b/docs/_docs/monitoring-metrics/new-metrics.adoc index 3d6c6085234db..8dfd610c6d7fd 100644 --- a/docs/_docs/monitoring-metrics/new-metrics.adoc +++ b/docs/_docs/monitoring-metrics/new-metrics.adoc @@ -440,12 +440,12 @@ 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 88022e86fd65d..442b463d3efa9 100644 --- a/docs/_docs/restapi.adoc +++ b/docs/_docs/restapi.adoc @@ -104,6 +104,73 @@ 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-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 AutoReloadJettySslFactory { + private boolean autoReloadEnabled = true; + + private long autoReloadBeforeExpiryMs = AbstractSslContextFactory.DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS; + + @Override public boolean isAutoReloadEnabled() { + return autoReloadEnabled; + } + + public void setAutoReloadEnabled(boolean autoReloadEnabled) { + this.autoReloadEnabled = autoReloadEnabled; + } + + @Override public long getAutoReloadBeforeExpiryMs() { + return autoReloadBeforeExpiryMs; + } + + public void setAutoReloadBeforeExpiryMs(long autoReloadBeforeExpiryMs) { + if (autoReloadBeforeExpiryMs <= 0) + throw new IllegalArgumentException("autoReloadBeforeExpiryMs must be positive: " + autoReloadBeforeExpiryMs); + + this.autoReloadBeforeExpiryMs = autoReloadBeforeExpiryMs; + } +} +---- + +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 automatic 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. +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 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. + === 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..163227b1aae58 100644 --- a/docs/_docs/security/ssl-tls.adoc +++ b/docs/_docs/security/ssl-tls.adoc @@ -158,9 +158,15 @@ 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 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 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. Keep their configured paths, store types, and passwords unchanged; changing node configuration requires a restart. @@ -182,60 +188,75 @@ 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 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 TCP transports as <>. -It does not update the HTTP REST endpoint or external client applications. +Automatic reload covers the same transports as <>, including the HTTP REST endpoint. +It does not update external client applications. -=== Enable Hot Reload +=== Disable Automatic Reload -Enable hot reload on each configured factory before starting the node: +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(true); +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 `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. + +=== Supply Replacements + 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 checks each factory with hot reload enabled. -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. +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, wait through the one-hour interval and load the stores. +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#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, the next hourly check uses the loaded certificates. +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. @@ -244,22 +265,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.* @@ -270,11 +291,12 @@ 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 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. -Limit request duration in custom sources: a blocked load delays other hot reloads and manual reload. +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 automatic reloads and manual reload. == SslContextFactory Properties @@ -304,12 +326,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 <>. -|`false` +|`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/docs/_docs/tools/control-script.adoc b/docs/_docs/tools/control-script.adoc index 54fff9048bea8..19269f636df51 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,8 @@ 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`. +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. 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 new file mode 100644 index 0000000000000..4b49879e1e2db --- /dev/null +++ b/modules/commons/src/main/java/org/apache/ignite/internal/processors/ssl/ReloadableSslFactory.java @@ -0,0 +1,95 @@ +/* + * 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 javax.cache.configuration.Factory; +import javax.net.ssl.SSLContext; +import org.apache.ignite.IgniteException; + +/** 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. + * + * @throws IgniteException If loading fails. + */ + public void init(); + + /** + * 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 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 autoReloadTime(); + + /** @return Whether the registry reloads the factory before its certificates expire. Manual reload works either way. */ + public boolean isAutoReloadEnabled(); + + /** + * @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. + */ + 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)) + 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 x509Cert)) + return Long.MAX_VALUE; + + expiry = Math.min(expiry, x509Cert.getNotAfter().getTime()); + } + + 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 5f0b0447a4feb..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 @@ -21,12 +21,8 @@ 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; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; @@ -34,20 +30,24 @@ import javax.net.ssl.SSLParameters; import javax.net.ssl.TrustManager; import org.apache.ignite.IgniteException; +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}. + * 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 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 Factory { +public abstract class AbstractSslContextFactory implements ReloadableSslFactory { /** */ private static final long serialVersionUID = 0L; /** 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 Factory { protected final AtomicReference sslCtx = new AtomicReference<>(); /** */ - private boolean hotReloadEnabled; + 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; @@ -73,54 +73,41 @@ public abstract class AbstractSslContextFactory implements Factory { /** */ 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; + /** {@inheritDoc} */ + @Override public boolean isAutoReloadEnabled() { + return autoReloadEnabled; } /** - * @param enabled Whether automatic certificate hot reload is enabled. Changes require a node restart. + * @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; } - /** - * 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. - * 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() { + /** {@inheritDoc} */ + @Override public long autoReloadTime() { long expiry = earliestExpiry; - return expiry == 0 ? 0 : expiry - hotReloadBeforeExpiryMs; + return expiry == 0 ? 0 : expiry - autoReloadBeforeExpiryMs; } /** @@ -247,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. @@ -260,66 +247,19 @@ protected final synchronized KeyManager[] createKeyManagers(KeyManagerFactory ke throws GeneralSecurityException { keyMgrFactory.init(store, pwd); - pendingExpiry = keyChainsExpiry(store); + pendingExpiry = ReloadableSslFactory.keyChainsExpiry(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. */ 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. - */ - public final synchronized void init() { + /** {@inheritDoc} */ + @Override public final synchronized void init() { try { sslCtx.set(createSslContext()); } 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..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 @@ -32,13 +32,13 @@ 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.ReloadableSslFactory; 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; @@ -137,7 +137,7 @@ private SslReloadJob(NoArg arg, boolean debug) { } for (Entry, String> entry : factories) { - if (!(entry.getKey() instanceof AbstractSslContextFactory)) { + if (!(entry.getKey() instanceof ReloadableSslFactory)) { String report = entry.getValue() + ": unsupported: " + entry.getKey().getClass().getName(); ignite.log().warning("TLS reload: " + nodeId + ": " + report + initiator); @@ -152,7 +152,7 @@ private SslReloadJob(NoArg arg, boolean debug) { String transports = entry.getValue(); try { - ignite.context().ssl().reload((AbstractSslContextFactory)entry.getKey()); + 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 b23a170f33d93..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 @@ -23,7 +23,9 @@ import java.util.Map; import java.util.Map.Entry; 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 javax.cache.configuration.Factory; @@ -33,7 +35,6 @@ 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; @@ -42,7 +43,7 @@ /** SSL factories used by running transports. */ public class SslFactoryRegistry extends GridProcessorAdapter { - /** */ + /** Maximum delay when scheduling a check, also used for retries after a failed check. */ private static final long CHECK_PERIOD = HOURS.toMillis(1); /** */ @@ -55,14 +56,18 @@ 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) { super(ctx); } - /** */ + /** + * @param transport Transport name. + * @param factory SSL context factory of the transport. The registry reloads it if it implements + * {@link ReloadableSslFactory}. + */ public synchronized void register(String transport, Factory factory) { for (int i = 0; i < factories.size(); i++) { RegisteredFactory registered = factories.get(i); @@ -91,35 +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."); - - boolean hotReload = false; + metrics.register("AutoReloadAttempts", autoReloadAttempts::get, + "Number of automatic reload attempts."); for (RegisteredFactory registered : factories) { - AbstractSslContextFactory sslFactory = registered.hotReloadFactory(); + if (registered.reloadable == null || !registered.reloadable.isAutoReloadEnabled()) + continue; - if (sslFactory != null) { - registered.logHotReloadTime(sslFactory.getHotReloadTime()); + if (executor == null) + executor = newSingleThreadScheduledExecutor("ssl-auto-reload", ctx.igniteInstanceName()); - hotReload = true; - } + registered.scheduleCheck(0); } - - if (!hotReload) - return; - - executor = newSingleThreadScheduledExecutor("ssl-hot-reload", ctx.igniteInstanceName()); - - executor.scheduleWithFixedDelay(new OperationContextAwareRunnable(this::checkFactories, null), - 0, CHECK_PERIOD, MILLISECONDS); } - /** @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) @@ -128,17 +123,6 @@ private long consecutiveHotReloadFailures() { return sum; } - /** Runs the hourly check of the factories with hot reload enabled. */ - private void checkFactories() { - if (log.isDebugEnabled()) - log.debug("TLS hot reload check started"); - - for (RegisteredFactory registered : factories) { - if (registered.hotReloadFactory() != null) - registered.check(); - } - } - /** {@inheritDoc} */ @Override public void onKernalStop(boolean cancel) { if (executor != null) @@ -146,128 +130,197 @@ 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. 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 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. */ - public void reload(AbstractSslContextFactory factory) { + public void reload(ReloadableSslFactory factory) { for (RegisteredFactory registered : factories) { if (registered.factory == factory) registered.reload(); } } - /** Registered factory with its transports and hot reload state. The hourly check 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; + /** The factory if the registry can reload it, {@code null} otherwise. */ + @Nullable private final ReloadableSslFactory reloadable; + /** */ private final String transports; /** */ private final AtomicInteger failures = new AtomicInteger(); + /** */ + @Nullable private ScheduledFuture nextCheck; + + /** 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) { 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; + reloadable = factory instanceof ReloadableSslFactory sslFactory ? sslFactory : null; } /** - * 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. 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 automatic reload check started [transports=" + transports + ']'); + + long nextCheckDelay = CHECK_PERIOD; + try { - reloadIfDue(); + nextCheckDelay = reloadIfDue(); } catch (Throwable e) { 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 void reloadIfDue() { - AbstractSslContextFactory sslFactory = (AbstractSslContextFactory)factory; + private long reloadIfDue() { + long autoReloadTime = reloadable.autoReloadTime(); + + logAutoReloadTime(autoReloadTime); + + long nextCheckDelay = nextCheckDelay(autoReloadTime); - if (!due(sslFactory.getHotReloadTime())) { + if (nextCheckDelay != 0) { failures.set(0); - return; + 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 + ']'); - sslFactory.init(); + reloadable.init(); - long hotReloadTime = sslFactory.getHotReloadTime(); + autoReloadTime = reloadable.autoReloadTime(); + nextCheckDelay = nextCheckDelay(autoReloadTime); - if (due(hotReloadTime)) { - throw new IgniteException("Loaded certificates are still due for hot reload [hotReloadTime=" - + new Date(hotReloadTime) + ']'); + if (nextCheckDelay == 0) { + 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 + ']'); + + logAutoReloadTime(autoReloadTime); - logHotReloadTime(hotReloadTime); + return nextCheckDelay; } - /** @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(); + /** + * @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 autoReloadTime) { + if (autoReloadTime == 0) + return 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. */ + private synchronized void scheduleCheck(long delay) { + if (executor == null) + return; + + if (nextCheck != null) + nextCheck.cancel(false); + + try { + nextCheck = executor.schedule(new OperationContextAwareRunnable(this::check, null), delay, MILLISECONDS); + } + catch (RejectedExecutionException ignored) { + // The registry has stopped. + } } /** */ private synchronized void reload() { manualReloadAttempts.incrementAndGet(); - ((AbstractSslContextFactory)factory).init(); + reloadable.init(); - AbstractSslContextFactory sslFactory = hotReloadFactory(); + if (!reloadable.isAutoReloadEnabled()) + return; - if (sslFactory != null) { - failures.set(0); + failures.set(0); - logHotReloadTime(sslFactory.getHotReloadTime()); + long autoReloadTime; + + try { + autoReloadTime = reloadable.autoReloadTime(); } + catch (RuntimeException e) { + 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); + + return; + } + + logAutoReloadTime(autoReloadTime); + + long nextCheckDelay = nextCheckDelay(autoReloadTime); + + scheduleCheck(nextCheckDelay == 0 ? CHECK_PERIOD : nextCheckDelay); } - /** */ - private void logHotReloadTime(long hotReloadTime) { - if (hotReloadTime == 0) { - log.warning("TLS hot reload will not run: no private key with an X.509 certificate chain was found [transports=" + /** 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; + + loggedAutoReloadTime = autoReloadTime; + + 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 aa1e81d26cc48..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 @@ -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; @@ -31,6 +32,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; @@ -62,6 +64,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; @@ -73,16 +76,18 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; +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; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * 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 reload attempt that a scheduled check makes. */ public class SslFactoryRegistryTest { /** Upper bound for waiting for an event that must happen. */ @@ -106,8 +111,8 @@ public class SslFactoryRegistryTest { /** */ private MockedStatic executorFactory; - /** Hourly 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; @@ -122,8 +127,8 @@ public class SslFactoryRegistryTest { private TestCertificateAuthority authority; /** - * Each test gets a registry whose hot reload executor records the hourly check instead of running it. - * Tests run the check themselves. + * 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. */ @Before @@ -143,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); @@ -184,23 +193,67 @@ 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); - registerTransport("communication", factory(keys)); + communication.setAutoReloadEnabled(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. + * Then: no automatic reload thread starts, and the failure metric reads zero. + */ + @Test + public void testFactoryWithoutReloadDoesNotStartAutoReload() { + Factory createOnly = () -> null; + + registry.register("communication", createOnly); + 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 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 testReloadableFactoryIsAutoReloadedAndReloadedManually() { + ReloadableSslFactory rest = httpRestFactory(); + + when(rest.autoReloadTime()).thenReturn(due(), at(DAYS.toHours(30))); + + registry.register("HTTP REST", rest); + registry.onKernalStart(true); + runChecks(); + + assertEquals(0, failures()); + + registry.reload(rest); + + verify(rest, times(2)).init(); + assertEquals(1, metric("AutoReloadAttempts")); + assertEquals(1, metric("ManualReloadAttempts")); + } + /** * 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 @@ -209,21 +262,19 @@ 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); registry.onKernalStart(true); - long prevTime = communication.getHotReloadTime(); + long prevTime = communication.autoReloadTime(); writeFreshCertificates(keys); - check.run(); + runChecks(); - assertEquals(2, metric("AutomaticHotReloadAttempts")); - assertTrue(communication.getHotReloadTime() > prevTime); - assertEquals(communication.getHotReloadTime(), clientConnector.getHotReloadTime()); + assertEquals(2, metric("AutoReloadAttempts")); + assertTrue(communication.autoReloadTime() > prevTime); + assertEquals(communication.autoReloadTime(), clientConnector.autoReloadTime()); } /** @@ -237,27 +288,25 @@ 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); - long prevTime = communication.getHotReloadTime(); + long prevTime = communication.autoReloadTime(); writeFreshCertificates(keys); registry.reload(clientConnector); - assertTrue(clientConnector.getHotReloadTime() > prevTime); - assertEquals(prevTime, communication.getHotReloadTime()); + assertTrue(clientConnector.autoReloadTime() > prevTime); + assertEquals(prevTime, communication.autoReloadTime()); } /** - * Given: hot reload is enabled, and 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 + * 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 { @@ -265,59 +314,204 @@ public void testStoreWithoutPrivateKeyIsReportedUntilKeysAreReloaded() throws Ex SslContextFactory communication = factory(keys); save(authority.trustStore(), keys); - communication.setHotReloadEnabled(true); 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")); - 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.getHotReloadTime()) + ']', + assertEquals("TLS automatic reload due [transports=communication, autoReloadTime=" + new Date(communication.autoReloadTime()) + ']', logged.get(logged.size() - 1)); } /** - * Given: hot reload is enabled for due certificates, 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. + * 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. */ @Test - public void testHotReloadIsCheckedEveryHourFromStart() throws Exception { + public void testFailedCheckIsRetriedAfterCheckPeriod() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); 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: 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 automatic reload time. + */ + @Test + public void testFailedReadOfAutoReloadTimeIsRetriedWithoutFailingStart() throws Exception { + ReloadableSslFactory rest = httpRestFactory(); + + 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)); + 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 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 automatic reload time, and the next check of the client connector + * comes in an hour, the longest interval between checks. + */ + @Test + public void testNextCheckComesAtAutoReloadTimeButWithinCheckPeriod() 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); + runChecks(); + + List delays = List.copyOf(scheduled.values()); + + assertTrue(delays.toString(), isAbout30Minutes(delays.get(0))); + assertEquals(HOURS.toMillis(1), (long)delays.get(1)); + } + + /** + * 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 automatic reload time that the check read, not after the full hour. + */ + @Test + public void testCheckRightBeforeAutoReloadTimeDoesNotDeferAutoReload() { + ReloadableSslFactory rest = httpRestFactory(); + + when(rest.autoReloadTime()).thenReturn(System.currentTimeMillis() + MINUTES.toMillis(30), due()); + + registry.register("HTTP REST", rest); + registry.onKernalStart(true); + runChecks(); + + assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); + } + + /** + * 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 testAutoReloadSchedulesCheckAtNewAutoReloadTime() throws Exception { + writeDueCertificates(keys); + registerTransport("communication", factory(keys)); + registry.onKernalStart(true); + writeCertificatesDueIn30Minutes(keys); + runChecks(); + + assertEquals(0, failures()); + assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); + } + + /** + * 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 testManualReloadSchedulesCheckAtAutoReloadTime() throws Exception { + SslContextFactory communication = factory(keys); + + writeFreshCertificates(keys); + registerTransport("communication", communication); + registry.onKernalStart(true); + writeCertificatesDueIn30Minutes(keys); + registry.reload(communication); + + assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); + } + + /** + * 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 testManualReloadRetriesFailedReadOfAutoReloadTime() { + ReloadableSslFactory rest = httpRestFactory(); + + 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); + registry.onKernalStart(true); + registry.reload(rest); + + assertEquals(HOURS.toMillis(1), nextCheckDelay()); + + runChecks(); + + assertTrue(scheduled.toString(), isAbout30Minutes(nextCheckDelay())); + verify(rest).init(); + } + + /** + * 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. + */ + @Test + public void testManualReloadOfDueCertificatesDefersNextCheck() throws Exception { + SslContextFactory communication = factory(keys); + + writeDueCertificates(keys); + registerTransport("communication", communication); + registry.onKernalStart(true); + registry.reload(communication); + + assertEquals(0, failures()); + assertEquals(HOURS.toMillis(1), nextCheckDelay()); + } + /** * Given: the registry starts during an operation with a request ID. * When: its worker reloads a factory with due certificates. * 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)); @@ -335,7 +529,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. */ @@ -344,26 +538,25 @@ 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); - clientConnector.setHotReloadEnabled(true); registry.register("communication", factory); registerTransport("client connector", clientConnector); registry.onKernalStart(true); writeFreshCertificates(keys); - check.run(); + 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: hot reload is enabled for due certificates, 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 { @@ -371,34 +564,33 @@ public void testLogShowsDueTimeStartAndResultOfAttempts() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); registry.onKernalStart(true); - long due = communication.getHotReloadTime(); + long due = communication.autoReloadTime(); Files.delete(keys); - check.run(); + runChecks(); writeFreshCertificates(keys); - check.run(); + runChecks(); List evts = new ArrayList<>(); 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.getHotReloadTime()) + ']')); + assertTrue(logged.get(5), logged.get(5).endsWith("autoReloadTime=" + new Date(communication.autoReloadTime()) + ']')); } /** - * Given: hot reload is enabled for due certificates, 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. */ @@ -407,24 +599,23 @@ public void testSuccessResetsFailuresAndLaterChecksWait() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); registry.onKernalStart(true); Files.delete(keys); - check.run(); + runChecks(); assertEquals(1, failures()); - assertEquals(1, metric("AutomaticHotReloadAttempts")); + assertEquals(1, metric("AutoReloadAttempts")); writeFreshCertificates(keys); - check.run(); + runChecks(); assertEquals(0, failures()); - assertEquals(2, metric("AutomaticHotReloadAttempts")); + assertEquals(2, metric("AutoReloadAttempts")); - check.run(); + runChecks(); - assertEquals(2, metric("AutomaticHotReloadAttempts")); + assertEquals(2, metric("AutoReloadAttempts")); } /** @@ -438,23 +629,22 @@ public void testCheckResetsFailuresWhenFactoryIsNoLongerDue() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); 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")); + assertEquals(1, metric("AutoReloadAttempts")); } /** - * 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,27 +653,27 @@ public void testManualReloadBeforeStartLoadsFactory() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); - long prevTime = communication.getHotReloadTime(); + long prevTime = communication.autoReloadTime(); writeFreshCertificates(keys); registry.reload(communication); - assertTrue(communication.getHotReloadTime() > 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.setAutoReloadEnabled(false); registerTransport("communication", communication); registry.onKernalStart(true); registry.reload(communication); @@ -494,11 +684,33 @@ public void testManualReloadWithoutHotReloadCountsAppliedAndFailedLoads() throws assertThrows(IgniteException.class, () -> registry.reload(communication)); assertEquals(2, metric("ManualReloadAttempts")); - assertEquals(0, metric("AutomaticHotReloadAttempts")); + assertEquals(0, metric("AutoReloadAttempts")); } /** - * Given: a custom factory has loaded a certificate that is due for hot reload. + * 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. + */ + @Test + public void testManualReloadDoesNotScheduleCheckOfDisabledFactory() throws Exception { + Path clientKeys = dir.resolve("client-keys.jks"); + SslContextFactory communication = factory(keys); + + writeDueCertificates(keys); + writeFreshCertificates(clientKeys); + communication.setAutoReloadEnabled(false); + registerTransport("communication", communication); + registerTransport("client connector", factory(clientKeys)); + registry.onKernalStart(true); + registry.reload(communication); + runChecks(); + + assertEquals(0, metric("AutoReloadAttempts")); + } + + /** + * 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. */ @@ -507,7 +719,6 @@ public void testScheduledReloadUsesCustomFactoryKeyStoreAndPassword() throws Exc SourceSslContextFactory custom = new SourceSslContextFactory(); custom.setKeys(authority.keyStore("node", at(-1), at(10)), PASSWORD); - custom.setHotReloadEnabled(true); SSLContext initCtx = custom.create(); @@ -518,39 +729,38 @@ 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()); long expiry = ((X509Certificate)replacement.getCertificate("node")).getNotAfter().getTime(); - assertEquals(expiry - custom.getHotReloadBeforeExpiryMs(), custom.getHotReloadTime()); + assertEquals(expiry - custom.getAutoReloadBeforeExpiryMs(), custom.autoReloadTime()); } /** - * 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. + * 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.setHotReloadEnabled(true); custom.create(); - assertTrue(custom.getHotReloadTime() > 0); + assertTrue(custom.autoReloadTime() > 0); registry.register("communication", custom); registry.onKernalStart(true); custom.setKeys(null, null); registry.reload(custom); - check.run(); + runChecks(); - assertEquals(0, custom.getHotReloadTime()); - assertEquals(0, metric("AutomaticHotReloadAttempts")); + assertEquals(0, custom.autoReloadTime()); + assertEquals(0, metric("AutoReloadAttempts")); } /** @@ -579,11 +789,10 @@ public void testFailedManualReloadKeepsFailures() throws Exception { SslContextFactory communication = factory(keys); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); registry.onKernalStart(true); Files.delete(keys); - check.run(); + runChecks(); IgniteException err = assertThrows(IgniteException.class, () -> registry.reload(communication)); @@ -592,12 +801,12 @@ public void testFailedManualReloadKeepsFailures() throws Exception { } /** - * 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. + * 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); @@ -610,12 +819,11 @@ public void testManualOnlyFactoryDoesNotDelayHotReload() throws Exception { }).when(factory).init(); writeDueCertificates(keys); - clientConnector.setHotReloadEnabled(true); registry.register("communication", factory); registerTransport("client connector", clientConnector); registry.onKernalStart(true); - long prevTime = clientConnector.getHotReloadTime(); + long prevTime = clientConnector.autoReloadTime(); writeFreshCertificates(keys); @@ -623,9 +831,9 @@ public void testManualOnlyFactoryDoesNotDelayHotReload() throws Exception { try { assertTrue(manualStarted.await(TIMEOUT_MS, MILLISECONDS)); - runAsync(check).get(TIMEOUT_MS); + runAsync(nextCheck()).get(TIMEOUT_MS); - assertTrue(clientConnector.getHotReloadTime() > prevTime); + assertTrue(clientConnector.autoReloadTime() > prevTime); } finally { finishManual.countDown(); @@ -646,13 +854,12 @@ public void testManualReloadWaitsForRunningAttempt() throws Exception { CountDownLatch resumeAttempt = new CountDownLatch(1); writeDueCertificates(keys); - communication.setHotReloadEnabled(true); registerTransport("communication", communication); registry.onKernalStart(true); Files.delete(keys); when(executor.isShutdown()).thenAnswer(call -> { - if (metric("AutomaticHotReloadAttempts") > 0) { + if (metric("AutoReloadAttempts") > 0) { attemptFailed.countDown(); assertTrue(resumeAttempt.await(TIMEOUT_MS, MILLISECONDS)); @@ -661,7 +868,7 @@ public void testManualReloadWaitsForRunningAttempt() throws Exception { return false; }); - GridTestThread attempt = new GridTestThread(check); + GridTestThread attempt = new GridTestThread(nextCheck()); GridTestThread manualReload = new GridTestThread(() -> registry.reload(communication)); attempt.start(); @@ -705,12 +912,10 @@ 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); - check.run(); + runChecks(); assertEquals(1, failures()); @@ -719,7 +924,7 @@ public void testManualReloadResetsOnlyItsFactoryFailures() throws Exception { assertEquals(1, failures()); - check.run(); + runChecks(); assertEquals(3, failures()); @@ -737,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(); @@ -784,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); @@ -793,12 +998,12 @@ 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 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=")); } /** @@ -811,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 -> { @@ -826,18 +1031,18 @@ public void testStopDuringCheckSkipsRemainingFactories() { registry.register("communication", factory); registry.register("client connector", clientConnector); registry.onKernalStart(true); - check.run(); + runChecks(); 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. @@ -847,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); @@ -857,6 +1062,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(); + } + /** Loads a file-backed factory before registration, as the TCP transports do during startup. */ private void registerTransport(String transport, SslContextFactory factory) { factory.create(); @@ -865,7 +1098,7 @@ private void registerTransport(String transport, SslContextFactory factory) { /** */ private long failures() { - return metric("ConsecutiveHotReloadFailures"); + return metric("ConsecutiveAutoReloadFailures"); } /** */ @@ -874,24 +1107,33 @@ 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 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.getHotReloadTime()).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 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.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(); } /** - * 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 +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 { @@ -917,7 +1159,22 @@ 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 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 { + long now = System.currentTimeMillis(); + + 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. */ + private static boolean isAbout30Minutes(long delay) { + return delay > MINUTES.toMillis(29) && delay <= MINUTES.toMillis(30); + } + + /** + * 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 98e0e0bb7d315..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"); @@ -66,11 +66,9 @@ 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); + 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); @@ -97,20 +95,20 @@ 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 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); @@ -121,12 +119,10 @@ 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)); }); - 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)); @@ -139,15 +135,15 @@ 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 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,25 +153,23 @@ public void testNodeStopEndsHotReloadThread() throws Exception { SslContextFactory serverFactory = configure(new SslContextFactory(), keys, trust); - serverFactory.setHotReloadEnabled(true); - IgniteEx node = startGrid(0, cfg -> { 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(); @@ -187,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 ee4120e4100e6..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 disabled 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()); - assertFalse(factory.isHotReloadEnabled()); + assertTrue(factory.isAutoReloadEnabled()); assertNotNull(factory.create()); - assertEquals(0, factory.getHotReloadTime()); + 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.getHotReloadTime()); + assertEquals(at(DAYS.toHours(3)), factory.autoReloadTime()); - factory.setHotReloadBeforeExpiryMs(DAYS.toMillis(14)); + factory.setAutoReloadBeforeExpiryMs(DAYS.toMillis(14)); - assertEquals(at(-DAYS.toHours(4)), factory.getHotReloadTime()); + assertEquals(at(-DAYS.toHours(4)), factory.autoReloadTime()); } /** @@ -128,23 +128,23 @@ 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()); } /** * 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. + * When: the factory loads each key store. + * 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,23 +155,22 @@ 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 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. + * Then: it reads the key store once, so the automatic reload date matches the loaded key managers. */ @Test 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); @@ -179,27 +178,26 @@ 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 with hot reload enabled. - * Then: the load succeeds, and hot reload has been due since 15 hours before the issuer expired. + * When: the factory loads the chain for the first time. + * Then: the load succeeds, and automatic reload has been due since 15 hours 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(-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(); @@ -207,10 +205,8 @@ public void testStoreWithoutPrivateKeyLoadsWithoutHotReloadDate() throws Excepti InMemorySslContextFactory factory = new InMemorySslContextFactory(store); - factory.setHotReloadEnabled(true); - assertNotNull(factory.create()); - assertEquals(0, factory.getHotReloadTime()); + assertEquals(0, factory.autoReloadTime()); } /** @@ -303,10 +299,9 @@ public void testReloadRecoversAfterFailedTrustStoreLoad() throws Exception { InMemorySslContextFactory factory = new InMemorySslContextFactory(authority.keyStore("node", at(-90), at(10))); factory.useTrustStore(trust.toString()); - factory.setHotReloadEnabled(true); SSLContext ctx = factory.create(); - long hotReloadTime = factory.getHotReloadTime(); + long autoReloadTime = factory.autoReloadTime(); factory.keyStore = authority.keyStore("node", at(-1), at(99)); Files.delete(trust); @@ -315,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(autoReloadTime, factory.autoReloadTime()); save(authority.trustStore(), trust); factory.init(); assertNotSame(ctx, factory.create()); - assertEquals(at(84), factory.getHotReloadTime()); + 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#getHotReloadTime()} 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.getHotReloadTime(); + long autoReloadTime = factory.autoReloadTime(); factory.keyStore = authority.keyStore("node", at(-1), at(99)); @@ -354,7 +349,7 @@ public void testHotReloadTimeRemainsReadableDuringLoad() throws Exception { try { assertTrue(trustLoadStarted.await(TIMEOUT_MS, MILLISECONDS)); - assertEquals(hotReloadTime, factory.getHotReloadTime()); + assertEquals(autoReloadTime, factory.autoReloadTime()); } finally { finishTrustLoad.countDown(); @@ -366,7 +361,7 @@ public void testHotReloadTimeRemainsReadableDuringLoad() throws Exception { } /** - * Creates a factory with hot reload enabled 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 { @@ -374,22 +369,20 @@ private InMemorySslContextFactory dueFactory() throws Exception { factory.trustStore = authority.trustStore(); factory.useTrustStore("memory-trust"); - factory.setHotReloadEnabled(true); factory.create(); - assertEquals(at(-5), factory.getHotReloadTime()); + assertEquals(at(-5), factory.autoReloadTime()); return factory; } /** */ - private void assertHotReloadIsDueNow(KeyStore keys) { + private void assertAutoReloadIsDueNow(KeyStore keys) { InMemorySslContextFactory factory = new InMemorySslContextFactory(keys); - factory.setHotReloadEnabled(true); factory.create(); - assertEquals(now, factory.getHotReloadTime()); + assertEquals(now, factory.autoReloadTime()); } /** @@ -438,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 { /** */ @@ -460,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/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..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,10 +169,19 @@ else if (log.isDebugEnabled()) int portRange = config().getPortRange(); int lastPort = portRange == 0 ? initPort : initPort + portRange - 1; + Collection adapters = connector.getContainedBeans(SslConnectionFactory.class).stream() + .map(SslConnectionFactory::getSslContextFactory) + .distinct() + .map(JettySslFactoryAdapter::new) + .toList(); + for (port = initPort; port <= lastPort; port++) { connector.setPort(port); if (startJetty()) { + 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 new file mode 100644 index 0000000000000..49689da439a05 --- /dev/null +++ b/modules/rest-http/src/main/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettySslFactoryAdapter.java @@ -0,0 +1,203 @@ +/* + * 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 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; +import org.apache.ignite.ssl.AbstractSslContextFactory; +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_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. + * 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 + * 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. 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 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 + * 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 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; + + /** */ + private final SslContextFactory factory; + + /** 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}. + */ + JettySslFactoryAdapter(SslContextFactory factory) { + assert !factory.isStarted(); + + this.factory = factory; + + configured = new TlsState(factory); + } + + /** {@inheritDoc} */ + @Override public SSLContext create() { + return factory.getSslContext(); + } + + /** {@inheritDoc} */ + @Override public void init() { + try { + factory.unload(ignored -> reloadOrRestore()); + } + catch (SkipUnload skip) { + if (skip.loadErr != null) + throw new IgniteException(skip.loadErr); + } + } + + /** {@inheritDoc} */ + @Override public boolean isAutoReloadEnabled() { + if (factory instanceof AutoReloadJettySslFactory autoReloadFactory) + return autoReloadFactory.isAutoReloadEnabled(); + + return true; + } + + /** {@inheritDoc} */ + @Override public long autoReloadTime() { + TlsState state = currentState(); + + if (state == null) + return System.currentTimeMillis(); + + try { + KeyStore store = state.keyStore(); + long expiry = store == null ? 0 : ReloadableSslFactory.keyChainsExpiry(store); + + 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 automatic reload becomes due, in milliseconds. */ + private long autoReloadBeforeExpiryMs() { + if (factory instanceof AutoReloadJettySslFactory autoReloadFactory) + return autoReloadFactory.getAutoReloadBeforeExpiryMs(); + + return DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS; + } + + /** + * 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 = currentState(); + + try { + factory.reload(ignored -> {}); + } + catch (Throwable e) { + if (prev != null) + restore(prev, e); + + throw new SkipUnload(e); + } + + 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 { + factory.reload(prev::applyTo); + } + catch (Throwable e) { + loadErr.addSuppressed(e); + } + finally { + configured.applyTo(factory); + } + } + + /** Context and stores that Jetty uses together for new connections. */ + private record TlsState(SSLContext ctx, KeyStore keyStore, KeyStore trustStore) { + /** */ + 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); + factory.setTrustStore(trustStore); + } + } + + /** + * 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; + + /** Load failure, or {@code null} if the factory has the replacement. */ + @Nullable private final Throwable loadErr; + + /** */ + private SkipUnload(@Nullable Throwable loadErr) { + super(null, null, false, false); + + this.loadErr = loadErr; + } + } +} diff --git a/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/AutoReloadJettySslFactory.java b/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/AutoReloadJettySslFactory.java new file mode 100644 index 0000000000000..ee3c739a89450 --- /dev/null +++ b/modules/rest-http/src/main/java/org/apache/ignite/ssl/jetty/AutoReloadJettySslFactory.java @@ -0,0 +1,38 @@ +/* + * 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.jetty; + +import org.apache.ignite.ssl.AbstractSslContextFactory; + +/** + * 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 + * 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 AutoReloadJettySslFactory { + /** @return Whether Ignite reloads the factory before its certificates expire. Changes require a node restart. */ + public boolean isAutoReloadEnabled(); + + /** + * @return How long before the earliest certificate expiry in the private key chains automatic reload becomes due, + * in milliseconds. Must be positive. + */ + 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 new file mode 100644 index 0000000000000..4fe92d391540d --- /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 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/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..d0306a40d1bac --- /dev/null +++ b/modules/rest-http/src/test/java/org/apache/ignite/internal/processors/rest/protocols/http/jetty/JettyRestHttpsReloadTest.java @@ -0,0 +1,602 @@ +/* + * 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.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 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; +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.internal.processors.ssl.ReloadableSslFactory; +import org.apache.ignite.ssl.TestCertificateAuthority; +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; +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 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_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; +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 + * 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 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) +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: 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. + * 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 that sends the host name 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 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 testAutoReloadedKeysSurviveFailedManualReload() 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 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 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 testAutoReloadTimeFollowsKeysInUse() throws Exception { + SourceSslContextFactory.supply(fresh(), due(), new IOException("Source is unavailable")); + + SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); + JettySslFactoryAdapter adapter = new JettySslFactoryAdapter(jettyFactory); + + jettyFactory.start(); + + try { + assertEquals(now + DAYS.toMillis(23), adapter.autoReloadTime()); + + jettyFactory.reload(f -> { }); + + long dueB = now + HOURS.toMillis(1) - DAYS.toMillis(7); + + assertEquals(dueB, adapter.autoReloadTime()); + assertThrows(log, adapter::init, IgniteException.class, "Source is unavailable"); + assertEquals(dueB, adapter.autoReloadTime()); + } + finally { + jettyFactory.stop(); + } + } + + /** + * 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: 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 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(); + 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, new AssertionError("Unexpected third key store load")); + + 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)); + + assertEquals(httpsA.getCertificate(HOST), serverCertificate(node)); + assertTrue(reload(node).contains(": HTTP REST: reloaded")); + assertEquals(httpsB.getCertificate(HOST), serverCertificate(node)); + } + + /** + * 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 automatic reload time of the factory. + * Then: automatic reload becomes due an hour before the certificate expires. + */ + @Test + public void testAutoReloadTimeUsesLeadTimeOfJettyFactory() throws Exception { + SourceSslContextFactory.supply(fresh()); + + ConfigurableSourceSslContextFactory jettyFactory = new ConfigurableSourceSslContextFactory(); + JettySslFactoryAdapter adapter = new JettySslFactoryAdapter(jettyFactory); + + jettyFactory.setAutoReloadBeforeExpiryMs(HOURS.toMillis(1)); + jettyFactory.start(); + + try { + assertEquals(now + DAYS.toMillis(30) - HOURS.toMillis(1), adapter.autoReloadTime()); + } + finally { + jettyFactory.stop(); + } + } + + /** + * 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(); + JettySslFactoryAdapter adapter = new JettySslFactoryAdapter(jettyFactory); + + jettyFactory.start(); + + try { + SSLContext ctx = jettyFactory.getSslContext(); + + assertThrows(log, adapter::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. + * 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 automatic 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 { + KeyStore b = fresh(); + + SourceSslContextFactory.supply(fresh(), new IOException("Source is unavailable")); + + SourceSslContextFactory jettyFactory = new SourceSslContextFactory(); + JettySslFactoryAdapter adapter = new JettySslFactoryAdapter(jettyFactory); + + jettyFactory.start(); + + try { + assertThrows(log, () -> jettyFactory.reload(f -> { }), Exception.class, "Source is unavailable"); + assertThrows(log, adapter::init, IgniteException.class, "Source is unavailable"); + + long autoReloadTime = adapter.autoReloadTime(); + + assertTrue(autoReloadTime > 0 && autoReloadTime <= System.currentTimeMillis()); + + SourceSslContextFactory.supply(b); + adapter.init(); + + assertEquals(b.getCertificate(HOST), jettyFactory.getKeyStore().getCertificate(HOST)); + } + 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. + * Then: the failed reload keeps the working context. The retry picks up the new trust store with the configured keys. + */ + @Test + 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(trusted, trust); + jettyFactory.setKeyStore(keys); + jettyFactory.setKeyStorePassword(new String(PASSWORD)); + jettyFactory.setTrustStorePath(trust.toString()); + jettyFactory.setTrustStoreType("JKS"); + jettyFactory.setTrustStorePassword(new String(PASSWORD)); + + JettySslFactoryAdapter adapter = new JettySslFactoryAdapter(jettyFactory); + + jettyFactory.start(); + + try { + SSLContext ctx = jettyFactory.getSslContext(); + + Files.writeString(trust, "not a trust store"); + + assertThrows(log, adapter::init, IgniteException.class, null); + assertSame(ctx, jettyFactory.getSslContext()); + + Certificate cert = keys.getCertificate(HOST); + + trusted.setCertificateEntry(HOST, cert); + save(trusted, trust); + adapter.init(); + + assertSame(keys, jettyFactory.getKeyStore()); + assertEquals(cert, jettyFactory.getTrustStore().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)); + + JettySslFactoryAdapter adapter = new JettySslFactoryAdapter(jettyFactory); + + jettyFactory.start(); + + try { + adapter.init(); + + assertEquals(1, reloads.get()); + } + finally { + jettyFactory.stop(); + } + } + + /** @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 automatic 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 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 { + int port = node.localNode().attribute(ATTR_REST_JETTY_PORT); + + try (SSLSocket sock = (SSLSocket)clientContext().getSocketFactory().createSocket(HOST, port)) { + SSLParameters params = sock.getSSLParameters(); + + params.setServerNames(List.of(new SNIHostName(HOST))); + sock.setSSLParameters(params); + sock.startHandshake(); + + return sock.getSession().getPeerCertificates()[0]; + } + } + + /** 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. + */ + public static class SourceSslContextFactory extends SslContextFactory.Server { + /** */ + private static final Deque LOADS = new ConcurrentLinkedDeque<>(); + + /** 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)); + } + + /** 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; + + if (load instanceof Error e) + throw e; + + return (KeyStore)load; + } + } + + /** 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 autoReloadEnabled = true; + + /** */ + private long autoReloadBeforeExpiryMs = DFLT_AUTO_RELOAD_BEFORE_EXPIRY_MS; + + /** */ + public ConfigurableSourceSslContextFactory() throws Exception { + // No-op. + } + + /** {@inheritDoc} */ + @Override public boolean isAutoReloadEnabled() { + return autoReloadEnabled; + } + + /** */ + public void setAutoReloadEnabled(boolean autoReloadEnabled) { + this.autoReloadEnabled = autoReloadEnabled; + } + + /** {@inheritDoc} */ + @Override public long getAutoReloadBeforeExpiryMs() { + return autoReloadBeforeExpiryMs; + } + + /** */ + public void setAutoReloadBeforeExpiryMs(long autoReloadBeforeExpiryMs) { + this.autoReloadBeforeExpiryMs = autoReloadBeforeExpiryMs; + } + } +} 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 + + + + + + + + + + + + + + + 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..f162ef5e94bbc --- /dev/null +++ b/modules/rest-http/src/test/resources/META-INF/jetty/https-source-manual.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + false + + + + + + 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..ef5bf2bac4c45 --- /dev/null +++ b/modules/rest-http/src/test/resources/META-INF/jetty/https.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + JKS + 123456 + true + + + + + + diff --git a/parent/pom.xml b/parent/pom.xml index 04629ecb634ce..429e2929b85bb 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 @@ -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