+ * 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