diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLService.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLService.java index a788090c831d9..2e7a3a5855943 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLService.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLService.java @@ -100,6 +100,7 @@ public class SSLService { private static final Setting DIAGNOSE_TRUST_EXCEPTIONS_SETTING = Setting.boolSetting( "xpack.security.ssl.diagnose.trust", true, Setting.Property.NodeScope); + private final Environment env; private final Settings settings; private final boolean diagnoseTrustExceptions; @@ -120,33 +121,33 @@ public class SSLService { */ private final Map sslContexts; private final SetOnce transportSSLConfiguration = new SetOnce<>(); - private final Environment env; /** - * Create a new SSLService using the {@code Settings} from {@link Environment#settings()}. - * @see #SSLService(Settings, Environment) + * Create a new SSLService that parses the settings for the ssl contexts that need to be created, creates them, and then caches them + * for use later */ public SSLService(Environment environment) { - this(environment.settings(), environment); + this.env = environment; + this.settings = env.settings(); + this.diagnoseTrustExceptions = DIAGNOSE_TRUST_EXCEPTIONS_SETTING.get(environment.settings()); + this.sslConfigurations = new HashMap<>(); + this.sslContexts = loadSSLConfigurations(); } - /** - * Create a new SSLService that parses the settings for the ssl contexts that need to be created, creates them, and then caches them - * for use later - */ + @Deprecated public SSLService(Settings settings, Environment environment) { - this.settings = settings; this.env = environment; + this.settings = env.settings(); this.diagnoseTrustExceptions = DIAGNOSE_TRUST_EXCEPTIONS_SETTING.get(settings); this.sslConfigurations = new HashMap<>(); this.sslContexts = loadSSLConfigurations(); } - private SSLService(Settings settings, Environment environment, Map sslConfigurations, + private SSLService(Environment environment, Map sslConfigurations, Map sslContexts) { - this.settings = settings; this.env = environment; - this.diagnoseTrustExceptions = DIAGNOSE_TRUST_EXCEPTIONS_SETTING.get(settings); + this.settings = env.settings(); + this.diagnoseTrustExceptions = DIAGNOSE_TRUST_EXCEPTIONS_SETTING.get(environment.settings()); this.sslConfigurations = sslConfigurations; this.sslContexts = sslContexts; } @@ -157,7 +158,7 @@ private SSLService(Settings settings, Environment environment, Map loadSSLConfigurations() { @@ -489,9 +490,9 @@ X509ExtendedTrustManager wrapWithDiagnostics(X509ExtendedTrustManager trustManag * Parses the settings to load all SSLConfiguration objects that will be used. */ Map loadSSLConfigurations() { - Map sslContextHolders = new HashMap<>(); + final Map sslContextHolders = new HashMap<>(); - Map sslSettingsMap = new HashMap<>(); + final Map sslSettingsMap = new HashMap<>(); sslSettingsMap.put(XPackSettings.HTTP_SSL_PREFIX, getHttpTransportSSLSettings(settings)); sslSettingsMap.put("xpack.http.ssl", settings.getByPrefix("xpack.http.ssl.")); sslSettingsMap.putAll(getRealmsSSLSettings(settings)); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/transport/ProfileConfigurationsTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/transport/ProfileConfigurationsTests.java index fd7315d7457c2..8b3d4cc3bec75 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/transport/ProfileConfigurationsTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/transport/ProfileConfigurationsTests.java @@ -30,7 +30,7 @@ public void testGetSecureTransportProfileConfigurations() { .put("transport.profiles.cert.xpack.security.ssl.verification_mode", VerificationMode.CERTIFICATE.name()) .build(); final Environment env = TestEnvironment.newEnvironment(settings); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(env); final SSLConfiguration defaultConfig = sslService.getSSLConfiguration("xpack.security.transport.ssl"); final Map profileConfigurations = ProfileConfigurations.get(settings, sslService, defaultConfig); assertThat(profileConfigurations.size(), Matchers.equalTo(3)); @@ -48,7 +48,7 @@ public void testGetInsecureTransportProfileConfigurations() { .put("transport.profiles.none.xpack.security.ssl.verification_mode", VerificationMode.NONE.name()) .build(); final Environment env = TestEnvironment.newEnvironment(settings); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(env); final SSLConfiguration defaultConfig = sslService.getSSLConfiguration("xpack.security.transport.ssl"); final Map profileConfigurations = ProfileConfigurations.get(settings, sslService, defaultConfig); assertThat(profileConfigurations.size(), Matchers.equalTo(2)); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SSLConfigurationReloaderTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SSLConfigurationReloaderTests.java index c2ba99a441616..2c9cc037e7cc4 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SSLConfigurationReloaderTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SSLConfigurationReloaderTests.java @@ -147,7 +147,7 @@ public void testReloadingKeyStore() throws Exception { throw new RuntimeException("Exception starting or connecting to the mock server", e); } }; - validateSSLConfigurationIsReloaded(settings, env, keyMaterialPreChecks, modifier, keyMaterialPostChecks); + validateSSLConfigurationIsReloaded(env, keyMaterialPreChecks, modifier, keyMaterialPostChecks); } } /** @@ -174,7 +174,7 @@ public void testPEMKeyConfigReloading() throws Exception { .putList("xpack.security.transport.ssl.certificate_authorities", certPath.toString()) .setSecureSettings(secureSettings) .build(); - final Environment env = newEnvironment(); + final Environment env = TestEnvironment.newEnvironment(settings); // Load HTTPClient once. Client uses a keystore containing testnode key/cert as a truststore try (CloseableHttpClient client = getSSLClient(Collections.singletonList(certPath))) { final Consumer keyMaterialPreChecks = (context) -> { @@ -207,7 +207,7 @@ public void testPEMKeyConfigReloading() throws Exception { throw new RuntimeException("Exception starting or connecting to the mock server", e); } }; - validateSSLConfigurationIsReloaded(settings, env, keyMaterialPreChecks, modifier, keyMaterialPostChecks); + validateSSLConfigurationIsReloaded(env, keyMaterialPreChecks, modifier, keyMaterialPostChecks); } } @@ -259,7 +259,7 @@ public void testReloadingTrustStore() throws Exception { throw new RuntimeException("Error closing CloseableHttpClient", e); } }; - validateSSLConfigurationIsReloaded(settings, env, trustMaterialPreChecks, modifier, trustMaterialPostChecks); + validateSSLConfigurationIsReloaded(env, trustMaterialPreChecks, modifier, trustMaterialPostChecks); } } @@ -309,7 +309,7 @@ public void testReloadingPEMTrustConfig() throws Exception { throw new RuntimeException("Error closing CloseableHttpClient", e); } }; - validateSSLConfigurationIsReloaded(settings, env, trustMaterialPreChecks, modifier, trustMaterialPostChecks); + validateSSLConfigurationIsReloaded(env, trustMaterialPreChecks, modifier, trustMaterialPostChecks); } } @@ -331,7 +331,7 @@ public void testReloadingKeyStoreException() throws Exception { .put("path.home", createTempDir()) .build(); Environment env = TestEnvironment.newEnvironment(settings); - final SSLService sslService = new SSLService(settings, env); + final SSLService sslService = new SSLService(env); final SSLConfiguration config = sslService.getSSLConfiguration("xpack.security.transport.ssl."); final AtomicReference exceptionRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); @@ -353,6 +353,7 @@ void reloadSSLContext(SSLConfiguration configuration) { // truncate the keystore try (OutputStream ignore = Files.newOutputStream(keystorePath, StandardOpenOption.TRUNCATE_EXISTING)) { + // do nothing } latch.await(); @@ -384,7 +385,7 @@ public void testReloadingPEMKeyConfigException() throws Exception { .setSecureSettings(secureSettings) .build(); Environment env = TestEnvironment.newEnvironment(settings); - final SSLService sslService = new SSLService(settings, env); + final SSLService sslService = new SSLService(env); final SSLConfiguration config = sslService.getSSLConfiguration("xpack.security.transport.ssl."); final AtomicReference exceptionRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); @@ -430,7 +431,7 @@ public void testTrustStoreReloadException() throws Exception { .put("path.home", createTempDir()) .build(); Environment env = TestEnvironment.newEnvironment(settings); - final SSLService sslService = new SSLService(settings, env); + final SSLService sslService = new SSLService(env); final SSLConfiguration config = sslService.getSSLConfiguration("xpack.security.transport.ssl."); final AtomicReference exceptionRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); @@ -474,7 +475,7 @@ public void testPEMTrustReloadException() throws Exception { .put("path.home", createTempDir()) .build(); Environment env = TestEnvironment.newEnvironment(settings); - final SSLService sslService = new SSLService(settings, env); + final SSLService sslService = new SSLService(env); final SSLConfiguration config = sslService.sslConfiguration(settings.getByPrefix("xpack.security.transport.ssl.")); final AtomicReference exceptionRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); @@ -524,10 +525,10 @@ private Settings.Builder baseKeystoreSettings(Path tempDir, MockSecureSettings s .setSecureSettings(secureSettings); } - private void validateSSLConfigurationIsReloaded(Settings settings, Environment env, Consumer preChecks, + private void validateSSLConfigurationIsReloaded(Environment env, Consumer preChecks, Runnable modificationFunction, Consumer postChecks) throws Exception { final CountDownLatch reloadLatch = new CountDownLatch(1); - final SSLService sslService = new SSLService(settings, env); + final SSLService sslService = new SSLService(env); final SSLConfiguration config = sslService.getSSLConfiguration("xpack.security.transport.ssl"); new SSLConfigurationReloader(env, sslService, resourceWatcherService) { @Override diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SSLServiceTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SSLServiceTests.java index b2bf6974e319d..14654902b0405 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SSLServiceTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/SSLServiceTests.java @@ -121,7 +121,7 @@ public void testThatCustomTruststoreCanBeSpecified() throws Exception { .setSecureSettings(secureSettings) .put("transport.profiles.foo.xpack.security.ssl.truststore.path", testClientStore) .build(); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); MockSecureSettings secureCustomSettings = new MockSecureSettings(); secureCustomSettings.setString("truststore.secure_password", "testclient"); @@ -153,7 +153,7 @@ public void testThatSslContextCachingWorks() throws Exception { .put("xpack.security.transport.ssl.key", testnodeKey) .setSecureSettings(secureSettings) .build(); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); final Settings transportSSLSettings = settings.getByPrefix("xpack.security.transport.ssl."); SSLContext sslContext = sslService.sslContext(sslService.sslConfiguration(transportSSLSettings)); @@ -179,7 +179,7 @@ public void testThatKeyStoreAndKeyCanHaveDifferentPasswords() throws Exception { .setSecureSettings(secureSettings) .build(); - final SSLService sslService = new SSLService(settings, env); + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); SSLConfiguration configuration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); sslService.createSSLEngine(configuration, null, -1); } @@ -195,7 +195,7 @@ public void testIncorrectKeyPasswordThrowsException() throws Exception { .put("xpack.security.transport.ssl.keystore.path", differentPasswordsStore) .setSecureSettings(secureSettings) .build(); - final SSLService sslService = new SSLService(settings, env); + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); SSLConfiguration configuration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); sslService.createSSLEngine(configuration, null, -1); fail("expected an exception"); @@ -214,14 +214,14 @@ public void testThatSSLv3IsNotEnabled() throws Exception { .put("xpack.security.transport.ssl.key", testnodeKey) .setSecureSettings(secureSettings) .build(); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); SSLConfiguration configuration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); SSLEngine engine = sslService.createSSLEngine(configuration, null, -1); assertThat(Arrays.asList(engine.getEnabledProtocols()), not(hasItem("SSLv3"))); } public void testThatCreateClientSSLEngineWithoutAnySettingsWorks() throws Exception { - SSLService sslService = new SSLService(Settings.EMPTY, env); + SSLService sslService = new SSLService(env); SSLConfiguration configuration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); SSLEngine sslEngine = sslService.createSSLEngine(configuration, null, -1); assertThat(sslEngine, notNullValue()); @@ -235,7 +235,7 @@ public void testThatCreateSSLEngineWithOnlyTruststoreWorks() throws Exception { .put("xpack.http.ssl.truststore.path", testclientStore) .setSecureSettings(secureSettings) .build(); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); SSLConfiguration configuration = sslService.getSSLConfiguration("xpack.security.http.ssl"); SSLEngine sslEngine = sslService.createSSLEngine(configuration, null, -1); assertThat(sslEngine, notNullValue()); @@ -252,7 +252,7 @@ public void testCreateWithKeystoreIsValidForServer() throws Exception { .put("xpack.security.transport.ssl.keystore.type", testnodeStoreType) .setSecureSettings(secureSettings) .build(); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); assertTrue(sslService.isConfigurationValidForServerUsage(sslService.getSSLConfiguration("xpack.security.transport.ssl"))); } @@ -266,7 +266,7 @@ public void testValidForServer() throws Exception { .put("xpack.http.ssl.truststore.type", testnodeStoreType) .setSecureSettings(secureSettings) .build(); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); // Technically, we don't care whether xpack.http.ssl is valid for server - it's a client context, but we validate both of the // server contexts (http & transport) during construction, so this is the only way to make a non-server-valid context. assertFalse(sslService.isConfigurationValidForServerUsage(sslService.getSSLConfiguration("xpack.http.ssl"))); @@ -279,13 +279,13 @@ public void testValidForServer() throws Exception { .put("xpack.http.ssl.keystore.path", testnodeStore) .put("xpack.http.ssl.keystore.type", testnodeStoreType) .build(); - sslService = new SSLService(settings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); assertTrue(sslService.isConfigurationValidForServerUsage(sslService.getSSLConfiguration("xpack.http.ssl"))); } public void testGetVerificationMode() throws Exception { assumeFalse("Can't run in a FIPS JVM, TrustAllConfig is not a SunJSSE TrustManagers", inFipsJvm()); - SSLService sslService = new SSLService(Settings.EMPTY, env); + SSLService sslService = new SSLService(env); assertThat(sslService.getSSLConfiguration("xpack.security.transport.ssl").verificationMode(), is(XPackSettings.VERIFICATION_MODE_DEFAULT)); @@ -294,14 +294,14 @@ public void testGetVerificationMode() throws Exception { .put("xpack.security.transport.ssl.verification_mode", "certificate") .put("transport.profiles.foo.xpack.security.ssl.verification_mode", "full") .build(); - sslService = new SSLService(settings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); assertThat(sslService.getSSLConfiguration("xpack.security.transport.ssl.").verificationMode(), is(VerificationMode.CERTIFICATE)); assertThat(sslService.getSSLConfiguration("transport.profiles.foo.xpack.security.ssl.").verificationMode(), is(VerificationMode.FULL)); } public void testIsSSLClientAuthEnabled() throws Exception { - SSLService sslService = new SSLService(Settings.EMPTY, env); + SSLService sslService = new SSLService(env); assertTrue(sslService.getSSLConfiguration("xpack.security.transport.ssl").sslClientAuth().enabled()); Settings settings = Settings.builder() @@ -309,7 +309,7 @@ public void testIsSSLClientAuthEnabled() throws Exception { .put("xpack.security.transport.ssl.client_authentication", "optional") .put("transport.profiles.foo.port", "9400-9410") .build(); - sslService = new SSLService(settings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); assertTrue(sslService.isSSLClientAuthEnabled(sslService.getSSLConfiguration("xpack.security.transport.ssl"))); assertTrue(sslService.isSSLClientAuthEnabled(sslService.getSSLConfiguration("transport.profiles.foo.xpack.security.ssl"))); } @@ -328,7 +328,7 @@ public void testThatHttpClientAuthDefaultsToNone() throws Exception { .put("xpack.security.transport.ssl.keystore.type", testnodeStoreType) .setSecureSettings(secureSettings) .build(); - final SSLService sslService = new SSLService(globalSettings, env); + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(globalSettings))); final SSLConfiguration globalConfig = sslService.getSSLConfiguration("xpack.security.transport.ssl"); assertThat(globalConfig.sslClientAuth(), is(SSLClientAuth.OPTIONAL)); @@ -348,7 +348,7 @@ public void testThatTruststorePasswordIsRequired() throws Exception { .put("xpack.security.transport.ssl.truststore.type", testnodeStoreType) .build(); ElasticsearchException e = - expectThrows(ElasticsearchException.class, () -> new SSLService(settings, env)); + expectThrows(ElasticsearchException.class, () -> new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings)))); assertThat(e, throwableWithMessage("failed to load SSL configuration [xpack.security.transport.ssl]")); assertThat(e.getCause(), throwableWithMessage(containsString("failed to initialize SSL TrustManager"))); } @@ -359,7 +359,7 @@ public void testThatKeystorePasswordIsRequired() throws Exception { .put("xpack.security.transport.ssl.keystore.type", testnodeStoreType) .build(); ElasticsearchException e = - expectThrows(ElasticsearchException.class, () -> new SSLService(settings, env)); + expectThrows(ElasticsearchException.class, () -> new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings)))); assertThat(e, throwableWithMessage("failed to load SSL configuration [xpack.security.transport.ssl]")); assertThat(e.getCause(), throwableWithMessage("failed to create trust manager")); } @@ -377,7 +377,7 @@ public void testCiphersAndInvalidCiphersWork() throws Exception { .setSecureSettings(secureSettings) .putList("xpack.security.transport.ssl.ciphers", ciphers.toArray(new String[ciphers.size()])) .build(); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); SSLConfiguration configuration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); SSLEngine engine = sslService.createSSLEngine(configuration, null, -1); assertThat(engine, is(notNullValue())); @@ -396,7 +396,7 @@ public void testInvalidCiphersOnlyThrowsException() throws Exception { .putList("xpack.security.transport.ssl.cipher_suites", new String[] { "foo", "bar" }) .build(); ElasticsearchException e = - expectThrows(ElasticsearchException.class, () -> new SSLService(settings, env)); + expectThrows(ElasticsearchException.class, () -> new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings)))); assertThat(e, throwableWithMessage("failed to load SSL configuration [xpack.security.transport.ssl]")); assertThat(e.getCause(), throwableWithMessage("none of the ciphers [foo, bar] are supported by this JVM")); } @@ -410,7 +410,7 @@ public void testThatSSLEngineHasCipherSuitesOrderSet() throws Exception { .put("xpack.security.transport.ssl.key", testnodeKey) .setSecureSettings(secureSettings) .build(); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); SSLConfiguration configuration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); SSLEngine engine = sslService.createSSLEngine(configuration, null, -1); assertThat(engine, is(notNullValue())); @@ -426,7 +426,7 @@ public void testThatSSLSocketFactoryHasProperCiphersAndProtocols() throws Except .put("xpack.security.transport.ssl.key", testnodeKey) .setSecureSettings(secureSettings) .build(); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); SSLConfiguration config = sslService.getSSLConfiguration("xpack.security.transport.ssl"); final SSLSocketFactory factory = sslService.sslSocketFactory(config); final String[] ciphers = sslService.supportedCiphers(factory.getSupportedCipherSuites(), config.cipherSuites(), false); @@ -452,7 +452,7 @@ public void testThatSSLEngineHasProperCiphersAndProtocols() throws Exception { .put("xpack.security.transport.ssl.key", testnodeKey) .setSecureSettings(secureSettings) .build(); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); SSLConfiguration configuration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); SSLEngine engine = sslService.createSSLEngine(configuration, null, -1); final String[] ciphers = sslService.supportedCiphers(engine.getSupportedCipherSuites(), configuration.cipherSuites(), false); @@ -542,7 +542,7 @@ public void testGetConfigurationByContextName() throws Exception { final Settings settings = builder .setSecureSettings(secureSettings) .build(); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); for (int i = 0; i < contextNames.length; i++) { final String name = contextNames[i]; @@ -576,7 +576,7 @@ public void testReadCertificateInformation() throws Exception { .setSecureSettings(secureSettings) .build(); - final SSLService sslService = new SSLService(settings, env); + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); final List certificates = new ArrayList<>(sslService.getLoadedCertificates()); assertThat(certificates, iterableWithSize(13)); Collections.sort(certificates, @@ -757,7 +757,7 @@ public int getSessionCacheSize() { @Network public void testThatSSLContextWithoutSettingsWorks() throws Exception { - SSLService sslService = new SSLService(Settings.EMPTY, env); + SSLService sslService = new SSLService(env); SSLContext sslContext = sslService.sslContext(sslService.sslConfiguration(Settings.EMPTY)); try (CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).build()) { // Execute a GET on a site known to have a valid certificate signed by a trusted public CA @@ -775,7 +775,7 @@ public void testThatSSLContextTrustsJDKTrustedCAs() throws Exception { .put("xpack.security.transport.ssl.keystore.path", testclientStore) .setSecureSettings(secureSettings) .build(); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); SSLContext sslContext = sslService.sslContext(sslService.sslConfiguration(settings.getByPrefix("xpack.security.transport.ssl."))); try (CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).build()) { // Execute a GET on a site known to have a valid certificate signed by a trusted public CA which will succeed because the JDK @@ -786,7 +786,7 @@ public void testThatSSLContextTrustsJDKTrustedCAs() throws Exception { @Network public void testThatSSLIOSessionStrategyWithoutSettingsWorks() throws Exception { - SSLService sslService = new SSLService(Settings.EMPTY, env); + SSLService sslService = new SSLService(env); SSLConfiguration sslConfiguration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); logger.info("SSL Configuration: {}", sslConfiguration); SSLIOSessionStrategy sslStrategy = sslService.sslIOSessionStrategy(sslConfiguration); @@ -808,7 +808,7 @@ public void testThatSSLIOSessionStrategyTrustsJDKTrustedCAs() throws Exception { .put("xpack.security.transport.ssl.keystore.path", testclientStore) .setSecureSettings(secureSettings) .build(); - final SSLService sslService = new SSLService(settings, env); + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); SSLIOSessionStrategy sslStrategy = sslService.sslIOSessionStrategy(sslService.getSSLConfiguration("xpack.security.transport.ssl")); try (CloseableHttpAsyncClient client = getAsyncHttpClient(sslStrategy)) { client.start(); @@ -824,7 +824,7 @@ public void testWrapTrustManagerWhenDiagnosticsEnabled() { if (randomBoolean()) { // randomly select between default, and explicit enabled builder.put("xpack.security.ssl.diagnose.trust", true); } - final SSLService sslService = new SSLService(builder.build(), env); + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(builder.build()))); final X509ExtendedTrustManager baseTrustManager = TrustAllConfig.INSTANCE.createTrustManager(env); final SSLConfiguration sslConfiguration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); final X509ExtendedTrustManager wrappedTrustManager = sslService.wrapWithDiagnostics(baseTrustManager, sslConfiguration); @@ -835,7 +835,7 @@ public void testWrapTrustManagerWhenDiagnosticsEnabled() { public void testDontWrapTrustManagerWhenDiagnosticsDisabled() { final Settings.Builder builder = Settings.builder(); builder.put("xpack.security.ssl.diagnose.trust", false); - final SSLService sslService = new SSLService(builder.build(), env); + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(builder.build()))); final X509ExtendedTrustManager baseTrustManager = TrustAllConfig.INSTANCE.createTrustManager(env); final SSLConfiguration sslConfiguration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); assertThat(sslService.wrapWithDiagnostics(baseTrustManager, sslConfiguration), sameInstance(baseTrustManager)); diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/TestsSSLService.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/TestsSSLService.java index e8766225a7a92..5a2c43d504616 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/TestsSSLService.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ssl/TestsSSLService.java @@ -15,8 +15,8 @@ */ public class TestsSSLService extends SSLService { - public TestsSSLService(Settings settings, Environment environment) { - super(settings, environment); + public TestsSSLService(Environment environment) { + super(environment); } /** diff --git a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterIT.java b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterIT.java index 1bed5f1c7fff9..7f1c0554b0e4f 100644 --- a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterIT.java +++ b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterIT.java @@ -590,7 +590,7 @@ private HttpExporter createHttpExporter(final Settings settings) { final Exporter.Config config = new Exporter.Config("_http", "http", settings, clusterService(), new XPackLicenseState(Settings.EMPTY)); - return new HttpExporter(config, new SSLService(settings, environment), new ThreadContext(settings)); + return new HttpExporter(config, new SSLService(TestEnvironment.newEnvironment(settings)), new ThreadContext(settings)); } private void export(final Settings settings, final Collection docs) throws Exception { diff --git a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterSslIT.java b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterSslIT.java index fb0da753be3b5..94b1e3f4699b4 100644 --- a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterSslIT.java +++ b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterSslIT.java @@ -12,7 +12,6 @@ import org.elasticsearch.bootstrap.JavaVersion; import org.elasticsearch.common.settings.MockSecureSettings; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.env.Environment; import org.elasticsearch.env.TestEnvironment; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.Scope; @@ -44,7 +43,6 @@ public class HttpExporterSslIT extends MonitoringIntegTestCase { private final Settings globalSettings = Settings.builder().put("path.home", createTempDir()).build(); - private final Environment environment = TestEnvironment.newEnvironment(globalSettings); private static MockWebServer webServer; private MockSecureSettings secureSettings; @@ -108,7 +106,7 @@ private MockWebServer buildWebServer() throws IOException { .put(globalSettings) .build(); - TestsSSLService sslService = new TestsSSLService(sslSettings, environment); + TestsSSLService sslService = new TestsSSLService(TestEnvironment.newEnvironment(sslSettings)); final SSLContext sslContext = sslService.sslContext("xpack.security.transport.ssl"); MockWebServer server = new MockWebServer(sslContext, false); server.start(); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/tool/CommandLineHttpClient.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/tool/CommandLineHttpClient.java index 7e9d5a8a32657..4b16e4d84bda3 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/tool/CommandLineHttpClient.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/tool/CommandLineHttpClient.java @@ -53,11 +53,9 @@ public class CommandLineHttpClient { */ private static final int READ_TIMEOUT = 35 * 1000; - private final Settings settings; private final Environment env; - public CommandLineHttpClient(Settings settings, Environment env) { - this.settings = settings; + public CommandLineHttpClient(Environment env) { this.env = env; } @@ -82,7 +80,7 @@ public HttpResponse execute(String method, URL url, String user, SecureString pa final HttpURLConnection conn; // If using SSL, need a custom service because it's likely a self-signed certificate if ("https".equalsIgnoreCase(url.getProtocol())) { - final SSLService sslService = new SSLService(settings, env); + final SSLService sslService = new SSLService(env); final HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection(); AccessController.doPrivileged((PrivilegedAction) () -> { final SSLConfiguration sslConfiguration = sslService.getHttpTransportSSLConfiguration(); @@ -133,6 +131,7 @@ public HttpResponse execute(String method, URL url, String user, SecureString pa } String getDefaultURL() { + final Settings settings = env.settings(); final String scheme = XPackSettings.HTTP_SSL_ENABLED.get(settings) ? "https" : "http"; List httpPublishHost = SETTING_HTTP_PUBLISH_HOST.get(settings); if (httpPublishHost.isEmpty()) { @@ -162,5 +161,4 @@ String getDefaultURL() { "provide the url", e); } } - } diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordTool.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordTool.java index 5ac81a0648019..9f853134d00b7 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordTool.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordTool.java @@ -50,7 +50,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.function.BiFunction; +import java.util.function.Function; import static java.util.Arrays.asList; @@ -68,15 +68,13 @@ public class SetupPasswordTool extends LoggingAwareMultiCommand { public static final List USERS = asList(ElasticUser.NAME, APMSystemUser.NAME, KibanaUser.NAME, LogstashSystemUser.NAME, BeatsSystemUser.NAME, RemoteMonitoringUser.NAME); - private final BiFunction clientFunction; + private final Function clientFunction; private final CheckedFunction keyStoreFunction; private CommandLineHttpClient client; SetupPasswordTool() { - this((environment, settings) -> { - return new CommandLineHttpClient(settings, environment); - }, (environment) -> { + this(environment -> new CommandLineHttpClient(environment), environment -> { KeyStoreWrapper keyStoreWrapper = KeyStoreWrapper.load(environment.configFile()); if (keyStoreWrapper == null) { throw new UserException(ExitCodes.CONFIG, @@ -86,8 +84,8 @@ public class SetupPasswordTool extends LoggingAwareMultiCommand { }); } - SetupPasswordTool(BiFunction clientFunction, - CheckedFunction keyStoreFunction) { + SetupPasswordTool(Function clientFunction, + CheckedFunction keyStoreFunction) { super("Sets the passwords for reserved users"); subcommands.put("auto", newAutoSetup()); subcommands.put("interactive", newInteractiveSetup()); @@ -261,12 +259,14 @@ void setupOptions(OptionSet options, Environment env) throws Exception { Settings settings = settingsBuilder.build(); elasticUserPassword = ReservedRealm.BOOTSTRAP_ELASTIC_PASSWORD.get(settings); - client = clientFunction.apply(env, settings); + final Environment newEnv = new Environment(settings, env.configFile()); + Environment.assertEquivalent(newEnv, env); + + client = clientFunction.apply(newEnv); String providedUrl = urlOption.value(options); url = new URL(providedUrl == null ? client.getDefaultURL() : providedUrl); setShouldPrompt(options); - } private void setParser() { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/PkiRealmBootstrapCheckTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/PkiRealmBootstrapCheckTests.java index 62aece1f4fdf2..2d9411f5407b9 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/PkiRealmBootstrapCheckTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/PkiRealmBootstrapCheckTests.java @@ -19,9 +19,8 @@ public class PkiRealmBootstrapCheckTests extends AbstractBootstrapCheckTestCase { public void testPkiRealmBootstrapDefault() throws Exception { - final Settings settings = Settings.EMPTY; - final Environment env = TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build()); - assertFalse(runCheck(settings, env).isFailure()); + final Settings settings = Settings.builder().put("path.home", createTempDir()).build(); + assertFalse(runCheck(settings).isFailure()); } public void testBootstrapCheckWithPkiRealm() throws Exception { @@ -34,8 +33,7 @@ public void testBootstrapCheckWithPkiRealm() throws Exception { .put("path.home", createTempDir()) .setSecureSettings(secureSettings) .build(); - Environment env = TestEnvironment.newEnvironment(settings); - assertTrue(runCheck(settings, env).isFailure()); + assertTrue(runCheck(settings).isFailure()); // enable transport tls secureSettings.setString("xpack.security.transport.ssl.secure_key_passphrase", "testnode"); @@ -44,7 +42,7 @@ public void testBootstrapCheckWithPkiRealm() throws Exception { .put("xpack.security.transport.ssl.certificate", certPath) .put("xpack.security.transport.ssl.key", keyPath) .build(); - assertFalse(runCheck(settings, env).isFailure()); + assertFalse(runCheck(settings).isFailure()); // enable ssl for http secureSettings.setString("xpack.security.http.ssl.secure_key_passphrase", "testnode"); @@ -54,29 +52,25 @@ public void testBootstrapCheckWithPkiRealm() throws Exception { .put("xpack.security.http.ssl.certificate", certPath) .put("xpack.security.http.ssl.key", keyPath) .build(); - env = TestEnvironment.newEnvironment(settings); - assertTrue(runCheck(settings, env).isFailure()); + assertTrue(runCheck(settings).isFailure()); // enable client auth for http settings = Settings.builder().put(settings) .put("xpack.security.http.ssl.client_authentication", randomFrom("required", "optional")) .build(); - env = TestEnvironment.newEnvironment(settings); - assertFalse(runCheck(settings, env).isFailure()); + assertFalse(runCheck(settings).isFailure()); // disable http ssl settings = Settings.builder().put(settings) .put("xpack.security.http.ssl.enabled", false) .build(); - env = TestEnvironment.newEnvironment(settings); - assertTrue(runCheck(settings, env).isFailure()); + assertTrue(runCheck(settings).isFailure()); // set transport auth settings = Settings.builder().put(settings) .put("xpack.security.transport.client_authentication", randomFrom("required", "optional")) .build(); - env = TestEnvironment.newEnvironment(settings); - assertTrue(runCheck(settings, env).isFailure()); + assertTrue(runCheck(settings).isFailure()); // test with transport profile settings = Settings.builder().put(settings) @@ -84,12 +78,12 @@ public void testBootstrapCheckWithPkiRealm() throws Exception { .put("xpack.security.transport.client_authentication", "none") .put("transport.profiles.foo.xpack.security.ssl.client_authentication", randomFrom("required", "optional")) .build(); - env = TestEnvironment.newEnvironment(settings); - assertFalse(runCheck(settings, env).isFailure()); + assertFalse(runCheck(settings).isFailure()); } - private BootstrapCheck.BootstrapCheckResult runCheck(Settings settings, Environment env) throws Exception { - return new PkiRealmBootstrapCheck(new SSLService(settings, env)).check(createTestContext(settings, null)); + private BootstrapCheck.BootstrapCheckResult runCheck(Settings settings) throws Exception { + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(settings)); + return new PkiRealmBootstrapCheck(sslService).check(createTestContext(settings, null)); } public void testBootstrapCheckWithDisabledRealm() throws Exception { @@ -100,7 +94,7 @@ public void testBootstrapCheckWithDisabledRealm() throws Exception { .put("path.home", createTempDir()) .build(); Environment env = TestEnvironment.newEnvironment(settings); - assertFalse(runCheck(settings, env).isFailure()); + assertFalse(runCheck(settings).isFailure()); } public void testBootstrapCheckWithDelegationEnabled() throws Exception { @@ -119,8 +113,7 @@ public void testBootstrapCheckWithDelegationEnabled() throws Exception { .put("path.home", createTempDir()) .setSecureSettings(secureSettings) .build(); - Environment env = TestEnvironment.newEnvironment(settings); - assertFalse(runCheck(settings, env).isFailure()); + assertFalse(runCheck(settings).isFailure()); } public void testBootstrapCheckWithClosedSecuredSetting() throws Exception { @@ -140,7 +133,7 @@ public void testBootstrapCheckWithClosedSecuredSetting() throws Exception { .build(); Environment env = TestEnvironment.newEnvironment(settings); - final PkiRealmBootstrapCheck check = new PkiRealmBootstrapCheck(new SSLService(settings, env)); + final PkiRealmBootstrapCheck check = new PkiRealmBootstrapCheck(new SSLService(env)); secureSettings.close(); assertThat(check.check(createTestContext(settings, null)).isFailure(), Matchers.equalTo(expectFail)); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/SecurityTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/SecurityTests.java index 2d663ea619f9a..d5b513284510f 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/SecurityTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/SecurityTests.java @@ -104,7 +104,7 @@ private Collection createComponents(Settings testSettings, SecurityExten .put("path.home", createTempDir()).build(); Environment env = TestEnvironment.newEnvironment(settings); licenseState = new TestUtils.UpdatableLicenseState(settings); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(env); security = new Security(settings, null, Arrays.asList(extensions)) { @Override protected XPackLicenseState getLicenseState() { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectLogoutActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectLogoutActionTests.java index 387470090735b..d2ed6500036c4 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectLogoutActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectLogoutActionTests.java @@ -182,8 +182,8 @@ public void setup() throws Exception { final RealmConfig.RealmIdentifier realmIdentifier = new RealmConfig.RealmIdentifier("oidc", REALM_NAME); final RealmConfig realmConfig = new RealmConfig(realmIdentifier, settings, env, threadContext); - oidcRealm = new OpenIdConnectRealm(realmConfig, new SSLService(sslSettings, env), mock(UserRoleMapper.class), - mock(ResourceWatcherService.class)); + oidcRealm = new OpenIdConnectRealm(realmConfig, new SSLService(TestEnvironment.newEnvironment(sslSettings)), + mock(UserRoleMapper.class), mock(ResourceWatcherService.class)); when(realms.realm(realmConfig.name())).thenReturn(oidcRealm); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/CommandLineHttpClientTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/CommandLineHttpClientTests.java index 4f2484d193116..65ae66278cee2 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/CommandLineHttpClientTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/CommandLineHttpClientTests.java @@ -8,7 +8,6 @@ import org.elasticsearch.common.settings.MockSecureSettings; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.env.Environment; import org.elasticsearch.env.TestEnvironment; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.http.MockResponse; @@ -36,7 +35,6 @@ public class CommandLineHttpClientTests extends ESTestCase { private MockWebServer webServer; - private Environment environment = TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build()); private Path certPath; private Path keyPath; @@ -60,7 +58,7 @@ public void testCommandLineHttpClientCanExecuteAndReturnCorrectResultUsingSSLSet .put("xpack.security.http.ssl.certificate_authorities", certPath.toString()) .put("xpack.security.http.ssl.verification_mode", VerificationMode.CERTIFICATE) .build(); - CommandLineHttpClient client = new CommandLineHttpClient(settings, environment); + CommandLineHttpClient client = new CommandLineHttpClient(TestEnvironment.newEnvironment(settings)); HttpResponse httpResponse = client.execute("GET", new URL("https://localhost:" + webServer.getPort() + "/test"), "u1", new SecureString(new char[]{'p'}), () -> null, is -> responseBuilder(is)); @@ -71,16 +69,17 @@ public void testCommandLineHttpClientCanExecuteAndReturnCorrectResultUsingSSLSet public void testGetDefaultURLFailsWithHelpfulMessage() { Settings settings = Settings.builder() + .put("path.home", createTempDir()) .put("network.host", "_ec2:privateIpv4_") .build(); - CommandLineHttpClient client = new CommandLineHttpClient(settings, environment); + CommandLineHttpClient client = new CommandLineHttpClient(TestEnvironment.newEnvironment(settings)); assertThat(expectThrows(IllegalStateException.class, () -> client.getDefaultURL()).getMessage(), containsString("unable to determine default URL from settings, please use the -u option to explicitly provide the url")); } private MockWebServer createMockWebServer() { Settings settings = getHttpSslSettings().build(); - TestsSSLService sslService = new TestsSSLService(settings, environment); + TestsSSLService sslService = new TestsSSLService(TestEnvironment.newEnvironment(settings)); return new MockWebServer(sslService.sslContext("xpack.security.http.ssl."), false); } @@ -88,6 +87,7 @@ private Settings.Builder getHttpSslSettings() { MockSecureSettings secureSettings = new MockSecureSettings(); secureSettings.setString("xpack.security.http.ssl.secure_key_passphrase", "testnode"); return Settings.builder() + .put("path.home", createTempDir()) .put("xpack.security.http.ssl.enabled", true) .put("xpack.security.http.ssl.key", keyPath.toString()) .put("xpack.security.http.ssl.certificate", certPath.toString()) diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordToolTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordToolTests.java index adb4fc58d3ed4..e80c4636e9766 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordToolTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordToolTests.java @@ -124,7 +124,7 @@ public void setSecretsAndKeyStore() throws Exception { @Override protected Command newCommand() { - return new SetupPasswordTool((e, s) -> httpClient, (e) -> keyStore) { + return new SetupPasswordTool(env -> httpClient, env -> keyStore) { @Override protected AutoSetup newAutoSetup() { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRealmTests.java index 4080b318a2eeb..fea74c5d660be 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRealmTests.java @@ -143,7 +143,7 @@ public void start() throws Exception { threadPool = new TestThreadPool("active directory realm tests"); resourceWatcherService = new ResourceWatcherService(Settings.EMPTY, threadPool); globalSettings = Settings.builder().put("path.home", createTempDir()).build(); - sslService = new SSLService(globalSettings, TestEnvironment.newEnvironment(globalSettings)); + sslService = new SSLService(TestEnvironment.newEnvironment(globalSettings)); licenseState = new TestUtils.UpdatableLicenseState(); } @@ -168,7 +168,7 @@ public boolean enableWarningsCheck() { private RealmConfig setupRealm(RealmConfig.RealmIdentifier realmIdentifier, Settings localSettings) { final Settings mergedSettings = Settings.builder().put(globalSettings).put(localSettings).build(); final Environment env = TestEnvironment.newEnvironment(mergedSettings); - this.sslService = new SSLService(mergedSettings, env); + this.sslService = new SSLService(env); return new RealmConfig( realmIdentifier, mergedSettings, diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapRealmTests.java index a56c5550c65c2..39268be35a8db 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapRealmTests.java @@ -99,7 +99,7 @@ public void init() throws Exception { threadPool = new TestThreadPool("ldap realm tests"); resourceWatcherService = new ResourceWatcherService(Settings.EMPTY, threadPool); defaultGlobalSettings = Settings.builder().put("path.home", createTempDir()).build(); - sslService = new SSLService(defaultGlobalSettings, TestEnvironment.newEnvironment(defaultGlobalSettings)); + sslService = new SSLService(TestEnvironment.newEnvironment(defaultGlobalSettings)); licenseState = mock(XPackLicenseState.class); when(licenseState.isAuthorizationRealmAllowed()).thenReturn(true); } @@ -305,6 +305,7 @@ public void testLdapRealmSelectsLdapSessionFactory() throws Exception { String userTemplate = VALID_USER_TEMPLATE; Settings settings = Settings.builder() .put(defaultGlobalSettings) + .putList(getFullSettingKey(identifier, URLS_SETTING), ldapUrls()) .putList(getFullSettingKey(identifier.getName(), LdapSessionFactorySettings.USER_DN_TEMPLATES_SETTING), userTemplate) .put(getFullSettingKey(identifier, SearchGroupsResolverSettings.BASE_DN), groupSearchBase) @@ -312,7 +313,8 @@ public void testLdapRealmSelectsLdapSessionFactory() throws Exception { .put(getFullSettingKey(identifier, SSLConfigurationSettings.VERIFICATION_MODE_SETTING_REALM), VerificationMode.CERTIFICATE) .build(); RealmConfig config = getRealmConfig(identifier, settings); - SessionFactory sessionFactory = LdapRealm.sessionFactory(config, new SSLService(settings, config.env()), threadPool); + final SSLService ssl = new SSLService(config.env()); + SessionFactory sessionFactory = LdapRealm.sessionFactory(config, ssl, threadPool); assertThat(sessionFactory, is(instanceOf(LdapSessionFactory.class))); } @@ -332,7 +334,7 @@ public void testLdapRealmSelectsLdapUserSearchSessionFactory() throws Exception .put(getFullSettingKey(identifier, SSLConfigurationSettings.VERIFICATION_MODE_SETTING_REALM), VerificationMode.CERTIFICATE) .build(); final RealmConfig config = getRealmConfig(identifier, settings); - SessionFactory sessionFactory = LdapRealm.sessionFactory(config, new SSLService(config.settings(), config.env()), threadPool); + SessionFactory sessionFactory = LdapRealm.sessionFactory(config, new SSLService(config.env()), threadPool); try { assertThat(sessionFactory, is(instanceOf(LdapUserSearchSessionFactory.class))); } finally { @@ -530,7 +532,7 @@ public void testUsageStats() throws Exception { RealmConfig config = getRealmConfig(identifier, settings.build()); - LdapSessionFactory ldapFactory = new LdapSessionFactory(config, new SSLService(config.settings(), config.env()), threadPool); + LdapSessionFactory ldapFactory = new LdapSessionFactory(config, new SSLService(config.env()), threadPool); LdapRealm realm = new LdapRealm(config, ldapFactory, new DnRoleMapper(config, resourceWatcherService), threadPool); realm.initialize(Collections.singleton(realm), licenseState); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapSessionFactoryTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapSessionFactoryTests.java index f7f38d41a2d66..3ba6d0da34824 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapSessionFactoryTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapSessionFactoryTests.java @@ -63,7 +63,7 @@ public void setup() throws Exception { .put("path.home", createTempDir()) .putList(RealmSettings.realmSslPrefix(REALM_IDENTIFIER) + "certificate_authorities", ldapCaPath.toString()) .build(); - sslService = new SSLService(globalSettings, TestEnvironment.newEnvironment(globalSettings)); + sslService = new SSLService(TestEnvironment.newEnvironment(globalSettings)); threadPool = new TestThreadPool("LdapSessionFactoryTests thread pool"); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapTestUtils.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapTestUtils.java index 65eb36aeba73b..f8d1281434567 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapTestUtils.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapTestUtils.java @@ -40,7 +40,7 @@ public static LDAPConnection openConnection(String url, String bindDN, String bi secureSettings.setString("xpack.security.authc.realms.ldap.bar.ssl.truststore.secure_password", "changeit"); Settings settings = builder.build(); Environment env = TestEnvironment.newEnvironment(settings); - SSLService sslService = new SSLService(settings, env); + SSLService sslService = new SSLService(env); LDAPURL ldapurl = new LDAPURL(url); LDAPConnectionOptions options = new LDAPConnectionOptions(); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapUserSearchSessionFactoryTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapUserSearchSessionFactoryTests.java index d6a370d9d3464..b59d95cb7a9da 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapUserSearchSessionFactoryTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapUserSearchSessionFactoryTests.java @@ -21,7 +21,6 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ThreadContext; -import org.elasticsearch.env.Environment; import org.elasticsearch.env.TestEnvironment; import org.elasticsearch.threadpool.TestThreadPool; import org.elasticsearch.threadpool.ThreadPool; @@ -56,7 +55,6 @@ public class LdapUserSearchSessionFactoryTests extends LdapTestCase { @Before public void init() throws Exception { Path certPath = getDataPath("support/smb_ca.crt"); - Environment env = TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build()); /* * Prior to each test we reinitialize the socket factory with a new SSLService so that we get a new SSLContext. * If we re-use an SSLContext, previously connected sessions can get re-established which breaks hostname @@ -68,7 +66,7 @@ public void init() throws Exception { .put("xpack.security.transport.ssl.enabled", false) .put("xpack.security.transport.ssl.certificate_authorities", certPath) .build(); - sslService = new SSLService(globalSettings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(globalSettings)); threadPool = new TestThreadPool("LdapUserSearchSessionFactoryTests"); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryLoadBalancingTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryLoadBalancingTests.java index 7c80de3ace4fe..f0ace87cd6990 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryLoadBalancingTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryLoadBalancingTests.java @@ -292,7 +292,7 @@ private TestSessionFactory createSessionFactory(LdapLoadBalancing loadBalancing) Settings globalSettings = Settings.builder().put("path.home", createTempDir()).put(settings).build(); RealmConfig config = new RealmConfig(REALM_IDENTIFIER, globalSettings, TestEnvironment.newEnvironment(globalSettings), new ThreadContext(Settings.EMPTY)); - return new TestSessionFactory(config, new SSLService(Settings.EMPTY, TestEnvironment.newEnvironment(config.settings())), + return new TestSessionFactory(config, new SSLService(TestEnvironment.newEnvironment(config.settings())), threadPool); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryTests.java index bb93e95950e86..313cd943f19a3 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/support/SessionFactoryTests.java @@ -52,7 +52,7 @@ public void testConnectionFactoryReturnsCorrectLDAPConnectionOptionsWithDefaultS final Environment environment = TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build()); RealmConfig realmConfig = new RealmConfig(new RealmConfig.RealmIdentifier("ldap", "conn_settings"), environment.settings(), environment, new ThreadContext(Settings.EMPTY)); - LDAPConnectionOptions options = SessionFactory.connectionOptions(realmConfig, new SSLService(environment.settings(), environment), + LDAPConnectionOptions options = SessionFactory.connectionOptions(realmConfig, new SSLService(environment), logger); assertThat(options.followReferrals(), is(equalTo(true))); assertThat(options.allowConcurrentSocketFactoryUse(), is(equalTo(true))); @@ -72,9 +72,9 @@ public void testConnectionFactoryReturnsCorrectLDAPConnectionOptions() throws Ex .put("path.home", pathHome) .build(); - final Environment environment = TestEnvironment.newEnvironment(settings); + Environment environment = TestEnvironment.newEnvironment(settings); RealmConfig realmConfig = new RealmConfig(realmId, settings, environment, new ThreadContext(settings)); - LDAPConnectionOptions options = SessionFactory.connectionOptions(realmConfig, new SSLService(settings, environment), logger); + LDAPConnectionOptions options = SessionFactory.connectionOptions(realmConfig, new SSLService(environment), logger); assertThat(options.followReferrals(), is(equalTo(false))); assertThat(options.allowConcurrentSocketFactoryUse(), is(equalTo(true))); assertThat(options.getConnectTimeoutMillis(), is(equalTo(10))); @@ -88,7 +88,7 @@ public void testConnectionFactoryReturnsCorrectLDAPConnectionOptions() throws Ex .put("path.home", pathHome) .build(); realmConfig = new RealmConfig(realmId, settings, environment, new ThreadContext(settings)); - options = SessionFactory.connectionOptions(realmConfig, new SSLService(settings, environment), logger); + options = SessionFactory.connectionOptions(realmConfig, new SSLService(TestEnvironment.newEnvironment(settings)), logger); assertThat(options.getSSLSocketVerifier(), is(instanceOf(TrustAllSSLSocketVerifier.class))); // Can't run in FIPS with verification_mode none, disable this check instead of duplicating the test case @@ -97,8 +97,9 @@ public void testConnectionFactoryReturnsCorrectLDAPConnectionOptions() throws Ex .put(getFullSettingKey(realmId, SSLConfigurationSettings.VERIFICATION_MODE_SETTING_REALM), VerificationMode.NONE) .put("path.home", pathHome) .build(); + environment = TestEnvironment.newEnvironment(settings); realmConfig = new RealmConfig(realmId, settings, environment, new ThreadContext(settings)); - options = SessionFactory.connectionOptions(realmConfig, new SSLService(settings, environment), logger); + options = SessionFactory.connectionOptions(realmConfig, new SSLService(environment), logger); assertThat(options.getSSLSocketVerifier(), is(instanceOf(TrustAllSSLSocketVerifier.class))); } @@ -106,8 +107,9 @@ public void testConnectionFactoryReturnsCorrectLDAPConnectionOptions() throws Ex .put(getFullSettingKey(realmId, SSLConfigurationSettings.VERIFICATION_MODE_SETTING_REALM), VerificationMode.FULL) .put("path.home", pathHome) .build(); + environment = TestEnvironment.newEnvironment(settings); realmConfig = new RealmConfig(realmId, settings, environment, new ThreadContext(settings)); - options = SessionFactory.connectionOptions(realmConfig, new SSLService(settings, environment), logger); + options = SessionFactory.connectionOptions(realmConfig, new SSLService(environment), logger); assertThat(options.getSSLSocketVerifier(), is(instanceOf(HostNameSSLSocketVerifier.class))); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java index ad4b9fcd2af81..bf0bdbee13e9c 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java @@ -86,14 +86,13 @@ public class OpenIdConnectAuthenticatorTests extends OpenIdConnectTestCase { private OpenIdConnectAuthenticator authenticator; - private Settings globalSettings; private Environment env; private ThreadContext threadContext; private int callsToReloadJwk; @Before public void setup() { - globalSettings = Settings.builder().put("path.home", createTempDir()) + final Settings globalSettings = Settings.builder().put("path.home", createTempDir()) .put("xpack.security.authc.realms.oidc.oidc-realm.ssl.verification_mode", "certificate").build(); env = TestEnvironment.newEnvironment(globalSettings); threadContext = new ThreadContext(globalSettings); @@ -109,7 +108,7 @@ public void cleanup() { private OpenIdConnectAuthenticator buildAuthenticator() throws URISyntaxException { final RealmConfig config = buildConfig(getBasicRealmSettings().build(), threadContext); - return new OpenIdConnectAuthenticator(config, getOpConfig(), getDefaultRpConfig(), new SSLService(globalSettings, env), null); + return new OpenIdConnectAuthenticator(config, getOpConfig(), getDefaultRpConfig(), new SSLService(env), null); } private OpenIdConnectAuthenticator buildAuthenticator(OpenIdConnectProviderConfiguration opConfig, RelyingPartyConfiguration rpConfig, @@ -117,7 +116,7 @@ private OpenIdConnectAuthenticator buildAuthenticator(OpenIdConnectProviderConfi final RealmConfig config = buildConfig(getBasicRealmSettings().build(), threadContext); final JWSVerificationKeySelector keySelector = new JWSVerificationKeySelector(rpConfig.getSignatureAlgorithm(), jwkSource); final IDTokenValidator validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), keySelector, null); - return new OpenIdConnectAuthenticator(config, opConfig, rpConfig, new SSLService(globalSettings, env), validator, + return new OpenIdConnectAuthenticator(config, opConfig, rpConfig, new SSLService(env), validator, null); } @@ -126,7 +125,7 @@ private OpenIdConnectAuthenticator buildAuthenticator(OpenIdConnectProviderConfi final RealmConfig config = buildConfig(getBasicRealmSettings().build(), threadContext); final IDTokenValidator validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), rpConfig.getSignatureAlgorithm(), new Secret(rpConfig.getClientSecret().toString())); - return new OpenIdConnectAuthenticator(config, opConfig, rpConfig, new SSLService(globalSettings, env), validator, + return new OpenIdConnectAuthenticator(config, opConfig, rpConfig, new SSLService(env), validator, null); } @@ -984,7 +983,7 @@ private Tuple getRandomJwkForType(String type) throws Exception { } else { throw new IllegalArgumentException("Invalid key type :" + type); } - return new Tuple(key, new JWKSet(jwk)); + return new Tuple<>(key, new JWKSet(jwk)); } private Curve curveFromHashSize(int size) { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlRealmTests.java index b4800c798a7f5..9b86075107876 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlRealmTests.java @@ -141,7 +141,7 @@ public void testReadIdpMetadataFromHttps() throws Exception { .put("path.home", createTempDir()) .setSecureSettings(mockSecureSettings) .build(); - TestsSSLService sslService = new TestsSSLService(settings, TestEnvironment.newEnvironment(settings)); + TestsSSLService sslService = new TestsSSLService(TestEnvironment.newEnvironment(settings)); try (MockWebServer proxyServer = new MockWebServer(sslService.sslContext("xpack.security.http.ssl"), false)) { proxyServer.start(); @@ -690,9 +690,8 @@ private EntityDescriptor mockIdp() { private Tuple buildConfig(String idpMetaDataPath) throws Exception { Settings globalSettings = buildSettings(idpMetaDataPath).build(); - final Environment env = TestEnvironment.newEnvironment(globalSettings); final RealmConfig config = realmConfigFromGlobalSettings(globalSettings); - final SSLService sslService = new SSLService(globalSettings, env); + final SSLService sslService = new SSLService(config.env()); return new Tuple<>(config, sslService); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/AbstractSimpleSecurityTransportTestCase.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/AbstractSimpleSecurityTransportTestCase.java index ffb470083e90e..1dd7981af5038 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/AbstractSimpleSecurityTransportTestCase.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/AbstractSimpleSecurityTransportTestCase.java @@ -90,7 +90,7 @@ protected SSLService createSSLService(Settings settings) { .setSecureSettings(secureSettings) .build(); try { - return new SSLService(settings1, TestEnvironment.newEnvironment(settings1)); + return new SSLService(TestEnvironment.newEnvironment(settings1)); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/netty4/SecurityNetty4HttpServerTransportTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/netty4/SecurityNetty4HttpServerTransportTests.java index 8efa61ebe40b6..e73a4ad715109 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/netty4/SecurityNetty4HttpServerTransportTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/netty4/SecurityNetty4HttpServerTransportTests.java @@ -55,14 +55,14 @@ public void createSSLService() { .setSecureSettings(secureSettings) .build(); env = TestEnvironment.newEnvironment(settings); - sslService = new SSLService(settings, env); + sslService = new SSLService(env); } public void testDefaultClientAuth() throws Exception { Settings settings = Settings.builder() .put(env.settings()) .put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true).build(); - sslService = new SSLService(settings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(settings)); SecurityNetty4HttpServerTransport transport = new SecurityNetty4HttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(IPFilter.class), sslService, mock(ThreadPool.class), xContentRegistry(), new NullDispatcher()); @@ -78,7 +78,7 @@ public void testOptionalClientAuth() throws Exception { .put(env.settings()) .put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true) .put("xpack.security.http.ssl.client_authentication", value).build(); - sslService = new SSLService(settings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(settings)); SecurityNetty4HttpServerTransport transport = new SecurityNetty4HttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(IPFilter.class), sslService, mock(ThreadPool.class), xContentRegistry(), new NullDispatcher()); @@ -94,7 +94,7 @@ public void testRequiredClientAuth() throws Exception { .put(env.settings()) .put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true) .put("xpack.security.http.ssl.client_authentication", value).build(); - sslService = new SSLService(settings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(settings)); SecurityNetty4HttpServerTransport transport = new SecurityNetty4HttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(IPFilter.class), sslService, mock(ThreadPool.class), xContentRegistry(), new NullDispatcher()); @@ -110,7 +110,7 @@ public void testNoClientAuth() throws Exception { .put(env.settings()) .put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true) .put("xpack.security.http.ssl.client_authentication", value).build(); - sslService = new SSLService(settings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(settings)); SecurityNetty4HttpServerTransport transport = new SecurityNetty4HttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(IPFilter.class), sslService, mock(ThreadPool.class), xContentRegistry(), new NullDispatcher()); @@ -124,7 +124,7 @@ public void testCustomSSLConfiguration() throws Exception { Settings settings = Settings.builder() .put(env.settings()) .put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true).build(); - sslService = new SSLService(settings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(settings)); SecurityNetty4HttpServerTransport transport = new SecurityNetty4HttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(IPFilter.class), sslService, mock(ThreadPool.class), xContentRegistry(), new NullDispatcher()); @@ -137,7 +137,7 @@ public void testCustomSSLConfiguration() throws Exception { .put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true) .put("xpack.security.http.ssl.supported_protocols", "TLSv1.2") .build(); - sslService = new SSLService(settings, TestEnvironment.newEnvironment(settings)); + sslService = new SSLService(TestEnvironment.newEnvironment(settings)); transport = new SecurityNetty4HttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(IPFilter.class), sslService, mock(ThreadPool.class), xContentRegistry(), new NullDispatcher()); handler = transport.configureServerChannelHandler(); @@ -158,7 +158,7 @@ public void testNoExceptionWhenConfiguredWithoutSslKeySSLDisabled() throws Excep .put("path.home", createTempDir()) .build(); env = TestEnvironment.newEnvironment(settings); - sslService = new SSLService(settings, env); + sslService = new SSLService(env); SecurityNetty4HttpServerTransport transport = new SecurityNetty4HttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(IPFilter.class), sslService, mock(ThreadPool.class), xContentRegistry(), new NullDispatcher()); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/nio/SecurityNioHttpServerTransportTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/nio/SecurityNioHttpServerTransportTests.java index 14addd0620b43..f1474ccc77145 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/nio/SecurityNioHttpServerTransportTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/nio/SecurityNioHttpServerTransportTests.java @@ -63,7 +63,7 @@ public void createSSLService() { .setSecureSettings(secureSettings) .build(); env = TestEnvironment.newEnvironment(settings); - sslService = new SSLService(settings, env); + sslService = new SSLService(env); } public void testDefaultClientAuth() throws IOException { @@ -71,7 +71,7 @@ public void testDefaultClientAuth() throws IOException { .put(env.settings()) .put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true).build(); nioGroupFactory = new NioGroupFactory(settings, logger); - sslService = new SSLService(settings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(settings)); SecurityNioHttpServerTransport transport = new SecurityNioHttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(PageCacheRecycler.class), mock(ThreadPool.class), xContentRegistry(), new NullDispatcher(), mock(IPFilter.class), sslService, nioGroupFactory); @@ -91,7 +91,7 @@ public void testOptionalClientAuth() throws IOException { .put(env.settings()) .put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true) .put("xpack.security.http.ssl.client_authentication", value).build(); - sslService = new SSLService(settings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(settings)); nioGroupFactory = new NioGroupFactory(settings, logger); SecurityNioHttpServerTransport transport = new SecurityNioHttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(PageCacheRecycler.class), mock(ThreadPool.class), @@ -113,7 +113,7 @@ public void testRequiredClientAuth() throws IOException { .put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true) .put("xpack.security.http.ssl.client_authentication", value).build(); nioGroupFactory = new NioGroupFactory(settings, logger); - sslService = new SSLService(settings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(settings)); SecurityNioHttpServerTransport transport = new SecurityNioHttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(PageCacheRecycler.class), mock(ThreadPool.class), xContentRegistry(), new NullDispatcher(), mock(IPFilter.class), sslService, nioGroupFactory); @@ -133,7 +133,7 @@ public void testNoClientAuth() throws IOException { .put(env.settings()) .put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true) .put("xpack.security.http.ssl.client_authentication", value).build(); - sslService = new SSLService(settings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(settings)); nioGroupFactory = new NioGroupFactory(settings, logger); SecurityNioHttpServerTransport transport = new SecurityNioHttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(PageCacheRecycler.class), mock(ThreadPool.class), @@ -152,7 +152,7 @@ public void testCustomSSLConfiguration() throws IOException { Settings settings = Settings.builder() .put(env.settings()) .put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true).build(); - sslService = new SSLService(settings, env); + sslService = new SSLService(TestEnvironment.newEnvironment(settings)); nioGroupFactory = new NioGroupFactory(settings, logger); SecurityNioHttpServerTransport transport = new SecurityNioHttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(PageCacheRecycler.class), mock(ThreadPool.class), @@ -168,7 +168,7 @@ public void testCustomSSLConfiguration() throws IOException { .put(XPackSettings.HTTP_SSL_ENABLED.getKey(), true) .put("xpack.security.http.ssl.supported_protocols", "TLSv1.2") .build(); - sslService = new SSLService(settings, TestEnvironment.newEnvironment(settings)); + sslService = new SSLService(TestEnvironment.newEnvironment(settings)); nioGroupFactory = new NioGroupFactory(settings, logger); transport = new SecurityNioHttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(PageCacheRecycler.class), mock(ThreadPool.class), @@ -191,7 +191,7 @@ public void testNoExceptionWhenConfiguredWithoutSslKeySSLDisabled() { .put("path.home", createTempDir()) .build(); env = TestEnvironment.newEnvironment(settings); - sslService = new SSLService(settings, env); + sslService = new SSLService(env); nioGroupFactory = new NioGroupFactory(settings, logger); SecurityNioHttpServerTransport transport = new SecurityNioHttpServerTransport(settings, new NetworkService(Collections.emptyList()), mock(BigArrays.class), mock(PageCacheRecycler.class), mock(ThreadPool.class), diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/ssl/SslIntegrationTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/ssl/SslIntegrationTests.java index 741b70c2258c3..7d24b273de209 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/ssl/SslIntegrationTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/ssl/SslIntegrationTests.java @@ -19,6 +19,7 @@ import org.elasticsearch.common.network.NetworkAddress; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; +import org.elasticsearch.env.TestEnvironment; import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.xpack.core.common.socket.SocketAccess; @@ -68,7 +69,7 @@ public void testThatConnectionToHTTPWorks() throws Exception { "/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testclient.crt", "xpack.security.http.", Arrays.asList("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.crt")); - SSLService service = new SSLService(builder.build(), newEnvironment()); + SSLService service = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(builder.build()))); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(nodeClientUsername(), diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLErrorMessageCertificateVerificationTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLErrorMessageCertificateVerificationTests.java index 691b6501273a5..2c21b3984309a 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLErrorMessageCertificateVerificationTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLErrorMessageCertificateVerificationTests.java @@ -21,6 +21,7 @@ import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.ssl.DiagnosticTrustManager; +import org.elasticsearch.env.TestEnvironment; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.MockLogAppender; import org.elasticsearch.test.http.MockResponse; @@ -58,7 +59,7 @@ public void testMessageForHttpClientHostnameVerificationFailure() throws IOExcep SSLClientAuth.NONE, VerificationMode.FULL, null) .putList("xpack.http.ssl.certificate_authorities", getPath("ca1.crt")) .build(); - final SSLService sslService = new SSLService(sslSetup, newEnvironment()); + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(sslSetup))); try (MockWebServer webServer = initWebServer(sslService); CloseableHttpClient client = buildHttpClient(sslService)) { final HttpGet request = new HttpGet(webServer.getUri("/")); @@ -79,7 +80,7 @@ public void testMessageForRestClientHostnameVerificationFailure() throws IOExcep // Client .putList("xpack.http.ssl.certificate_authorities", getPath("ca1.crt")) .build(); - final SSLService sslService = new SSLService(sslSetup, newEnvironment()); + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(sslSetup))); try (MockWebServer webServer = initWebServer(sslService)) { try (RestClient restClient = buildRestClient(sslService, webServer)) { restClient.performRequest(new Request("GET", "/")); @@ -98,7 +99,7 @@ public void testDiagnosticTrustManagerForHostnameVerificationFailure() throws Ex SSLClientAuth.NONE, VerificationMode.FULL, null) .putList("xpack.http.ssl.certificate_authorities", getPath("ca1.crt")) .build(); - final SSLService sslService = new SSLService(settings, newEnvironment()); + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings))); final SSLConfiguration clientSslConfig = sslService.getSSLConfiguration(HTTP_CLIENT_SSL); final SSLSocketFactory clientSocketFactory = sslService.sslSocketFactory(clientSslConfig); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLErrorMessageFileTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLErrorMessageFileTests.java index de12f2c3cf331..5efce0a8ab0fa 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLErrorMessageFileTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLErrorMessageFileTests.java @@ -346,10 +346,12 @@ private Settings.Builder configureWorkingKeystore(String prefix, Settings.Builde } private ElasticsearchException expectFailure(Settings.Builder settings) { - return expectThrows(ElasticsearchException.class, () -> new SSLService(settings.build(), env)); + return expectThrows(ElasticsearchException.class, + () -> new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings.build())))); } + private SSLService expectSuccess(Settings.Builder settings) { - return new SSLService(settings.build(), env); + return new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(settings.build()))); } private String resource(String fileName) { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLReloadIntegTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLReloadIntegTests.java index 6354ddb5046c3..6f51f453f9178 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLReloadIntegTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLReloadIntegTests.java @@ -108,7 +108,7 @@ public void testThatSSLConfigurationReloadsOnModification() throws Exception { .setSecureSettings(secureSettings) .build(); String node = randomFrom(internalCluster().getNodeNames()); - SSLService sslService = new SSLService(settings, TestEnvironment.newEnvironment(settings)); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(settings)); SSLConfiguration sslConfiguration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); SSLSocketFactory sslSocketFactory = sslService.sslSocketFactory(sslConfiguration); TransportAddress address = internalCluster() diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLTrustRestrictionsTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLTrustRestrictionsTests.java index 2f097480f928d..e23ed8dcb20a3 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLTrustRestrictionsTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/ssl/SSLTrustRestrictionsTests.java @@ -221,7 +221,7 @@ private void tryConnect(CertificateInfo certificate, boolean shouldFail) throws .build(); String node = randomFrom(internalCluster().getNodeNames()); - SSLService sslService = new SSLService(settings, TestEnvironment.newEnvironment(settings)); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(settings)); SSLConfiguration sslConfiguration = sslService.getSSLConfiguration("xpack.security.transport.ssl"); SSLSocketFactory sslSocketFactory = sslService.sslSocketFactory(sslConfiguration); TransportAddress address = internalCluster().getInstance(Transport.class, node).boundAddress().publishAddress(); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/email/EmailSslTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/email/EmailSslTests.java index 70d7f2f6dd5ee..91bf327a37e18 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/email/EmailSslTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/email/EmailSslTests.java @@ -138,7 +138,7 @@ private ExecutableEmailAction buildEmailAction(Settings.Builder baseSettings, Mo Set> registeredSettings = new HashSet<>(ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); registeredSettings.addAll(EmailService.getSettings()); ClusterSettings clusterSettings = new ClusterSettings(settings, registeredSettings); - SSLService sslService = new SSLService(settings, TestEnvironment.newEnvironment(settings)); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(settings)); final EmailService emailService = new EmailService(settings, null, sslService, clusterSettings); EmailTemplate emailTemplate = EmailTemplate.builder().from("from@example.org").to("to@example.org") .subject("subject").textBody("body").build(); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/webhook/WebhookActionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/webhook/WebhookActionTests.java index 439eb45f0159f..7cb87c62a2a3a 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/webhook/WebhookActionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/webhook/WebhookActionTests.java @@ -215,7 +215,7 @@ private WebhookActionFactory webhookFactory(HttpClient client) { public void testThatSelectingProxyWorks() throws Exception { Environment environment = TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build()); - try (HttpClient httpClient = new HttpClient(Settings.EMPTY, new SSLService(environment.settings(), environment), null, + try (HttpClient httpClient = new HttpClient(Settings.EMPTY, new SSLService(environment), null, mockClusterService()); MockWebServer proxyServer = new MockWebServer()) { proxyServer.start(); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/webhook/WebhookHttpsIntegrationTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/webhook/WebhookHttpsIntegrationTests.java index c03d924cd6faa..1deced67b3d23 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/webhook/WebhookHttpsIntegrationTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/actions/webhook/WebhookHttpsIntegrationTests.java @@ -64,8 +64,8 @@ protected Settings nodeSettings(int nodeOrdinal) { @Before public void startWebservice() throws Exception { - Settings settings = getInstanceFromMaster(Settings.class); - TestsSSLService sslService = new TestsSSLService(settings, getInstanceFromMaster(Environment.class)); + final Environment environment = getInstanceFromMaster(Environment.class); + final TestsSSLService sslService = new TestsSSLService(environment); webServer = new MockWebServer(sslService.sslContext("xpack.http.ssl"), false); webServer.start(); } diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/common/http/HttpClientTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/common/http/HttpClientTests.java index e83f9154c5459..f820b530de26d 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/common/http/HttpClientTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/common/http/HttpClientTests.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.xpack.watcher.common.http; -import com.carrotsearch.randomizedtesting.generators.RandomStrings; import com.sun.net.httpserver.HttpsServer; import org.apache.http.HttpHeaders; import org.apache.http.HttpHost; @@ -86,7 +85,7 @@ public void init() throws Exception { ClusterService clusterService = mock(ClusterService.class); ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, new HashSet<>(HttpSettings.getSettings())); when(clusterService.getClusterSettings()).thenReturn(clusterSettings); - httpClient = new HttpClient(Settings.EMPTY, new SSLService(environment.settings(), environment), null, clusterService); + httpClient = new HttpClient(Settings.EMPTY, new SSLService(environment), null, clusterService); } @After @@ -189,14 +188,17 @@ public void testHttps() throws Exception { Path keyPath = getDataPath("/org/elasticsearch/xpack/security/keystore/testnode.pem"); MockSecureSettings secureSettings = new MockSecureSettings(); Settings settings = Settings.builder() + .put(environment.settings()) .put("xpack.http.ssl.certificate_authorities", trustedCertPath) .setSecureSettings(secureSettings) .build(); - try (HttpClient client = new HttpClient(settings, new SSLService(settings, environment), null, mockClusterService())) { + final SSLService ssl = new SSLService(TestEnvironment.newEnvironment(settings)); + try (HttpClient client = new HttpClient(settings, ssl, null, mockClusterService())) { secureSettings = new MockSecureSettings(); // We can't use the client created above for the server since it is only a truststore secureSettings.setString("xpack.security.http.ssl.secure_key_passphrase", "testnode"); Settings settings2 = Settings.builder() + .put(environment.settings()) .put("xpack.security.http.ssl.enabled", true) .put("xpack.security.http.ssl.key", keyPath) .put("xpack.security.http.ssl.certificate", certPath) @@ -204,7 +206,7 @@ public void testHttps() throws Exception { .setSecureSettings(secureSettings) .build(); - TestsSSLService sslService = new TestsSSLService(settings2, environment); + TestsSSLService sslService = new TestsSSLService(TestEnvironment.newEnvironment(settings2)); testSslMockWebserver(client, sslService.sslContext("xpack.security.http.ssl"), false); } } @@ -212,8 +214,8 @@ public void testHttps() throws Exception { public void testHttpsDisableHostnameVerification() throws Exception { Path certPath = getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode-no-subjaltname.crt"); Path keyPath = getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode-no-subjaltname.pem"); - Settings settings; Settings.Builder builder = Settings.builder() + .put(environment.settings()) .put("xpack.http.ssl.certificate_authorities", certPath); if (inFipsJvm()) { //Can't use TrustAllConfig in FIPS mode @@ -221,12 +223,14 @@ public void testHttpsDisableHostnameVerification() throws Exception { } else { builder.put("xpack.http.ssl.verification_mode", randomFrom(VerificationMode.NONE, VerificationMode.CERTIFICATE)); } - settings = builder.build(); - try (HttpClient client = new HttpClient(settings, new SSLService(settings, environment), null, mockClusterService())) { + final Settings settings = builder.build(); + final SSLService ssl = new SSLService(TestEnvironment.newEnvironment(settings)); + try (HttpClient client = new HttpClient(settings, ssl, null, mockClusterService())) { MockSecureSettings secureSettings = new MockSecureSettings(); // We can't use the client created above for the server since it only defines a truststore secureSettings.setString("xpack.security.http.ssl.secure_key_passphrase", "testnode-no-subjaltname"); Settings settings2 = Settings.builder() + .put(environment.settings()) .put("xpack.security.http.ssl.enabled", true) .put("xpack.security.http.ssl.key", keyPath) .put("xpack.security.http.ssl.certificate", certPath) @@ -234,8 +238,8 @@ public void testHttpsDisableHostnameVerification() throws Exception { .setSecureSettings(secureSettings) .build(); - TestsSSLService sslService = new TestsSSLService(settings2, environment); - testSslMockWebserver(client, sslService.sslContext("xpack.security.http.ssl"), false); + TestsSSLService ssl2 = new TestsSSLService(TestEnvironment.newEnvironment(settings2)); + testSslMockWebserver(client, ssl2.sslContext("xpack.security.http.ssl"), false); } } @@ -245,13 +249,14 @@ public void testHttpsClientAuth() throws Exception { MockSecureSettings secureSettings = new MockSecureSettings(); secureSettings.setString("xpack.http.ssl.secure_key_passphrase", "testnode"); Settings settings = Settings.builder() + .put(environment.settings()) .put("xpack.http.ssl.key", keyPath) .put("xpack.http.ssl.certificate", certPath) .putList("xpack.http.ssl.supported_protocols", getProtocols()) .setSecureSettings(secureSettings) .build(); - TestsSSLService sslService = new TestsSSLService(settings, environment); + TestsSSLService sslService = new TestsSSLService(TestEnvironment.newEnvironment(settings)); try (HttpClient client = new HttpClient(settings, sslService, null, mockClusterService())) { testSslMockWebserver(client, sslService.sslContext("xpack.http.ssl"), true); } @@ -275,9 +280,9 @@ private void testSslMockWebserver(HttpClient client, SSLContext sslContext, bool } public void testHttpResponseWithAnyStatusCodeCanReturnBody() throws Exception { - int statusCode = randomFrom(200, 201, 400, 401, 403, 404, 405, 409, 413, 429, 500, 503); - String body = RandomStrings.randomAsciiOfLength(random(), 100); - boolean hasBody = usually(); + final int statusCode = randomFrom(200, 201, 400, 401, 403, 404, 405, 409, 413, 429, 500, 503); + final String body = randomAlphaOfLength(100); + final boolean hasBody = usually(); MockResponse mockResponse = new MockResponse().setResponseCode(statusCode); if (hasBody) { mockResponse.setBody(body); @@ -300,7 +305,7 @@ public void testHttpResponseWithAnyStatusCodeCanReturnBody() throws Exception { @Network public void testHttpsWithoutTruststore() throws Exception { - try (HttpClient client = new HttpClient(Settings.EMPTY, new SSLService(Settings.EMPTY, environment), null, mockClusterService())) { + try (HttpClient client = new HttpClient(Settings.EMPTY, new SSLService(environment), null, mockClusterService())) { // Known server with a valid cert from a commercial CA HttpRequest.Builder request = HttpRequest.builder("www.elastic.co", 443).scheme(Scheme.HTTPS); HttpResponse response = client.execute(request.build()); @@ -316,6 +321,7 @@ public void testThatProxyCanBeConfigured() throws Exception { proxyServer.enqueue(new MockResponse().setResponseCode(200).setBody("fullProxiedContent")); proxyServer.start(); Settings settings = Settings.builder() + .put(environment.settings()) .put(HttpSettings.PROXY_HOST.getKey(), "localhost") .put(HttpSettings.PROXY_PORT.getKey(), proxyServer.getPort()) .build(); @@ -324,7 +330,8 @@ public void testThatProxyCanBeConfigured() throws Exception { .method(HttpMethod.GET) .path("/"); - try (HttpClient client = new HttpClient(settings, new SSLService(settings, environment), null, mockClusterService())) { + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(settings)); + try (HttpClient client = new HttpClient(settings, sslService, null, mockClusterService())) { HttpResponse response = client.execute(requestBuilder.build()); assertThat(response.status(), equalTo(200)); assertThat(response.body().utf8ToString(), equalTo("fullProxiedContent")); @@ -382,19 +389,21 @@ public void testProxyCanHaveDifferentSchemeThanRequest() throws Exception { // We can't use the client created above for the server since it is only a truststore serverSecureSettings.setString("xpack.http.ssl.secure_key_passphrase", "testnode"); Settings serverSettings = Settings.builder() + .put(environment.settings()) .put("xpack.http.ssl.key", keyPath) .put("xpack.http.ssl.certificate", certPath) .put("xpack.security.http.ssl.enabled", false) .putList("xpack.security.http.ssl.supported_protocols", getProtocols()) .setSecureSettings(serverSecureSettings) .build(); - TestsSSLService sslService = new TestsSSLService(serverSettings, environment); + TestsSSLService sslService = new TestsSSLService(TestEnvironment.newEnvironment(serverSettings)); try (MockWebServer proxyServer = new MockWebServer(sslService.sslContext(serverSettings.getByPrefix("xpack.http.ssl.")), false)) { proxyServer.enqueue(new MockResponse().setResponseCode(200).setBody("fullProxiedContent")); proxyServer.start(); Settings settings = Settings.builder() + .put(environment.settings()) .put(HttpSettings.PROXY_HOST.getKey(), "localhost") .put(HttpSettings.PROXY_PORT.getKey(), proxyServer.getPort()) .put(HttpSettings.PROXY_SCHEME.getKey(), "https") @@ -408,7 +417,8 @@ public void testProxyCanHaveDifferentSchemeThanRequest() throws Exception { .scheme(Scheme.HTTP) .path("/"); - try (HttpClient client = new HttpClient(settings, new SSLService(settings, environment), null, mockClusterService())) { + final SSLService ssl = new SSLService(TestEnvironment.newEnvironment(settings)); + try (HttpClient client = new HttpClient(settings, ssl, null, mockClusterService())) { HttpResponse response = client.execute(requestBuilder.build()); assertThat(response.status(), equalTo(200)); assertThat(response.body().utf8ToString(), equalTo("fullProxiedContent")); @@ -426,6 +436,7 @@ public void testThatProxyCanBeOverriddenByRequest() throws Exception { proxyServer.enqueue(new MockResponse().setResponseCode(200).setBody("fullProxiedContent")); proxyServer.start(); Settings settings = Settings.builder() + .put(environment.settings()) .put(HttpSettings.PROXY_HOST.getKey(), "localhost") .put(HttpSettings.PROXY_PORT.getKey(), proxyServer.getPort() + 1) .put(HttpSettings.PROXY_HOST.getKey(), "https") @@ -436,7 +447,8 @@ public void testThatProxyCanBeOverriddenByRequest() throws Exception { .proxy(new HttpProxy("localhost", proxyServer.getPort(), Scheme.HTTP)) .path("/"); - try (HttpClient client = new HttpClient(settings, new SSLService(settings, environment), null, mockClusterService())) { + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(settings)); + try (HttpClient client = new HttpClient(settings, sslService, null, mockClusterService())) { HttpResponse response = client.execute(requestBuilder.build()); assertThat(response.status(), equalTo(200)); assertThat(response.body().utf8ToString(), equalTo("fullProxiedContent")); @@ -449,15 +461,17 @@ public void testThatProxyCanBeOverriddenByRequest() throws Exception { } public void testThatProxyConfigurationRequiresHostAndPort() { - Settings.Builder settings = Settings.builder(); + Settings.Builder settings = Settings.builder().put(environment.settings()); if (randomBoolean()) { settings.put(HttpSettings.PROXY_HOST.getKey(), "localhost"); } else { settings.put(HttpSettings.PROXY_PORT.getKey(), 8080); } + final SSLService sslService = new SSLService(TestEnvironment.newEnvironment(settings.build())); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, - () -> new HttpClient(settings.build(), new SSLService(settings.build(), environment), null, mockClusterService())); + () -> new HttpClient(settings.build(), sslService, null, + mockClusterService())); assertThat(e.getMessage(), containsString("HTTP proxy requires both settings: [xpack.http.proxy.host] and [xpack.http.proxy.port]")); } @@ -515,7 +529,7 @@ public void testThatClientTakesTimeoutsIntoAccountAfterHeadersAreSent() throws E public void testThatHttpClientFailsOnNonHttpResponse() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); - AtomicReference hasExceptionHappened = new AtomicReference(); + AtomicReference hasExceptionHappened = new AtomicReference<>(); try (ServerSocket serverSocket = new MockServerSocket(0, 50, InetAddress.getByName("localhost"))) { executor.execute(() -> { try (Socket socket = serverSocket.accept()) { @@ -556,7 +570,7 @@ public void testMaxHttpResponseSize() throws Exception { HttpRequest.Builder requestBuilder = HttpRequest.builder("localhost", webServer.getPort()).method(HttpMethod.GET).path("/"); - try (HttpClient client = new HttpClient(settings, new SSLService(environment.settings(), environment), null, + try (HttpClient client = new HttpClient(settings, new SSLService(environment), null, mockClusterService())) { IOException e = expectThrows(IOException.class, () -> client.execute(requestBuilder.build())); assertThat(e.getMessage(), startsWith("Maximum limit of")); @@ -631,7 +645,7 @@ public void testThatWhiteListingWorks() throws Exception { webServer.enqueue(new MockResponse().setResponseCode(200).setBody("whatever")); Settings settings = Settings.builder().put(HttpSettings.HOSTS_WHITELIST.getKey(), getWebserverUri()).build(); - try (HttpClient client = new HttpClient(settings, new SSLService(environment.settings(), environment), null, + try (HttpClient client = new HttpClient(settings, new SSLService(environment), null, mockClusterService())) { HttpRequest request = HttpRequest.builder(webServer.getHostName(), webServer.getPort()).path("foo").build(); client.execute(request); @@ -643,7 +657,7 @@ public void testThatWhiteListBlocksRequests() throws Exception { .put(HttpSettings.HOSTS_WHITELIST.getKey(), getWebserverUri()) .build(); - try (HttpClient client = new HttpClient(settings, new SSLService(environment.settings(), environment), null, + try (HttpClient client = new HttpClient(settings, new SSLService(environment), null, mockClusterService())) { HttpRequest request = HttpRequest.builder("blocked.domain.org", webServer.getPort()) .path("foo") @@ -667,7 +681,7 @@ public void testThatWhiteListBlocksRedirects() throws Exception { Settings settings = Settings.builder().put(HttpSettings.HOSTS_WHITELIST.getKey(), getWebserverUri()).build(); - try (HttpClient client = new HttpClient(settings, new SSLService(environment.settings(), environment), null, + try (HttpClient client = new HttpClient(settings, new SSLService(environment), null, mockClusterService())) { HttpRequest request = HttpRequest.builder(webServer.getHostName(), webServer.getPort()).path("/") .method(method) @@ -688,7 +702,7 @@ public void testThatWhiteListingWorksForRedirects() throws Exception { Settings settings = Settings.builder().put(HttpSettings.HOSTS_WHITELIST.getKey(), getWebserverUri() + "*").build(); - try (HttpClient client = new HttpClient(settings, new SSLService(environment.settings(), environment), null, + try (HttpClient client = new HttpClient(settings, new SSLService(environment), null, mockClusterService())) { HttpRequest request = HttpRequest.builder(webServer.getHostName(), webServer.getPort()).path("/") .method(HttpMethod.GET) @@ -708,7 +722,7 @@ public void testThatWhiteListReloadingWorks() throws Exception { when(clusterService.getClusterSettings()).thenReturn(clusterSettings); try (HttpClient client = - new HttpClient(settings, new SSLService(environment.settings(), environment), null, clusterService)) { + new HttpClient(settings, new SSLService(environment), null, clusterService)) { // blacklisted HttpRequest request = HttpRequest.builder(webServer.getHostName(), webServer.getPort()).path("/") diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/common/http/HttpConnectionTimeoutTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/common/http/HttpConnectionTimeoutTests.java index 3451c771e3e60..94f5115d673fd 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/common/http/HttpConnectionTimeoutTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/common/http/HttpConnectionTimeoutTests.java @@ -25,7 +25,7 @@ public class HttpConnectionTimeoutTests extends ESTestCase { @Network public void testDefaultTimeout() throws Exception { Environment environment = TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build()); - HttpClient httpClient = new HttpClient(Settings.EMPTY, new SSLService(environment.settings(), environment), null, + HttpClient httpClient = new HttpClient(Settings.EMPTY, new SSLService(environment), null, mockClusterService()); HttpRequest request = HttpRequest.builder(UNROUTABLE_IP, 12345) @@ -51,7 +51,7 @@ public void testDefaultTimeout() throws Exception { public void testDefaultTimeoutCustom() throws Exception { Environment environment = TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build()); HttpClient httpClient = new HttpClient(Settings.builder() - .put("xpack.http.default_connection_timeout", "5s").build(), new SSLService(environment.settings(), environment), null, + .put("xpack.http.default_connection_timeout", "5s").build(), new SSLService(environment), null, mockClusterService()); HttpRequest request = HttpRequest.builder(UNROUTABLE_IP, 12345) @@ -77,7 +77,7 @@ public void testDefaultTimeoutCustom() throws Exception { public void testTimeoutCustomPerRequest() throws Exception { Environment environment = TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build()); HttpClient httpClient = new HttpClient(Settings.builder() - .put("xpack.http.default_connection_timeout", "10s").build(), new SSLService(environment.settings(), environment), null, + .put("xpack.http.default_connection_timeout", "10s").build(), new SSLService(environment), null, mockClusterService()); HttpRequest request = HttpRequest.builder(UNROUTABLE_IP, 12345) diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/common/http/HttpReadTimeoutTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/common/http/HttpReadTimeoutTests.java index e534a2a90757e..918bc33d61cf4 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/common/http/HttpReadTimeoutTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/common/http/HttpReadTimeoutTests.java @@ -44,7 +44,7 @@ public void testDefaultTimeout() throws Exception { .path("/") .build(); - try (HttpClient httpClient = new HttpClient(Settings.EMPTY, new SSLService(environment.settings(), environment), + try (HttpClient httpClient = new HttpClient(Settings.EMPTY, new SSLService(environment), null, mockClusterService())) { long start = System.nanoTime(); @@ -67,7 +67,7 @@ public void testDefaultTimeoutCustom() throws Exception { .build(); try (HttpClient httpClient = new HttpClient(Settings.builder() - .put("xpack.http.default_read_timeout", "3s").build(), new SSLService(environment.settings(), environment), + .put("xpack.http.default_read_timeout", "3s").build(), new SSLService(environment), null, mockClusterService())) { long start = System.nanoTime(); @@ -91,7 +91,7 @@ public void testTimeoutCustomPerRequest() throws Exception { .build(); try (HttpClient httpClient = new HttpClient(Settings.builder() - .put("xpack.http.default_read_timeout", "10s").build(), new SSLService(environment.settings(), environment), + .put("xpack.http.default_read_timeout", "10s").build(), new SSLService(environment), null, mockClusterService())) { long start = System.nanoTime(); diff --git a/x-pack/qa/openldap-tests/src/test/java/org/elasticsearch/test/OpenLdapTests.java b/x-pack/qa/openldap-tests/src/test/java/org/elasticsearch/test/OpenLdapTests.java index b763e3e985fb5..2e9ecdfbc67f4 100644 --- a/x-pack/qa/openldap-tests/src/test/java/org/elasticsearch/test/OpenLdapTests.java +++ b/x-pack/qa/openldap-tests/src/test/java/org/elasticsearch/test/OpenLdapTests.java @@ -102,7 +102,7 @@ public void initializeSslSocketFactory() throws Exception { builder.put("xpack.security.authc.realms.ldap.vmode_full.ssl.verification_mode", VerificationMode.FULL); globalSettings = builder.setSecureSettings(mockSecureSettings).build(); Environment environment = TestEnvironment.newEnvironment(globalSettings); - sslService = new SSLService(globalSettings, environment); + sslService = new SSLService(environment); } public void testConnect() throws Exception { diff --git a/x-pack/qa/openldap-tests/src/test/java/org/elasticsearch/xpack/security/authc/ldap/OpenLdapUserSearchSessionFactoryTests.java b/x-pack/qa/openldap-tests/src/test/java/org/elasticsearch/xpack/security/authc/ldap/OpenLdapUserSearchSessionFactoryTests.java index de1183db19391..74396e3ff9837 100644 --- a/x-pack/qa/openldap-tests/src/test/java/org/elasticsearch/xpack/security/authc/ldap/OpenLdapUserSearchSessionFactoryTests.java +++ b/x-pack/qa/openldap-tests/src/test/java/org/elasticsearch/xpack/security/authc/ldap/OpenLdapUserSearchSessionFactoryTests.java @@ -94,7 +94,7 @@ public void testUserSearchWithBindUserOpenLDAP() throws Exception { RealmConfig config = new RealmConfig(realmId, settings, TestEnvironment.newEnvironment(globalSettings), new ThreadContext(globalSettings)); - SSLService sslService = new SSLService(settings, TestEnvironment.newEnvironment(settings)); + SSLService sslService = new SSLService(TestEnvironment.newEnvironment(settings)); String[] users = new String[]{"cap", "hawkeye", "hulk", "ironman", "thor"}; try (LdapUserSearchSessionFactory sessionFactory = new LdapUserSearchSessionFactory(config, sslService, threadPool)) { diff --git a/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ADLdapUserSearchSessionFactoryTests.java b/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ADLdapUserSearchSessionFactoryTests.java index d2c79d8882f46..54e6cd1e0ed0b 100644 --- a/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ADLdapUserSearchSessionFactoryTests.java +++ b/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ADLdapUserSearchSessionFactoryTests.java @@ -37,7 +37,6 @@ public class ADLdapUserSearchSessionFactoryTests extends AbstractActiveDirectory @Before public void init() throws Exception { Path certPath = getDataPath("support/smb_ca.crt"); - Environment env = TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build()); /* * Prior to each test we reinitialize the socket factory with a new SSLService so that we get a new SSLContext. * If we re-use an SSLContext, previously connected sessions can get re-established which breaks hostname @@ -48,7 +47,8 @@ public void init() throws Exception { .put("path.home", createTempDir()) .put("xpack.security.authc.realms.ldap.ad-as-ldap-test.ssl.certificate_authorities", certPath) .build(); - sslService = new SSLService(globalSettings, env); + Environment env = TestEnvironment.newEnvironment(globalSettings); + sslService = new SSLService(env); threadPool = new TestThreadPool("ADLdapUserSearchSessionFactoryTests"); } @@ -77,7 +77,7 @@ public void testUserSearchWithActiveDirectory() throws Exception { }); Settings fullSettings = builder.build(); - sslService = new SSLService(fullSettings, TestEnvironment.newEnvironment(fullSettings)); + sslService = new SSLService(TestEnvironment.newEnvironment(fullSettings)); RealmConfig config = new RealmConfig(new RealmConfig.RealmIdentifier("ldap", "ad-as-ldap-test"), fullSettings, TestEnvironment.newEnvironment(fullSettings), new ThreadContext(fullSettings)); LdapUserSearchSessionFactory sessionFactory = getLdapUserSearchSessionFactory(config, sslService, threadPool); diff --git a/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/AbstractActiveDirectoryTestCase.java b/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/AbstractActiveDirectoryTestCase.java index df8b23d9381a1..e77c00b534b88 100644 --- a/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/AbstractActiveDirectoryTestCase.java +++ b/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/AbstractActiveDirectoryTestCase.java @@ -90,7 +90,7 @@ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IO builder.put("xpack.security.authc.realms.active_directory.bar.ssl.verification_mode", VerificationMode.CERTIFICATE); globalSettings = builder.build(); Environment environment = TestEnvironment.newEnvironment(globalSettings); - sslService = new SSLService(globalSettings, environment); + sslService = new SSLService(environment); } Settings buildAdSettings(RealmConfig.RealmIdentifier realmId, String ldapUrl, String adDomainName, String userSearchDN, diff --git a/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectorySessionFactoryTests.java b/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectorySessionFactoryTests.java index b122404507bc6..65936248b4db5 100644 --- a/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectorySessionFactoryTests.java +++ b/x-pack/qa/third-party/active-directory/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectorySessionFactoryTests.java @@ -87,13 +87,13 @@ public void testAdAuth() throws Exception { } private RealmConfig configureRealm(String name, String type, Settings settings) { - final Environment env = TestEnvironment.newEnvironment(globalSettings); final Settings mergedSettings = Settings.builder() .put(settings) .normalizePrefix("xpack.security.authc.realms." + type + "." + name + ".") .put(globalSettings) .build(); - this.sslService = new SSLService(mergedSettings, env); + final Environment env = TestEnvironment.newEnvironment(mergedSettings); + this.sslService = new SSLService(env); final RealmConfig.RealmIdentifier identifier = new RealmConfig.RealmIdentifier(type, name); return new RealmConfig(identifier, mergedSettings, env, new ThreadContext(globalSettings)); }