anton-vinogradov commented on code in PR #13874: URL: https://github.com/apache/ignite/pull/13874#discussion_r4737735760
########## 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 = "") Review Comment: After each test it removed the key store path that keyStoreFile() sets, so later tests did not get a stale path. afterTest() now clears the property, and the annotations are gone. ########## modules/core/src/main/java/org/apache/ignite/internal/processors/ssl/SslFactoryRegistry.java: ########## @@ -128,146 +123,204 @@ 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) executor.shutdownNow(); } /** - * 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<SSLContext> 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<SSLContext> 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) Review Comment: The flag is checked first: reload() returns before scheduleCheck() for a factory with automatic reload disabled. The null check covers a manual reload before onKernalStart(), which creates the executor and then schedules the first check of every factory with automatic reload enabled; testManualReloadBeforeStartLoadsFactory covers that case. ########## 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 { Review Comment: onKernalStart() schedules the first check in the ssl-auto-reload thread with no delay, so startGrid() can return before the check starts. The Jetty lock makes a handshake wait only for a reload that has already started, so without the wait a client can still see A. A sleep in loadKeyStore() keeps the reload running when the client connects, which hides the case where the check has not started yet. ########## 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<SSLContext> { Review Comment: Right, the settings were split. They now live in one public interface, org.apache.ignite.ssl.AutoReloadSslFactory, with isAutoReloadEnabled(), getAutoReloadBeforeExpiryMs() and the default lead time. ReloadableSslFactory extends it with init() and autoReloadTime(), which the registry calls; AbstractSslContextFactory implements it through ReloadableSslFactory, and a custom Jetty factory implements it directly. AutoReloadJettySslFactory is gone. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
