From f58f347fe1f21ca42c29ea264b8561ebe397ceb9 Mon Sep 17 00:00:00 2001 From: javanna Date: Thu, 19 May 2016 11:46:55 +0200 Subject: [PATCH 01/11] Replace HttpRequestBuilder usages with official RestClient Original commit: elastic/x-pack-elasticsearch@7428498b471d06dac2c677ef6d4fc0125949be1f --- .../shield/audit/IndexAuditIT.java | 14 ++- .../example/realm/CustomRealmIT.java | 29 ++++-- .../shield/MarvelSettingsFilterTests.java | 80 ++++++---------- .../AbstractPrivilegeTestCase.java | 68 +++++++------- .../integration/BulkUpdateTests.java | 84 ++++++++++------- .../integration/ClearRealmsCacheTests.java | 34 +++---- .../integration/ClearRolesCacheTests.java | 25 ++--- .../integration/IndexPrivilegeTests.java | 19 +++- .../integration/LicensingTests.java | 23 +++-- .../ShieldPluginEnabledDisabledTests.java | 16 ---- .../shield/ShieldPluginTests.java | 41 ++++----- .../shield/authc/RunAsIntegTests.java | 91 +++++++++++-------- .../authc/pki/PkiOptionalClientAuthTests.java | 37 ++++---- .../PkiWithoutClientAuthenticationTests.java | 28 +++--- .../shield/authc/pki/PkiWithoutSSLTests.java | 27 +++--- .../action/RestAuthenticateActionTests.java | 62 ++++++++----- .../transport/ssl/SslClientAuthTests.java | 32 +++---- .../watcher/WatcherPluginDisableTests.java | 19 ++-- .../WatcherSettingsFilterTests.java | 60 +++++------- 19 files changed, 395 insertions(+), 394 deletions(-) diff --git a/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java b/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java index e8858992dde..3f50acc809c 100644 --- a/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java +++ b/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java @@ -6,10 +6,13 @@ package org.elasticsearch.shield.audit; import com.carrotsearch.hppc.cursors.ObjectCursor; +import org.apache.http.message.BasicHeader; import org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateResponse; import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.cluster.ClusterState; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.RestClient; import org.elasticsearch.cluster.metadata.IndexTemplateMetaData; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.query.QueryBuilders; @@ -19,7 +22,6 @@ import org.elasticsearch.shield.audit.index.IndexAuditTrail; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ESIntegTestCase; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.xpack.XPackPlugin; import java.util.Collection; @@ -36,10 +38,12 @@ public class IndexAuditIT extends ESIntegTestCase { private static final String PASS = "changeme"; public void testShieldIndexAuditTrailWorking() throws Exception { - HttpResponse response = httpClient().path("/") - .addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray()))) - .execute(); - assertThat(response.getStatusCode(), is(200)); + try (RestClient restClient = restClient()) { + ElasticsearchResponse response = restClient.performRequest("GET", "/_cluster/health", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray())))); + assertThat(response.getStatusLine().getStatusCode(), is(200)); + } final AtomicReference lastClusterState = new AtomicReference<>(); final AtomicBoolean indexExists = new AtomicBoolean(false); diff --git a/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java b/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java index 0e46268b2a2..0ff3537e54a 100644 --- a/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java +++ b/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java @@ -5,9 +5,13 @@ */ package org.elasticsearch.example.realm; +import org.apache.http.message.BasicHeader; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.client.transport.NoNodeAvailableException; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; @@ -16,7 +20,6 @@ import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.env.Environment; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESIntegTestCase; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.xpack.XPackPlugin; import java.util.Collection; @@ -43,18 +46,24 @@ public class CustomRealmIT extends ESIntegTestCase { } public void testHttpConnectionWithNoAuthentication() throws Exception { - HttpResponse response = httpClient().path("/").execute(); - assertThat(response.getStatusCode(), is(401)); - String value = response.getHeaders().get("WWW-Authenticate"); - assertThat(value, is("custom-challenge")); + try (RestClient restClient = restClient()) { + restClient.performRequest("GET", "/", Collections.emptyMap(), null); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + ElasticsearchResponse response = e.getElasticsearchResponse(); + assertThat(response.getStatusLine().getStatusCode(), is(401)); + String value = response.getFirstHeader("WWW-Authenticate"); + assertThat(value, is("custom-challenge")); + } } public void testHttpAuthentication() throws Exception { - HttpResponse response = httpClient().path("/") - .addHeader(CustomRealm.USER_HEADER, CustomRealm.KNOWN_USER) - .addHeader(CustomRealm.PW_HEADER, CustomRealm.KNOWN_PW) - .execute(); - assertThat(response.getStatusCode(), is(200)); + try (RestClient restClient = restClient()) { + ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null, + new BasicHeader(CustomRealm.USER_HEADER, CustomRealm.KNOWN_USER), + new BasicHeader(CustomRealm.PW_HEADER, CustomRealm.KNOWN_PW)); + assertThat(response.getStatusLine().getStatusCode(), is(200)); + } } public void testTransportClient() throws Exception { diff --git a/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java b/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java index f847966061a..1d7426060c0 100644 --- a/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java +++ b/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java @@ -5,21 +5,19 @@ */ package org.elasticsearch.marvel.shield; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; +import org.apache.http.Header; +import org.apache.http.message.BasicHeader; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.json.JsonXContent; -import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.marvel.MonitoringSettings; import org.elasticsearch.marvel.test.MarvelIntegTestCase; import org.elasticsearch.shield.authc.support.SecuredString; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.hamcrest.Matchers; -import org.junit.After; -import java.io.IOException; +import java.util.Collections; import java.util.Map; import static org.elasticsearch.common.xcontent.support.XContentMapValues.extractValue; @@ -29,13 +27,6 @@ import static org.hamcrest.CoreMatchers.nullValue; public class MarvelSettingsFilterTests extends MarvelIntegTestCase { - private CloseableHttpClient httpClient = HttpClients.createDefault(); - - @After - public void cleanup() throws IOException { - httpClient.close(); - } - @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() @@ -53,46 +44,35 @@ public class MarvelSettingsFilterTests extends MarvelIntegTestCase { } public void testGetSettingsFiltered() throws Exception { - String body = executeRequest("GET", "/_nodes/settings", null, null).getBody(); - Map response = JsonXContent.jsonXContent.createParser(body).map(); - Map nodes = (Map) response.get("nodes"); - for (Object node : nodes.values()) { - Map settings = (Map) ((Map) node).get("settings"); - - assertThat(extractValue("xpack.monitoring.agent.exporters._http.type", settings), Matchers.equalTo("http")); - assertThat(extractValue("xpack.monitoring.agent.exporters._http.enabled", settings), Matchers.equalTo("false")); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.auth.username"); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.auth.password"); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.truststore.path"); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.truststore.password"); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.hostname_verification"); + try (RestClient restClient = restClient()) { + Header[] headers; + if (shieldEnabled) { + headers = new Header[] { + new BasicHeader(BASIC_AUTH_HEADER, + basicAuthHeaderValue(ShieldSettings.TEST_USERNAME, + new SecuredString(ShieldSettings.TEST_PASSWORD.toCharArray())))}; + } else { + headers = new Header[0]; + } + ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes/settings", Collections.emptyMap(), null, headers); + Map responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); + @SuppressWarnings("unchecked") + Map nodes = (Map) responseMap.get("nodes"); + for (Object node : nodes.values()) { + @SuppressWarnings("unchecked") + Map settings = (Map) ((Map) node).get("settings"); + assertThat(extractValue("xpack.monitoring.agent.exporters._http.type", settings), Matchers.equalTo("http")); + assertThat(extractValue("xpack.monitoring.agent.exporters._http.enabled", settings), Matchers.equalTo("false")); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.auth.username"); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.auth.password"); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.truststore.path"); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.truststore.password"); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.hostname_verification"); + } } } private void assertNullSetting(Map settings, String setting) { assertThat(extractValue(setting, settings), nullValue()); } - - protected HttpResponse executeRequest(String method, String path, String body, Map params) throws IOException { - HttpServerTransport httpServerTransport = internalCluster().getInstance(HttpServerTransport.class, - internalCluster().getMasterName()); - HttpRequestBuilder requestBuilder = new HttpRequestBuilder(httpClient) - .httpTransport(httpServerTransport) - .method(method) - .path(path); - - if (params != null) { - for (Map.Entry entry : params.entrySet()) { - requestBuilder.addParam(entry.getKey(), entry.getValue()); - } - } - if (body != null) { - requestBuilder.body(body); - } - if (shieldEnabled) { - requestBuilder.addHeader(BASIC_AUTH_HEADER, - basicAuthHeaderValue(ShieldSettings.TEST_USERNAME, new SecuredString(ShieldSettings.TEST_PASSWORD.toCharArray()))); - } - return requestBuilder.execute(); - } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java index efc3f2109cd..20e76bf1031 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java @@ -5,16 +5,18 @@ */ package org.elasticsearch.integration; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.elasticsearch.http.HttpServerTransport; +import org.apache.http.HttpEntity; +import org.apache.http.StatusLine; +import org.apache.http.entity.StringEntity; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.shield.authc.support.Hasher; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ShieldIntegTestCase; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; -import org.junit.After; import java.io.IOException; import java.util.HashMap; @@ -32,19 +34,17 @@ public abstract class AbstractPrivilegeTestCase extends ShieldIntegTestCase { protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("passwd".toCharArray()))); - private CloseableHttpClient httpClient = HttpClients.createDefault(); - - @After - public void cleanup() throws IOException { - httpClient.close(); - } - protected void assertAccessIsAllowed(String user, String method, String uri, String body, Map params) throws IOException { - HttpResponse response = executeRequest(user, method, uri, body, params); - String message = String.format(Locale.ROOT, "%s %s: Expected no error got %s %s with body %s", method, uri, - response.getStatusCode(), response.getReasonPhrase(), response.getBody()); - assertThat(message, response.getStatusCode(), is(not(greaterThanOrEqualTo(400)))); + try (RestClient restClient = restClient()) { + ElasticsearchResponse response = restClient.performRequest(method, uri, params, entityOrNull(body), + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray())))); + StatusLine statusLine = response.getStatusLine(); + String message = String.format(Locale.ROOT, "%s %s: Expected no error got %s %s with body %s", method, uri, + statusLine.getStatusCode(), statusLine.getReasonPhrase(), EntityUtils.toString(response.getEntity())); + assertThat(message, statusLine.getStatusCode(), is(not(greaterThanOrEqualTo(400)))); + } } protected void assertAccessIsAllowed(String user, String method, String uri, String body) throws IOException { @@ -65,28 +65,24 @@ public abstract class AbstractPrivilegeTestCase extends ShieldIntegTestCase { protected void assertAccessIsDenied(String user, String method, String uri, String body, Map params) throws IOException { - HttpResponse response = executeRequest(user, method, uri, body, params); - String message = String.format(Locale.ROOT, "%s %s body %s: Expected 403, got %s %s with body %s", method, uri, body, - response.getStatusCode(), response.getReasonPhrase(), response.getBody()); - assertThat(message, response.getStatusCode(), is(403)); + try (RestClient restClient = restClient()) { + restClient.performRequest(method, uri, params, entityOrNull(body), + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray())))); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + StatusLine statusLine = e.getElasticsearchResponse().getStatusLine(); + String message = String.format(Locale.ROOT, "%s %s body %s: Expected 403, got %s %s with body %s", method, uri, body, + statusLine.getStatusCode(), statusLine.getReasonPhrase(), e.getResponseBody()); + assertThat(message, statusLine.getStatusCode(), is(403)); + } } - protected HttpResponse executeRequest(String user, String method, String uri, String body, - Map params) throws IOException { - HttpServerTransport httpServerTransport = internalCluster().getDataNodeInstance(HttpServerTransport.class); - - HttpRequestBuilder requestBuilder = new HttpRequestBuilder(httpClient).httpTransport(httpServerTransport); - requestBuilder.path(uri); - requestBuilder.method(method); - for (Map.Entry entry : params.entrySet()) { - requestBuilder.addParam(entry.getKey(), entry.getValue()); - } + private static HttpEntity entityOrNull(String body) { + HttpEntity entity = null; if (body != null) { - requestBuilder.body(body); + entity = new StringEntity(body, RestClient.JSON_CONTENT_TYPE); } - requestBuilder.addHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(user, - new SecuredString("passwd".toCharArray()))); - return requestBuilder.execute(); + return entity; } - } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java index 4c0f825a143..50590bb7bbc 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java @@ -5,9 +5,15 @@ */ package org.elasticsearch.integration; +import org.apache.http.Header; +import org.apache.http.entity.StringEntity; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.update.UpdateResponse; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.Security; @@ -15,10 +21,10 @@ import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.xpack.XPackPlugin; import java.io.IOException; +import java.util.Collections; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -49,8 +55,8 @@ public class BulkUpdateTests extends ShieldIntegTestCase { .get().isCreated(); assertThat(created, is(false)); getResponse = internalCluster().transportClient().prepareGet("index1", "type", "1").setFields("test", "not test").get(); - assertThat((String) getResponse.getField("test").getValue(), equalTo("test")); - assertThat((String) getResponse.getField("not test").getValue(), equalTo("not test")); + assertThat(getResponse.getField("test").getValue(), equalTo("test")); + assertThat(getResponse.getField("not test").getValue(), equalTo("not test")); // this part is important. Without this, the document may be read from the translog which would bypass the bug where // FLS kicks in because the request can't be found and only returns meta fields @@ -62,43 +68,55 @@ public class BulkUpdateTests extends ShieldIntegTestCase { assertThat(((UpdateResponse)response.getItems()[0].getResponse()).isCreated(), is(false)); getResponse = internalCluster().transportClient().prepareGet("index1", "type", "1"). setFields("test", "not test", "bulk updated").get(); - assertThat((String) getResponse.getField("test").getValue(), equalTo("test")); - assertThat((String) getResponse.getField("not test").getValue(), equalTo("not test")); - assertThat((String) getResponse.getField("bulk updated").getValue(), equalTo("bulk updated")); + assertThat(getResponse.getField("test").getValue(), equalTo("test")); + assertThat(getResponse.getField("not test").getValue(), equalTo("not test")); + assertThat(getResponse.getField("bulk updated").getValue(), equalTo("bulk updated")); } public void testThatBulkUpdateDoesNotLoseFieldsHttp() throws IOException { final String path = "/index1/type/1"; - final String basicAuthHeader = UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())); + final Header basicAuthHeader = new BasicHeader("Authorization", + UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))); - httpClient().path(path).addHeader("Authorization", basicAuthHeader).method("PUT").body("{\"test\":\"test\"}").execute(); - HttpResponse response = httpClient().path(path).addHeader("Authorization", basicAuthHeader).method("GET").execute(); - assertThat(response.getBody(), containsString("\"test\":\"test\"")); + try (RestClient restClient = restClient()) { + StringEntity body = new StringEntity("{\"test\":\"test\"}", RestClient.JSON_CONTENT_TYPE); + ElasticsearchResponse response = restClient.performRequest("PUT", path, Collections.emptyMap(), body, basicAuthHeader); + assertThat(response.getStatusLine().getStatusCode(), equalTo(201)); - if (randomBoolean()) { + response = restClient.performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(EntityUtils.toString(response.getEntity()), containsString("\"test\":\"test\"")); + + if (randomBoolean()) { + flushAndRefresh(); + } + + //update with new field + body = new StringEntity("{\"doc\": {\"not test\": \"not test\"}}", RestClient.JSON_CONTENT_TYPE); + response = restClient.performRequest("POST", path + "/_update", Collections.emptyMap(), body, basicAuthHeader); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + + response = restClient.performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + String responseBody = EntityUtils.toString(response.getEntity()); + assertThat(responseBody, containsString("\"test\":\"test\"")); + assertThat(responseBody, containsString("\"not test\":\"not test\"")); + + // this part is important. Without this, the document may be read from the translog which would bypass the bug where + // FLS kicks in because the request can't be found and only returns meta fields flushAndRefresh(); + + body = new StringEntity("{\"update\": {\"_index\": \"index1\", \"_type\": \"type\", \"_id\": \"1\"}}\n" + + "{\"doc\": {\"bulk updated\":\"bulk updated\"}}\n", RestClient.JSON_CONTENT_TYPE); + response = restClient.performRequest("POST", "/_bulk", Collections.emptyMap(), body, basicAuthHeader); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + + response = restClient.performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader); + responseBody = EntityUtils.toString(response.getEntity()); + assertThat(responseBody, containsString("\"test\":\"test\"")); + assertThat(responseBody, containsString("\"not test\":\"not test\"")); + assertThat(responseBody, containsString("\"bulk updated\":\"bulk updated\"")); } - - //update with new field - httpClient().path(path + "/_update").addHeader("Authorization", basicAuthHeader).method("POST"). - body("{\"doc\": {\"not test\": \"not test\"}}").execute(); - response = httpClient().path(path).addHeader("Authorization", basicAuthHeader).method("GET").execute(); - assertThat(response.getBody(), containsString("\"test\":\"test\"")); - assertThat(response.getBody(), containsString("\"not test\":\"not test\"")); - - // this part is important. Without this, the document may be read from the translog which would bypass the bug where - // FLS kicks in because the request can't be found and only returns meta fields - flushAndRefresh(); - - // update with bulk - httpClient().path("/_bulk").addHeader("Authorization", basicAuthHeader).method("POST") - .body("{\"update\": {\"_index\": \"index1\", \"_type\": \"type\", \"_id\": \"1\"}}\n{\"doc\": {\"bulk updated\":\"bulk " + - "updated\"}}\n") - .execute(); - response = httpClient().path(path).addHeader("Authorization", basicAuthHeader).method("GET").execute(); - assertThat(response.getBody(), containsString("\"test\":\"test\"")); - assertThat(response.getBody(), containsString("\"not test\":\"not test\"")); - assertThat(response.getBody(), containsString("\"bulk updated\":\"bulk updated\"")); } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java index 303b3e90ca0..241309fc6c5 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java @@ -5,14 +5,14 @@ */ package org.elasticsearch.integration; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; import org.elasticsearch.action.ActionListener; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.http.HttpServerTransport; -import org.elasticsearch.shield.user.User; import org.elasticsearch.shield.action.realm.ClearRealmCacheRequest; import org.elasticsearch.shield.action.realm.ClearRealmCacheResponse; import org.elasticsearch.shield.authc.Realm; @@ -22,10 +22,9 @@ import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.SecuredStringTests; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.shield.client.SecurityClient; +import org.elasticsearch.shield.user.User; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.junit.BeforeClass; import java.util.ArrayList; @@ -39,7 +38,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.sameInstance; @@ -168,21 +166,13 @@ public class ClearRealmsCacheTests extends ShieldIntegTestCase { } static void executeHttpRequest(String path, Map params) throws Exception { - try (CloseableHttpClient client = HttpClients.createDefault()) { - HttpRequestBuilder requestBuilder = new HttpRequestBuilder(client) - .httpTransport(internalCluster().getDataNodeInstance(HttpServerTransport.class)) - .method("POST") - .path(path); - for (Map.Entry entry : params.entrySet()) { - requestBuilder.addParam(entry.getKey(), entry.getValue()); - } - requestBuilder.addHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))); - HttpResponse response = requestBuilder.execute(); - assertThat(response.hasBody(), is(true)); - String body = response.getBody(); - assertThat(body.contains("cluster_name"), is(true)); + try (RestClient restClient = restClient()) { + ElasticsearchResponse response = restClient.performRequest("POST", path, params, null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); + assertNotNull(response.getEntity()); + assertTrue(EntityUtils.toString(response.getEntity()).contains("cluster_name")); } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java index a2cda298e38..ae3cdd7db8c 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java @@ -5,18 +5,20 @@ */ package org.elasticsearch.integration; +import org.apache.http.message.BasicHeader; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.Client; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.rest.RestStatus; -import org.elasticsearch.shield.action.role.PutRoleResponse; -import org.elasticsearch.shield.action.role.GetRolesResponse; import org.elasticsearch.shield.ShieldTemplateService; -import org.elasticsearch.shield.authc.esnative.NativeRealm; +import org.elasticsearch.shield.action.role.GetRolesResponse; +import org.elasticsearch.shield.action.role.PutRoleResponse; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.shield.authz.RoleDescriptor; @@ -24,11 +26,11 @@ import org.elasticsearch.shield.authz.store.NativeRolesStore; import org.elasticsearch.shield.client.SecurityClient; import org.elasticsearch.test.NativeRealmIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.junit.Before; import org.junit.BeforeClass; import java.util.Arrays; +import java.util.Collections; import java.util.List; import static org.hamcrest.Matchers.arrayWithSize; @@ -127,7 +129,7 @@ public class ClearRolesCacheTests extends NativeRealmIntegTestCase { final boolean useHttp = randomBoolean(); final boolean clearAll = randomBoolean(); logger.debug("--> starting to clear roles. using http [{}] clearing all [{}]", useHttp, clearAll); - String[] rolesToClear = clearAll ? (randomBoolean() ? roles : null) : toModify.toArray(Strings.EMPTY_ARRAY); + String[] rolesToClear = clearAll ? (randomBoolean() ? roles : null) : toModify.toArray(new String[toModify.size()]); if (useHttp) { String path; if (rolesToClear == null) { @@ -135,12 +137,13 @@ public class ClearRolesCacheTests extends NativeRealmIntegTestCase { } else { path = "/_xpack/security/role/" + Strings.arrayToCommaDelimitedString(rolesToClear) + "/_clear_cache"; } - HttpResponse response = httpClient().path(path).method("POST") - .addHeader("Authorization", - UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))) - .execute(); - assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); + try (RestClient restClient = restClient()) { + ElasticsearchResponse response = restClient.performRequest("POST", path, Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); + assertThat(response.getStatusLine().getStatusCode(), is(RestStatus.OK.getStatus())); + } } else { securityClient.prepareClearRolesCache().names(rolesToClear).get(); } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java index 5519eea89fa..1eeae9976a0 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java @@ -5,19 +5,22 @@ */ package org.elasticsearch.integration; -import org.apache.lucene.util.LuceneTestCase.BadApple; +import org.apache.http.message.BasicHeader; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.shield.authc.support.SecuredString; +import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ESIntegTestCase; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.junit.Before; import java.util.Collections; -import java.util.HashMap; import java.util.Locale; import java.util.Map; import static java.util.Collections.singletonMap; +import static org.apache.lucene.util.LuceneTestCase.BadApple; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; @@ -303,8 +306,14 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { } public void testThatUnknownUserIsRejectedProperly() throws Exception { - HttpResponse response = executeRequest("idonotexist", "GET", "/", null, new HashMap<>()); - assertThat(response.getStatusCode(), is(401)); + try (RestClient restClient = restClient()){ + restClient.performRequest("GET", "/", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue("idonotexist", new SecuredString("passwd".toCharArray())))); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); + } } private void assertUserExecutes(String user, String action, String index, boolean userIsAllowed) throws Exception { diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java index 550d280eaf6..fa555000938 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java @@ -14,6 +14,9 @@ import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse; import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.Client; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.client.transport.NoNodeAvailableException; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.component.AbstractComponent; @@ -194,13 +197,21 @@ public class LicensingTests extends ShieldIntegTestCase { } public void testRestAuthenticationByLicenseType() throws Exception { - // the default of the licensing tests is basic - assertThat(httpClient().path("/").execute().getStatusCode(), is(200)); + try (RestClient restClient = restClient()) { + ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null); + // the default of the licensing tests is basic + assertThat(response.getStatusLine().getStatusCode(), is(200)); - // generate a new license with a mode that enables auth - OperationMode mode = randomFrom(OperationMode.GOLD, OperationMode.TRIAL, OperationMode.PLATINUM, OperationMode.STANDARD); - enableLicensing(mode); - assertThat(httpClient().path("/").execute().getStatusCode(), is(401)); + // generate a new license with a mode that enables auth + OperationMode mode = randomFrom(OperationMode.GOLD, OperationMode.TRIAL, OperationMode.PLATINUM, OperationMode.STANDARD); + enableLicensing(mode); + try { + restClient.performRequest("GET", "/", Collections.emptyMap(), null); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); + } + } } public void testTransportClientAuthenticationByLicenseType() throws Exception { diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginEnabledDisabledTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginEnabledDisabledTests.java index fbb4b49145e..c8b74c18c51 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginEnabledDisabledTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginEnabledDisabledTests.java @@ -5,22 +5,12 @@ */ package org.elasticsearch.shield; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.integration.LicensingTests; -import org.elasticsearch.license.core.License.OperationMode; -import org.elasticsearch.shield.authc.support.SecuredString; -import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.shield.transport.ShieldServerTransportService; import org.elasticsearch.shield.transport.netty.ShieldNettyTransport; import org.elasticsearch.test.ShieldIntegTestCase; -import org.elasticsearch.test.ShieldSettingsSource; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; -import org.elasticsearch.test.rest.json.JsonPath; import org.elasticsearch.transport.Transport; import org.elasticsearch.transport.TransportService; import org.elasticsearch.xpack.XPackPlugin; @@ -28,13 +18,7 @@ import org.hamcrest.Matcher; import org.junit.After; import org.junit.BeforeClass; -import java.io.IOException; - -import static org.elasticsearch.rest.RestStatus.OK; -import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; /** diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java index 2f543a4b280..7d8ac262c3f 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java @@ -5,24 +5,22 @@ */ package org.elasticsearch.shield; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; import java.io.IOException; +import java.util.Collections; import static org.elasticsearch.rest.RestStatus.OK; import static org.elasticsearch.rest.RestStatus.UNAUTHORIZED; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; public class ShieldPluginTests extends ShieldIntegTestCase { @@ -36,24 +34,21 @@ public class ShieldPluginTests extends ShieldIntegTestCase { } public void testThatPluginIsLoaded() throws IOException { - HttpServerTransport httpServerTransport = internalCluster().getDataNodeInstance(HttpServerTransport.class); - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - logger.info("executing unauthorized request to /_xpack info"); - HttpResponse response = new HttpRequestBuilder(httpClient).httpTransport(httpServerTransport) - .method("GET") - .path("/_xpack") - .execute(); - assertThat(response.getStatusCode(), is(UNAUTHORIZED.getStatus())); + try (RestClient restClient = restClient()) { + try { + logger.info("executing unauthorized request to /_xpack info"); + restClient.performRequest("GET", "/_xpack", Collections.emptyMap(), null); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(UNAUTHORIZED.getStatus())); + } logger.info("executing authorized request to /_xpack infos"); - response = new HttpRequestBuilder(httpClient).httpTransport(httpServerTransport) - .method("GET") - .path("/_xpack") - .addHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))) - .execute(); - assertThat(response.getStatusCode(), is(OK.getStatus())); + ElasticsearchResponse response = restClient.performRequest("GET", "/_xpack", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); + assertThat(response.getStatusLine().getStatusCode(), is(OK.getStatus())); } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java index 5da10e734b3..a1a75f2d1ec 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java @@ -5,10 +5,14 @@ */ package org.elasticsearch.shield.authc; +import org.apache.http.message.BasicHeader; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; @@ -20,7 +24,6 @@ import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.shield.transport.netty.ShieldNettyTransport; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.xpack.XPackPlugin; import java.util.Collections; @@ -115,30 +118,37 @@ public class RunAsIntegTests extends ShieldIntegTestCase { public void testUserImpersonationUsingHttp() throws Exception { // use the transport client user and try to run as - HttpResponse response = httpClient().method("GET") - .path("/_nodes") - .addHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(TRANSPORT_CLIENT_USER, - SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))) - .addHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, ShieldSettingsSource.DEFAULT_USER_NAME) - .execute(); - assertThat(response.getStatusCode(), is(403)); + try (RestClient restClient = restClient()) { + try { + restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(TRANSPORT_CLIENT_USER, + SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), + new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, ShieldSettingsSource.DEFAULT_USER_NAME)); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(403)); + } - //the run as user shouldn't have access to the nodes api - response = httpClient().method("GET") - .path("/_nodes") - .addHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, - SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))) - .execute(); - assertThat(response.getStatusCode(), is(403)); + try { + //the run as user shouldn't have access to the nodes api + restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, + SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD)))); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(403)); + } - // but when running as a different user it should work - response = httpClient().method("GET") - .path("/_nodes") - .addHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, - SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))) - .addHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, ShieldSettingsSource.DEFAULT_USER_NAME) - .execute(); - assertThat(response.getStatusCode(), is(200)); + // but when running as a different user it should work + ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, + SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), + new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, ShieldSettingsSource.DEFAULT_USER_NAME)); + assertThat(response.getStatusLine().getStatusCode(), is(200)); + } } public void testEmptyUserImpersonationHeader() throws Exception { @@ -164,13 +174,16 @@ public class RunAsIntegTests extends ShieldIntegTestCase { } public void testEmptyHeaderUsingHttp() throws Exception { - HttpResponse response = httpClient().method("GET") - .path("/_nodes") - .addHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, - SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))) - .addHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, "") - .execute(); - assertThat(response.getStatusCode(), is(401)); + try (RestClient restClient = restClient()) { + restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, + SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), + new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, "")); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); + } } public void testNonExistentRunAsUser() throws Exception { @@ -196,13 +209,17 @@ public class RunAsIntegTests extends ShieldIntegTestCase { } public void testNonExistentRunAsUserUsingHttp() throws Exception { - HttpResponse response = httpClient().method("GET") - .path("/_nodes") - .addHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, - SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))) - .addHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, "idontexist") - .execute(); - assertThat(response.getStatusCode(), is(403)); + + try (RestClient restClient = restClient()) { + restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, + SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), + new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, "idontexist")); + fail("request should have failed"); + } catch (ElasticsearchResponseException e) { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(403)); + } } // build our own here to better mimic an actual client... diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java index 4e983854641..5198454adc0 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java @@ -7,11 +7,14 @@ package org.elasticsearch.shield.authc.pki; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; -import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.shield.Security; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; @@ -20,8 +23,6 @@ import org.elasticsearch.shield.transport.netty.ShieldNettyHttpServerTransport; import org.elasticsearch.shield.transport.netty.ShieldNettyTransport; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.transport.Transport; import org.elasticsearch.xpack.XPackPlugin; import org.junit.BeforeClass; @@ -34,6 +35,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyStore; import java.security.SecureRandom; +import java.util.Collections; import static org.elasticsearch.test.ShieldSettingsSource.DEFAULT_PASSWORD; import static org.elasticsearch.test.ShieldSettingsSource.DEFAULT_USER_NAME; @@ -78,23 +80,20 @@ public class PkiOptionalClientAuthTests extends ShieldIntegTestCase { } public void testRestClientWithoutClientCertificate() throws Exception { - HttpServerTransport httpServerTransport = internalCluster().getDataNodeInstance(HttpServerTransport.class); + CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(getSSLContext()).build(); + try (RestClient restClient = restClient(httpClient, "https")) { + try { + restClient.performRequest("GET", "_nodes", Collections.emptyMap(), null); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); + } - try (CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(getSSLContext()).build()) { - HttpRequestBuilder requestBuilder = new HttpRequestBuilder(httpClient) - .host("localhost") - .port(((InetSocketTransportAddress)httpServerTransport.boundAddress().publishAddress()).address().getPort()) - .protocol("https") - .method("GET") - .path("/_nodes"); - HttpResponse response = requestBuilder.execute(); - assertThat(response.getStatusCode(), is(401)); - - requestBuilder.addHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))); - response = requestBuilder.execute(); - assertThat(response.getStatusCode(), is(200)); + ElasticsearchResponse response = restClient.performRequest("GET", "_nodes", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); + assertThat(response.getStatusLine().getStatusCode(), is(200)); } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java index f874fcfebe2..7026062188f 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java @@ -8,11 +8,12 @@ package org.elasticsearch.shield.authc.pki; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Client; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.transport.InetSocketTransportAddress; -import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.shield.transport.SSLClientAuth; @@ -21,14 +22,13 @@ import org.elasticsearch.shield.transport.netty.ShieldNettyTransport; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.SecureRandom; import java.security.cert.X509Certificate; +import java.util.Collections; import java.util.Locale; import static org.hamcrest.Matchers.is; @@ -77,21 +77,15 @@ public class PkiWithoutClientAuthenticationTests extends ShieldIntegTestCase { } public void testThatHttpWorks() throws Exception { - HttpServerTransport httpServerTransport = internalCluster().getDataNodeInstance(HttpServerTransport.class); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); - try (CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sc).build()) { - HttpRequestBuilder requestBuilder = new HttpRequestBuilder(httpClient) - .host("localhost") - .port(((InetSocketTransportAddress)httpServerTransport.boundAddress().publishAddress()).address().getPort()) - .protocol("https") - .method("GET") - .path("/_nodes"); - requestBuilder.addHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))); - HttpResponse response = requestBuilder.execute(); - assertThat(response.getStatusCode(), is(200)); + CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sc).build(); + try (RestClient restClient = restClient(httpClient, "https")) { + ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); + assertThat(response.getStatusLine().getStatusCode(), is(200)); } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java index fcfc3cccdb0..33bd6b423e2 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java @@ -5,19 +5,19 @@ */ package org.elasticsearch.shield.authc.pki; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Client; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; + +import java.util.Collections; import static org.hamcrest.Matchers.is; @@ -44,17 +44,12 @@ public class PkiWithoutSSLTests extends ShieldIntegTestCase { } public void testThatHttpWorks() throws Exception { - HttpServerTransport httpServerTransport = internalCluster().getDataNodeInstance(HttpServerTransport.class); - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpRequestBuilder requestBuilder = new HttpRequestBuilder(httpClient) - .httpTransport(httpServerTransport) - .method("GET") - .path("/_nodes"); - requestBuilder.addHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))); - HttpResponse response = requestBuilder.execute(); - assertThat(response.getStatusCode(), is(200)); + try (RestClient restClient = restClient()) { + ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); + assertThat(response.getStatusLine().getStatusCode(), is(200)); } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java index 23cdaf239be..4ec2040d1cc 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java @@ -5,6 +5,11 @@ */ package org.elasticsearch.shield.rest.action; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.authc.support.SecuredString; @@ -12,10 +17,10 @@ import org.elasticsearch.shield.authz.InternalAuthorizationService; import org.elasticsearch.shield.user.AnonymousUser; import org.elasticsearch.test.ShieldIntegTestCase; import org.elasticsearch.test.ShieldSettingsSource; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.test.rest.json.JsonPath; import org.junit.BeforeClass; +import java.util.Collections; import java.util.List; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; @@ -47,32 +52,41 @@ public class RestAuthenticateActionTests extends ShieldIntegTestCase { } public void testAuthenticateApi() throws Exception { - HttpResponse response = httpClient().method("GET").path("/_xpack/security/_authenticate") - .addHeader("Authorization", basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))) - .execute(); - - assertThat(response.getStatusCode(), is(200)); - JsonPath jsonPath = new JsonPath(response.getBody()); - assertThat(jsonPath.evaluate("username").toString(), equalTo(ShieldSettingsSource.DEFAULT_USER_NAME)); - List roles = (List) jsonPath.evaluate("roles"); - assertThat(roles.size(), is(1)); - assertThat(roles, contains(ShieldSettingsSource.DEFAULT_ROLE)); + try (RestClient restClient = restClient()) { + ElasticsearchResponse response = restClient.performRequest("GET", "/_xpack/security/_authenticate", Collections.emptyMap(), + null, new BasicHeader("Authorization", basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); + assertThat(response.getStatusLine().getStatusCode(), is(200)); + JsonPath jsonPath = new JsonPath(EntityUtils.toString(response.getEntity())); + assertThat(jsonPath.evaluate("username").toString(), equalTo(ShieldSettingsSource.DEFAULT_USER_NAME)); + @SuppressWarnings("unchecked") + List roles = (List) jsonPath.evaluate("roles"); + assertThat(roles.size(), is(1)); + assertThat(roles, contains(ShieldSettingsSource.DEFAULT_ROLE)); + } } public void testAuthenticateApiWithoutAuthentication() throws Exception { - HttpResponse response = httpClient().method("GET").path("/_xpack/security/_authenticate") - .execute(); - - if (anonymousEnabled) { - assertThat(response.getStatusCode(), is(200)); - JsonPath jsonPath = new JsonPath(response.getBody()); - assertThat(jsonPath.evaluate("username").toString(), equalTo("anon")); - List roles = (List) jsonPath.evaluate("roles"); - assertThat(roles.size(), is(2)); - assertThat(roles, contains(ShieldSettingsSource.DEFAULT_ROLE, "foo")); - } else { - assertThat(response.getStatusCode(), is(401)); + try (RestClient restClient = restClient()) { + ElasticsearchResponse response = restClient.performRequest("GET", "/_xpack/security/_authenticate", + Collections.emptyMap(), null); + if (anonymousEnabled) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); + JsonPath jsonPath = new JsonPath(EntityUtils.toString(response.getEntity())); + assertThat(jsonPath.evaluate("username").toString(), equalTo("anon")); + @SuppressWarnings("unchecked") + List roles = (List) jsonPath.evaluate("roles"); + assertThat(roles.size(), is(2)); + assertThat(roles, contains(ShieldSettingsSource.DEFAULT_ROLE, "foo")); + } else { + fail("request should have failed"); + } + } catch(ElasticsearchResponseException e) { + if (anonymousEnabled) { + fail("request should have succeeded"); + } else { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); + } } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java index 1948175177d..5f18c7eb4e3 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java @@ -9,20 +9,21 @@ import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContexts; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; import org.elasticsearch.ElasticsearchException; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.RestClient; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; -import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.shield.Security; import org.elasticsearch.shield.ssl.ClientSSLService; import org.elasticsearch.shield.ssl.SSLConfiguration.Global; import org.elasticsearch.shield.transport.netty.ShieldNettyHttpServerTransport; import org.elasticsearch.shield.transport.netty.ShieldNettyTransport; import org.elasticsearch.test.ShieldIntegTestCase; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.transport.Transport; import org.elasticsearch.xpack.XPackPlugin; @@ -30,10 +31,12 @@ import javax.net.ssl.SSLHandshakeException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Collections; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; import static org.elasticsearch.test.ShieldSettingsSource.getSSLSettingsForStore; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; public class SslClientAuthTests extends ShieldIntegTestCase { @Override @@ -59,14 +62,8 @@ public class SslClientAuthTests extends ShieldIntegTestCase { SSLContexts.createDefault(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); - - try { - new HttpRequestBuilder(client) - .httpTransport(internalCluster().getInstance(HttpServerTransport.class)) - .method("GET").path("/") - .protocol("https") - .execute(); + try (RestClient restClient = restClient(HttpClients.custom().setSSLSocketFactory(socketFactory).build(), "https")) { + restClient.performRequest("GET", "/", Collections.emptyMap(), null); fail("Expected SSLHandshakeException"); } catch (SSLHandshakeException e) { assertThat(e.getMessage(), containsString("unable to find valid certification path to requested target")); @@ -85,13 +82,12 @@ public class SslClientAuthTests extends ShieldIntegTestCase { CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); - HttpResponse response = new HttpRequestBuilder(client) - .httpTransport(internalCluster().getInstance(HttpServerTransport.class)) - .method("GET").path("/") - .protocol("https") - .addHeader("Authorization", basicAuthHeaderValue(transportClientUsername(), transportClientPassword())) - .execute(); - assertThat(response.getBody(), containsString("You Know, for Search")); + try (RestClient restClient = restClient(client, "https")) { + ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null, + new BasicHeader("Authorization", basicAuthHeaderValue(transportClientUsername(), transportClientPassword()))); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(EntityUtils.toString(response.getEntity()), containsString("You Know, for Search")); + } } public void testThatTransportWorksWithoutSslClientAuth() throws Exception { diff --git a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherPluginDisableTests.java b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherPluginDisableTests.java index 54d266b47fa..004de9874af 100644 --- a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherPluginDisableTests.java +++ b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherPluginDisableTests.java @@ -6,10 +6,10 @@ package org.elasticsearch.xpack.watcher; import org.apache.http.HttpStatus; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.http.HttpServerTransport; @@ -18,12 +18,10 @@ import org.elasticsearch.plugins.Plugin; import org.elasticsearch.shield.Security; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.threadpool.ThreadPoolInfo; -import org.elasticsearch.xpack.watcher.execution.InternalWatchExecutor; import org.elasticsearch.xpack.XPackPlugin; +import org.elasticsearch.xpack.watcher.execution.InternalWatchExecutor; import java.util.Collection; import java.util.Collections; @@ -70,12 +68,11 @@ public class WatcherPluginDisableTests extends ESIntegTestCase { public void testRestEndpoints() throws Exception { HttpServerTransport httpServerTransport = internalCluster().getDataNodeInstance(HttpServerTransport.class); - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpRequestBuilder request = new HttpRequestBuilder(httpClient).httpTransport(httpServerTransport) - .method("GET") - .path("/_xpack/watcher"); - HttpResponse response = request.execute(); - assertThat(response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); + try (RestClient restClient = restClient()) { + restClient.performRequest("GET", "/_xpack/watcher", Collections.emptyMap(), null); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); } } diff --git a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java index 12f2fb6b423..303e844b5d5 100644 --- a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java +++ b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java @@ -5,26 +5,27 @@ */ package org.elasticsearch.xpack.watcher.test.integration; +import org.apache.http.Header; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.common.xcontent.support.XContentMapValues; -import org.elasticsearch.http.HttpServerTransport; +import org.elasticsearch.marvel.test.MarvelIntegTestCase; import org.elasticsearch.shield.authc.support.SecuredString; -import org.elasticsearch.test.rest.client.http.HttpRequestBuilder; -import org.elasticsearch.test.rest.client.http.HttpResponse; import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase; import org.junit.After; import java.io.IOException; +import java.util.Collections; import java.util.Map; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.BASIC_AUTH_HEADER; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; -import static org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase.ShieldSettings.TEST_PASSWORD; -import static org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase.ShieldSettings.TEST_USERNAME; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.is; @@ -52,37 +53,26 @@ public class WatcherSettingsFilterTests extends AbstractWatcherIntegrationTestCa } public void testGetSettingsSmtpPassword() throws Exception { - String body = executeRequest("GET", "/_nodes/settings", null, null).getBody(); - Map response = JsonXContent.jsonXContent.createParser(body).map(); - Map nodes = (Map) response.get("nodes"); - for (Object node : nodes.values()) { - Map settings = (Map) ((Map) node).get("settings"); - assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.user", settings), - is((Object) "_user")); - assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.password", settings), - nullValue()); - } - } - - protected HttpResponse executeRequest(String method, String path, String body, Map params) throws IOException { - HttpServerTransport httpServerTransport = getInstanceFromMaster(HttpServerTransport.class); - HttpRequestBuilder requestBuilder = new HttpRequestBuilder(httpClient) - .httpTransport(httpServerTransport) - .method(method) - .path(path); - - if (params != null) { - for (Map.Entry entry : params.entrySet()) { - requestBuilder.addParam(entry.getKey(), entry.getValue()); + try (RestClient restClient = restClient()) { + Header[] headers; + if (shieldEnabled()) { + headers = new Header[] { + new BasicHeader(BASIC_AUTH_HEADER, + basicAuthHeaderValue(MarvelIntegTestCase.ShieldSettings.TEST_USERNAME, + new SecuredString(MarvelIntegTestCase.ShieldSettings.TEST_PASSWORD.toCharArray())))}; + } else { + headers = new Header[0]; + } + ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes/settings", Collections.emptyMap(), null, headers); + Map responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); + Map nodes = (Map) responseMap.get("nodes"); + for (Object node : nodes.values()) { + Map settings = (Map) ((Map) node).get("settings"); + assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.user", settings), + is((Object) "_user")); + assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.password", settings), + nullValue()); } } - if (body != null) { - requestBuilder.body(body); - } - if (shieldEnabled()) { - requestBuilder.addHeader(BASIC_AUTH_HEADER, - basicAuthHeaderValue(TEST_USERNAME, new SecuredString(TEST_PASSWORD.toCharArray()))); - } - return requestBuilder.execute(); } } From e882fb3a1890c48d7f75b14c1d4ec61a8a49d1c0 Mon Sep 17 00:00:00 2001 From: javanna Date: Thu, 19 May 2016 15:19:22 +0200 Subject: [PATCH 02/11] Replace rest test client with low level RestClient We still have a wrapper called RestTestClient that is very specific to Rest tests, as well as RestTestResponse etc. but all the low level bits around http connections etc. are now handled by RestClient. Original commit: elastic/x-pack-elasticsearch@304487ecc5b8fe4b192da165b5b681296537415a --- .../smoketest/SmokeTestPluginsSslIT.java | 8 ++++---- .../xpack/test/rest/XPackRestTestCase.java | 20 ++++++++++--------- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/elasticsearch/qa/smoke-test-plugins-ssl/src/test/java/org/elasticsearch/smoketest/SmokeTestPluginsSslIT.java b/elasticsearch/qa/smoke-test-plugins-ssl/src/test/java/org/elasticsearch/smoketest/SmokeTestPluginsSslIT.java index 17878a9e51f..50027ae656a 100644 --- a/elasticsearch/qa/smoke-test-plugins-ssl/src/test/java/org/elasticsearch/smoketest/SmokeTestPluginsSslIT.java +++ b/elasticsearch/qa/smoke-test-plugins-ssl/src/test/java/org/elasticsearch/smoketest/SmokeTestPluginsSslIT.java @@ -14,7 +14,7 @@ import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.RestTestCandidate; -import org.elasticsearch.test.rest.client.RestClient; +import org.elasticsearch.test.rest.client.RestTestClient; import org.elasticsearch.test.rest.parser.RestTestParseException; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -65,9 +65,9 @@ public class SmokeTestPluginsSslIT extends ESRestTestCase { String token = basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray())); return Settings.builder() .put(ThreadContext.PREFIX + ".Authorization", token) - .put(RestClient.PROTOCOL, "https") - .put(RestClient.TRUSTSTORE_PATH, keyStore) - .put(RestClient.TRUSTSTORE_PASSWORD, KEYSTORE_PASS) + .put(RestTestClient.PROTOCOL, "https") + .put(RestTestClient.TRUSTSTORE_PATH, keyStore) + .put(RestTestClient.TRUSTSTORE_PASSWORD, KEYSTORE_PASS) .build(); } } diff --git a/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java b/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java index 675834e9245..5bda0f4e9c0 100644 --- a/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java +++ b/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java @@ -5,15 +5,6 @@ */ package org.elasticsearch.xpack.test.rest; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URI; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.List; -import java.util.Map; - import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; import org.apache.http.client.methods.CloseableHttpResponse; @@ -40,9 +31,19 @@ import org.elasticsearch.test.rest.parser.RestTestParseException; import org.junit.After; import org.junit.Before; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.List; +import java.util.Map; + import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; import static org.hamcrest.Matchers.is; + public abstract class XPackRestTestCase extends ESRestTestCase { private static final String BASIC_AUTH_VALUE = basicAuthHeaderValue("test_user", new SecuredString("changeme".toCharArray())); @@ -101,6 +102,7 @@ public abstract class XPackRestTestCase extends ESRestTestCase { @After public void clearShieldUsersAndRoles() throws Exception { + //TODO change this to use RestClient, also look for usages of HttpClient directly // we cannot delete the .security index from a rest test since we aren't the internal user, lets wipe the data // TODO remove this once the built-in SUPERUSER role is added that can delete the index and we use the built in admin user here try (CloseableHttpClient client = HttpClients.createMinimal(new BasicHttpClientConnectionManager())) { From 57f8063c3acb00298492acb35c359a70b67caad1 Mon Sep 17 00:00:00 2001 From: javanna Date: Fri, 20 May 2016 11:17:24 +0200 Subject: [PATCH 03/11] update XPackRestTestCase to use low level RestClient Original commit: elastic/x-pack-elasticsearch@8c16c9b06e9a5dc40f9c973da1afed13ea95e5f6 --- .../xpack/test/rest/XPackRestTestCase.java | 102 +++++++----------- 1 file changed, 40 insertions(+), 62 deletions(-) diff --git a/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java b/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java index 5bda0f4e9c0..dd1a23e028d 100644 --- a/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java +++ b/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java @@ -5,15 +5,12 @@ */ package org.elasticsearch.xpack.test.rest; + import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.BasicHttpClientConnectionManager; +import org.apache.http.util.EntityUtils; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.ElasticsearchResponseException; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.Streams; import org.elasticsearch.common.settings.Settings; @@ -24,7 +21,9 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.license.plugin.TestUtils; +import org.elasticsearch.shield.authc.esnative.ReservedRealm; import org.elasticsearch.shield.authc.support.SecuredString; +import org.elasticsearch.shield.authz.store.ReservedRolesStore; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.RestTestCandidate; import org.elasticsearch.test.rest.parser.RestTestParseException; @@ -33,8 +32,6 @@ import org.junit.Before; import java.io.IOException; import java.io.InputStreamReader; -import java.net.URI; -import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; @@ -59,31 +56,17 @@ public abstract class XPackRestTestCase extends ESRestTestCase { @Before public void startWatcher() throws Exception { - try (CloseableHttpClient client = HttpClients.createMinimal(new BasicHttpClientConnectionManager())) { - URL url = getClusterUrls()[0]; - HttpPut request = new HttpPut(new URI("http", - null, - url.getHost(), - url.getPort(), - "/_xpack/watcher/_start", null, null)); - request.addHeader("Authorization", BASIC_AUTH_VALUE); - try (CloseableHttpResponse response = client.execute(request)) { - } + try (ElasticsearchResponse response = getRestClient() + .performRequest("PUT", "/_xpack/watcher/_start", Collections.emptyMap(), null)) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); } } @After public void stopWatcher() throws Exception { - try(CloseableHttpClient client = HttpClients.createMinimal(new BasicHttpClientConnectionManager())) { - URL url = getClusterUrls()[0]; - HttpPut request = new HttpPut(new URI("http", - null, - url.getHost(), - url.getPort(), - "/_xpack/watcher/_stop", null, null)); - request.addHeader("Authorization", BASIC_AUTH_VALUE); - try (CloseableHttpResponse response = client.execute(request)) { - } + try (ElasticsearchResponse response = getRestClient() + .performRequest("PUT", "/_xpack/watcher/_stop", Collections.emptyMap(), null)) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); } } @@ -102,45 +85,40 @@ public abstract class XPackRestTestCase extends ESRestTestCase { @After public void clearShieldUsersAndRoles() throws Exception { - //TODO change this to use RestClient, also look for usages of HttpClient directly // we cannot delete the .security index from a rest test since we aren't the internal user, lets wipe the data // TODO remove this once the built-in SUPERUSER role is added that can delete the index and we use the built in admin user here - try (CloseableHttpClient client = HttpClients.createMinimal(new BasicHttpClientConnectionManager())) { - final URL url = getClusterUrls()[0]; - HttpGet getUsersRequest = new HttpGet(new URI("http", null, url.getHost(), url.getPort(), "/_xpack/security/user", null, null)); - getUsersRequest.addHeader("Authorization", BASIC_AUTH_VALUE); - try (CloseableHttpResponse closeableHttpResponse = client.execute(getUsersRequest)) { - assertThat(closeableHttpResponse.getStatusLine().getStatusCode(), is(200)); - String response = Streams.copyToString( - new InputStreamReader(closeableHttpResponse.getEntity().getContent(), StandardCharsets.UTF_8)); - Map responseMap = XContentFactory.xContent(response).createParser(response).map(); + String response; + try (ElasticsearchResponse elasticsearchResponse = getRestClient() + .performRequest("GET", "/_xpack/security/user", Collections.emptyMap(), null)) { + assertThat(elasticsearchResponse.getStatusLine().getStatusCode(), is(200)); + response = Streams.copyToString(new InputStreamReader(elasticsearchResponse.getEntity().getContent(), StandardCharsets.UTF_8)); + } - // in the structure of this API, the users are the keyset - for (String user : responseMap.keySet()) { - HttpDelete delete = new HttpDelete(new URI("http", null, url.getHost(), url.getPort(), - "/_xpack/security/user/" + user, null, null)); - delete.addHeader("Authorization", BASIC_AUTH_VALUE); - try (CloseableHttpResponse deleteResponse = client.execute(delete)) { - } + Map responseMap = XContentFactory.xContent(response).createParser(response).map(); + // in the structure of this API, the users are the keyset + for (String user : responseMap.keySet()) { + if (ReservedRealm.isReserved(user) == false) { + try (ElasticsearchResponse elasticsearchResponse = getRestClient() + .performRequest("DELETE", "/_xpack/security/user/" + user, Collections.emptyMap(), null)) { + assertThat(EntityUtils.toString(elasticsearchResponse.getEntity()), elasticsearchResponse.getStatusLine().getStatusCode(), is(200)); + } catch(ElasticsearchResponseException e) { + logger.error(e.getResponseBody()); } } + } - HttpGet getRolesRequest = new HttpGet(new URI("http", null, url.getHost(), url.getPort(), "/_xpack/security/role", - null, null)); - getRolesRequest.addHeader("Authorization", BASIC_AUTH_VALUE); - try (CloseableHttpResponse closeableHttpResponse = client.execute(getRolesRequest)) { - assertThat(closeableHttpResponse.getStatusLine().getStatusCode(), is(200)); - String response = Streams.copyToString( - new InputStreamReader(closeableHttpResponse.getEntity().getContent(), StandardCharsets.UTF_8)); - Map responseMap = XContentFactory.xContent(response).createParser(response).map(); - - // in the structure of this API, the users are the keyset - for (String role : responseMap.keySet()) { - HttpDelete delete = new HttpDelete(new URI("http", null, url.getHost(), url.getPort(), - "/_xpack/security/role/" + role, null, null)); - delete.addHeader("Authorization", BASIC_AUTH_VALUE); - try (CloseableHttpResponse deleteResponse = client.execute(delete)) { - } + try (ElasticsearchResponse elasticsearchResponse = getRestClient() + .performRequest("GET", "/_xpack/security/role", Collections.emptyMap(), null)) { + assertThat(elasticsearchResponse.getStatusLine().getStatusCode(), is(200)); + response = Streams.copyToString(new InputStreamReader(elasticsearchResponse.getEntity().getContent(), StandardCharsets.UTF_8)); + } + responseMap = XContentFactory.xContent(response).createParser(response).map(); + // in the structure of this API, the roles are the keyset + for (String role : responseMap.keySet()) { + if (ReservedRolesStore.isReserved(role) == false) { + try (ElasticsearchResponse elasticsearchResponse = getRestClient() + .performRequest("DELETE", "/_xpack/security/role/" + role, Collections.emptyMap(), null)) { + assertThat(elasticsearchResponse.getStatusLine().getStatusCode(), is(200)); } } } From 4e2766df11758d238b0593ab5ce41130da13d779 Mon Sep 17 00:00:00 2001 From: javanna Date: Fri, 20 May 2016 11:32:02 +0200 Subject: [PATCH 04/11] replace some more usage of HttpClient with RestClient Original commit: elastic/x-pack-elasticsearch@a3cb53b7a06d517eaf6e131d94037e8ad7a85500 --- .../smoketest/GraphWithShieldIT.java | 16 +---- .../smoketest/WatcherRestTestCase.java | 25 ++----- .../smoketest/WatcherRestTestCase.java | 21 ++---- .../smoketest/WatcherRestTestCase.java | 25 ++----- .../smoketest/WatcherWithShieldIT.java | 29 ++------ .../shield/user/AnonymousUserIntegTests.java | 40 ++++------- .../xpack/test/rest/XPackRestTestCase.java | 70 +++++++------------ 7 files changed, 65 insertions(+), 161 deletions(-) diff --git a/elasticsearch/qa/smoke-test-graph-with-shield/src/test/java/org/elasticsearch/smoketest/GraphWithShieldIT.java b/elasticsearch/qa/smoke-test-graph-with-shield/src/test/java/org/elasticsearch/smoketest/GraphWithShieldIT.java index f86fd8ee11c..71477cee204 100644 --- a/elasticsearch/qa/smoke-test-graph-with-shield/src/test/java/org/elasticsearch/smoketest/GraphWithShieldIT.java +++ b/elasticsearch/qa/smoke-test-graph-with-shield/src/test/java/org/elasticsearch/smoketest/GraphWithShieldIT.java @@ -7,32 +7,18 @@ package org.elasticsearch.smoketest; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; - -import org.apache.http.client.methods.HttpPut; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.BasicHttpClientConnectionManager; -//import org.elasticsearch.client.support.Headers; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; -import org.elasticsearch.plugins.Plugin; -//import org.elasticsearch.shield.ShieldPlugin; import org.elasticsearch.shield.authc.support.SecuredString; -import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.RestTestCandidate; import org.elasticsearch.test.rest.parser.RestTestParseException; -import org.junit.After; -import org.junit.Before; import java.io.IOException; -import java.net.URI; -import java.net.URL; -import java.util.Collection; -import java.util.Collections; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; + public class GraphWithShieldIT extends ESRestTestCase { private final static String TEST_ADMIN_USERNAME = "test_admin"; diff --git a/elasticsearch/qa/smoke-test-watcher-with-groovy/src/test/java/org/elasticsearch/smoketest/WatcherRestTestCase.java b/elasticsearch/qa/smoke-test-watcher-with-groovy/src/test/java/org/elasticsearch/smoketest/WatcherRestTestCase.java index 59430d0b378..af80d098c1c 100644 --- a/elasticsearch/qa/smoke-test-watcher-with-groovy/src/test/java/org/elasticsearch/smoketest/WatcherRestTestCase.java +++ b/elasticsearch/qa/smoke-test-watcher-with-groovy/src/test/java/org/elasticsearch/smoketest/WatcherRestTestCase.java @@ -5,22 +5,19 @@ */ package org.elasticsearch.smoketest; -import java.io.IOException; -import java.net.URI; -import java.net.URL; - import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.RestTestCandidate; import org.elasticsearch.test.rest.parser.RestTestParseException; import org.junit.After; import org.junit.Before; +import java.io.IOException; + +import static java.util.Collections.emptyList; +import static java.util.Collections.emptyMap; + public abstract class WatcherRestTestCase extends ESRestTestCase { public WatcherRestTestCase(@Name("yaml") RestTestCandidate testCandidate) { @@ -34,19 +31,11 @@ public abstract class WatcherRestTestCase extends ESRestTestCase { @Before public void startWatcher() throws Exception { - try(CloseableHttpClient client = HttpClients.createMinimal(new BasicHttpClientConnectionManager())) { - URL url = getClusterUrls()[0]; - HttpPut request = new HttpPut(new URI("http", null, url.getHost(), url.getPort(), "/_xpack/watcher/_start", null, null)); - client.execute(request); - } + getAdminExecutionContext().callApi("xpack.watcher.start", emptyMap(), emptyList(), emptyMap()); } @After public void stopWatcher() throws Exception { - try(CloseableHttpClient client = HttpClients.createMinimal(new BasicHttpClientConnectionManager())) { - URL url = getClusterUrls()[0]; - HttpPut request = new HttpPut(new URI("http", null, url.getHost(), url.getPort(), "/_xpack/watcher/_stop", null, null)); - client.execute(request); - } + getAdminExecutionContext().callApi("xpack.watcher.stop", emptyMap(), emptyList(), emptyMap()); } } diff --git a/elasticsearch/qa/smoke-test-watcher-with-mustache/src/test/java/org/elasticsearch/smoketest/WatcherRestTestCase.java b/elasticsearch/qa/smoke-test-watcher-with-mustache/src/test/java/org/elasticsearch/smoketest/WatcherRestTestCase.java index 17e0367317e..af80d098c1c 100644 --- a/elasticsearch/qa/smoke-test-watcher-with-mustache/src/test/java/org/elasticsearch/smoketest/WatcherRestTestCase.java +++ b/elasticsearch/qa/smoke-test-watcher-with-mustache/src/test/java/org/elasticsearch/smoketest/WatcherRestTestCase.java @@ -7,10 +7,6 @@ package org.elasticsearch.smoketest; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.RestTestCandidate; import org.elasticsearch.test.rest.parser.RestTestParseException; @@ -18,8 +14,9 @@ import org.junit.After; import org.junit.Before; import java.io.IOException; -import java.net.URI; -import java.net.URL; + +import static java.util.Collections.emptyList; +import static java.util.Collections.emptyMap; public abstract class WatcherRestTestCase extends ESRestTestCase { @@ -34,19 +31,11 @@ public abstract class WatcherRestTestCase extends ESRestTestCase { @Before public void startWatcher() throws Exception { - try(CloseableHttpClient client = HttpClients.createMinimal(new BasicHttpClientConnectionManager())) { - URL url = getClusterUrls()[0]; - HttpPut request = new HttpPut(new URI("http", null, url.getHost(), url.getPort(), "/_xpack/watcher/_start", null, null)); - client.execute(request); - } + getAdminExecutionContext().callApi("xpack.watcher.start", emptyMap(), emptyList(), emptyMap()); } @After public void stopWatcher() throws Exception { - try(CloseableHttpClient client = HttpClients.createMinimal(new BasicHttpClientConnectionManager())) { - URL url = getClusterUrls()[0]; - HttpPut request = new HttpPut(new URI("http", null, url.getHost(), url.getPort(), "/_xpack/watcher/_stop", null, null)); - client.execute(request); - } + getAdminExecutionContext().callApi("xpack.watcher.stop", emptyMap(), emptyList(), emptyMap()); } } diff --git a/elasticsearch/qa/smoke-test-watcher-with-painless/src/test/java/org/elasticsearch/smoketest/WatcherRestTestCase.java b/elasticsearch/qa/smoke-test-watcher-with-painless/src/test/java/org/elasticsearch/smoketest/WatcherRestTestCase.java index 59430d0b378..af80d098c1c 100644 --- a/elasticsearch/qa/smoke-test-watcher-with-painless/src/test/java/org/elasticsearch/smoketest/WatcherRestTestCase.java +++ b/elasticsearch/qa/smoke-test-watcher-with-painless/src/test/java/org/elasticsearch/smoketest/WatcherRestTestCase.java @@ -5,22 +5,19 @@ */ package org.elasticsearch.smoketest; -import java.io.IOException; -import java.net.URI; -import java.net.URL; - import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.RestTestCandidate; import org.elasticsearch.test.rest.parser.RestTestParseException; import org.junit.After; import org.junit.Before; +import java.io.IOException; + +import static java.util.Collections.emptyList; +import static java.util.Collections.emptyMap; + public abstract class WatcherRestTestCase extends ESRestTestCase { public WatcherRestTestCase(@Name("yaml") RestTestCandidate testCandidate) { @@ -34,19 +31,11 @@ public abstract class WatcherRestTestCase extends ESRestTestCase { @Before public void startWatcher() throws Exception { - try(CloseableHttpClient client = HttpClients.createMinimal(new BasicHttpClientConnectionManager())) { - URL url = getClusterUrls()[0]; - HttpPut request = new HttpPut(new URI("http", null, url.getHost(), url.getPort(), "/_xpack/watcher/_start", null, null)); - client.execute(request); - } + getAdminExecutionContext().callApi("xpack.watcher.start", emptyMap(), emptyList(), emptyMap()); } @After public void stopWatcher() throws Exception { - try(CloseableHttpClient client = HttpClients.createMinimal(new BasicHttpClientConnectionManager())) { - URL url = getClusterUrls()[0]; - HttpPut request = new HttpPut(new URI("http", null, url.getHost(), url.getPort(), "/_xpack/watcher/_stop", null, null)); - client.execute(request); - } + getAdminExecutionContext().callApi("xpack.watcher.stop", emptyMap(), emptyList(), emptyMap()); } } diff --git a/elasticsearch/qa/smoke-test-watcher-with-shield/src/test/java/org/elasticsearch/smoketest/WatcherWithShieldIT.java b/elasticsearch/qa/smoke-test-watcher-with-shield/src/test/java/org/elasticsearch/smoketest/WatcherWithShieldIT.java index a541b3776d9..5860b38efea 100644 --- a/elasticsearch/qa/smoke-test-watcher-with-shield/src/test/java/org/elasticsearch/smoketest/WatcherWithShieldIT.java +++ b/elasticsearch/qa/smoke-test-watcher-with-shield/src/test/java/org/elasticsearch/smoketest/WatcherWithShieldIT.java @@ -5,26 +5,21 @@ */ package org.elasticsearch.smoketest; -import java.io.IOException; -import java.net.URI; -import java.net.URL; - import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.shield.authc.support.SecuredString; -import org.elasticsearch.shield.authc.support.UsernamePasswordToken; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.RestTestCandidate; import org.elasticsearch.test.rest.parser.RestTestParseException; import org.junit.After; import org.junit.Before; +import java.io.IOException; + +import static java.util.Collections.emptyList; +import static java.util.Collections.emptyMap; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; public class WatcherWithShieldIT extends ESRestTestCase { @@ -43,24 +38,12 @@ public class WatcherWithShieldIT extends ESRestTestCase { @Before public void startWatcher() throws Exception { - try(CloseableHttpClient client = HttpClients.createMinimal(new BasicHttpClientConnectionManager())) { - URL url = getClusterUrls()[0]; - HttpPut request = new HttpPut(new URI("http", null, url.getHost(), url.getPort(), "/_xpack/watcher/_start", null, null)); - String token = basicAuthHeaderValue(TEST_ADMIN_USERNAME, new SecuredString(TEST_ADMIN_PASSWORD.toCharArray())); - request.addHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, token); - client.execute(request); - } + getAdminExecutionContext().callApi("xpack.watcher.start", emptyMap(), emptyList(), emptyMap()); } @After public void stopWatcher() throws Exception { - try(CloseableHttpClient client = HttpClients.createMinimal(new BasicHttpClientConnectionManager())) { - URL url = getClusterUrls()[0]; - HttpPut request = new HttpPut(new URI("http", null, url.getHost(), url.getPort(), "/_xpack/watcher/_stop", null, null)); - String token = basicAuthHeaderValue(TEST_ADMIN_USERNAME, new SecuredString(TEST_ADMIN_PASSWORD.toCharArray())); - request.addHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, token); - client.execute(request); - } + getAdminExecutionContext().callApi("xpack.watcher.stop", emptyMap(), emptyList(), emptyMap()); } @Override diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java index db701be1b1f..0b8b8036e4d 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java @@ -5,25 +5,17 @@ */ package org.elasticsearch.shield.user; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.elasticsearch.common.io.Streams; +import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.transport.InetSocketTransportAddress; -import org.elasticsearch.common.transport.TransportAddress; -import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.shield.authz.InternalAuthorizationService; import org.elasticsearch.test.ShieldIntegTestCase; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.Locale; +import java.util.Collections; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; @@ -51,28 +43,22 @@ public class AnonymousUserIntegTests extends ShieldIntegTestCase { } public void testAnonymousViaHttp() throws Exception { - try (CloseableHttpClient client = HttpClients.createDefault(); - CloseableHttpResponse response = client.execute(new HttpGet(getNodeUrl() + "_nodes"))) { - int statusCode = response.getStatusLine().getStatusCode(); - String data = Streams.copyToString(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)); + try (RestClient restClient = restClient()) { + restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + int statusCode = e.getElasticsearchResponse().getStatusLine().getStatusCode(); + ElasticsearchResponse response = e.getElasticsearchResponse(); if (authorizationExceptionsEnabled) { assertThat(statusCode, is(403)); assertThat(response.getFirstHeader("WWW-Authenticate"), nullValue()); - assertThat(data, containsString("security_exception")); + assertThat(e.getResponseBody(), containsString("security_exception")); } else { assertThat(statusCode, is(401)); assertThat(response.getFirstHeader("WWW-Authenticate"), notNullValue()); - assertThat(response.getFirstHeader("WWW-Authenticate").getValue(), containsString("Basic")); - assertThat(data, containsString("security_exception")); + assertThat(response.getFirstHeader("WWW-Authenticate"), containsString("Basic")); + assertThat(e.getResponseBody(), containsString("security_exception")); } } } - - private String getNodeUrl() { - TransportAddress transportAddress = - randomFrom(internalCluster().getInstance(HttpServerTransport.class).boundAddress().boundAddresses()); - assertThat(transportAddress, is(instanceOf(InetSocketTransportAddress.class))); - InetSocketTransportAddress inetSocketTransportAddress = (InetSocketTransportAddress) transportAddress; - return String.format(Locale.ROOT, "http://%s:%s/", "localhost", inetSocketTransportAddress.address().getPort()); - } } diff --git a/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java b/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java index dd1a23e028d..0dedb417891 100644 --- a/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java +++ b/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java @@ -8,11 +8,8 @@ package org.elasticsearch.xpack.test.rest; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import org.apache.http.util.EntityUtils; -import org.elasticsearch.client.ElasticsearchResponse; import org.elasticsearch.client.ElasticsearchResponseException; import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.common.io.Streams; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ThreadContext; @@ -26,19 +23,20 @@ import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authz.store.ReservedRolesStore; import org.elasticsearch.test.rest.ESRestTestCase; import org.elasticsearch.test.rest.RestTestCandidate; +import org.elasticsearch.test.rest.client.RestTestResponse; import org.elasticsearch.test.rest.parser.RestTestParseException; import org.junit.After; import org.junit.Before; import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.Collections; import java.util.List; import java.util.Map; +import static java.util.Collections.emptyList; +import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonList; +import static java.util.Collections.singletonMap; import static org.elasticsearch.shield.authc.support.UsernamePasswordToken.basicAuthHeaderValue; -import static org.hamcrest.Matchers.is; public abstract class XPackRestTestCase extends ESRestTestCase { @@ -56,17 +54,19 @@ public abstract class XPackRestTestCase extends ESRestTestCase { @Before public void startWatcher() throws Exception { - try (ElasticsearchResponse response = getRestClient() - .performRequest("PUT", "/_xpack/watcher/_start", Collections.emptyMap(), null)) { - assertThat(response.getStatusLine().getStatusCode(), is(200)); + try { + getAdminExecutionContext().callApi("xpack.watcher.start", emptyMap(), emptyList(), emptyMap()); + } catch(ElasticsearchResponseException e) { + //TODO ignore for now, needs to be fixed though } } @After public void stopWatcher() throws Exception { - try (ElasticsearchResponse response = getRestClient() - .performRequest("PUT", "/_xpack/watcher/_stop", Collections.emptyMap(), null)) { - assertThat(response.getStatusLine().getStatusCode(), is(200)); + try { + getAdminExecutionContext().callApi("xpack.watcher.stop", emptyMap(), emptyList(), emptyMap()); + } catch(ElasticsearchResponseException e) { + //TODO ignore for now, needs to be fixed though } } @@ -76,10 +76,10 @@ public abstract class XPackRestTestCase extends ESRestTestCase { TestUtils.generateSignedLicense("trial", TimeValue.timeValueHours(2)).toXContent(builder, ToXContent.EMPTY_PARAMS); final BytesReference bytes = builder.bytes(); try (XContentParser parser = XContentFactory.xContent(bytes).createParser(bytes)) { - final List> bodies = Collections.singletonList(Collections.singletonMap("license", + final List> bodies = singletonList(singletonMap("license", parser.map())); - getAdminExecutionContext().callApi("license.post", Collections.singletonMap("acknowledge", "true"), - bodies, Collections.singletonMap("Authorization", BASIC_AUTH_VALUE)); + getAdminExecutionContext().callApi("license.post", singletonMap("acknowledge", "true"), + bodies, singletonMap("Authorization", BASIC_AUTH_VALUE)); } } @@ -87,39 +87,21 @@ public abstract class XPackRestTestCase extends ESRestTestCase { public void clearShieldUsersAndRoles() throws Exception { // we cannot delete the .security index from a rest test since we aren't the internal user, lets wipe the data // TODO remove this once the built-in SUPERUSER role is added that can delete the index and we use the built in admin user here - String response; - try (ElasticsearchResponse elasticsearchResponse = getRestClient() - .performRequest("GET", "/_xpack/security/user", Collections.emptyMap(), null)) { - assertThat(elasticsearchResponse.getStatusLine().getStatusCode(), is(200)); - response = Streams.copyToString(new InputStreamReader(elasticsearchResponse.getEntity().getContent(), StandardCharsets.UTF_8)); - } - - Map responseMap = XContentFactory.xContent(response).createParser(response).map(); - // in the structure of this API, the users are the keyset - for (String user : responseMap.keySet()) { + RestTestResponse response = getAdminExecutionContext().callApi("xpack.security.get_user", emptyMap(), emptyList(), emptyMap()); + @SuppressWarnings("unchecked") + Map users = (Map) response.getBody(); + for (String user: users.keySet()) { if (ReservedRealm.isReserved(user) == false) { - try (ElasticsearchResponse elasticsearchResponse = getRestClient() - .performRequest("DELETE", "/_xpack/security/user/" + user, Collections.emptyMap(), null)) { - assertThat(EntityUtils.toString(elasticsearchResponse.getEntity()), elasticsearchResponse.getStatusLine().getStatusCode(), is(200)); - } catch(ElasticsearchResponseException e) { - logger.error(e.getResponseBody()); - } + getAdminExecutionContext().callApi("xpack.security.delete_user", singletonMap("username", user), emptyList(), emptyMap()); } } - try (ElasticsearchResponse elasticsearchResponse = getRestClient() - .performRequest("GET", "/_xpack/security/role", Collections.emptyMap(), null)) { - assertThat(elasticsearchResponse.getStatusLine().getStatusCode(), is(200)); - response = Streams.copyToString(new InputStreamReader(elasticsearchResponse.getEntity().getContent(), StandardCharsets.UTF_8)); - } - responseMap = XContentFactory.xContent(response).createParser(response).map(); - // in the structure of this API, the roles are the keyset - for (String role : responseMap.keySet()) { + response = getAdminExecutionContext().callApi("xpack.security.get_role", emptyMap(), emptyList(), emptyMap()); + @SuppressWarnings("unchecked") + Map roles = (Map) response.getBody(); + for (String role: roles.keySet()) { if (ReservedRolesStore.isReserved(role) == false) { - try (ElasticsearchResponse elasticsearchResponse = getRestClient() - .performRequest("DELETE", "/_xpack/security/role/" + role, Collections.emptyMap(), null)) { - assertThat(elasticsearchResponse.getStatusLine().getStatusCode(), is(200)); - } + getAdminExecutionContext().callApi("xpack.security.delete_role", singletonMap("name", role), emptyList(), emptyMap()); } } } From ad9a64e85428573c43ea372a51a1828da7570272 Mon Sep 17 00:00:00 2001 From: javanna Date: Fri, 3 Jun 2016 16:42:06 +0200 Subject: [PATCH 05/11] [TEST] add a lot of forgotten try with resources to wrap ElasticsearchResponses Original commit: elastic/x-pack-elasticsearch@e4634ea59940eae319108312596213320fb535ed --- .../shield/audit/IndexAuditIT.java | 7 ++- .../example/realm/CustomRealmIT.java | 7 ++- .../shield/MarvelSettingsFilterTests.java | 28 +++++----- .../AbstractPrivilegeTestCase.java | 13 +++-- .../integration/BulkUpdateTests.java | 47 +++++++++------- .../integration/ClearRealmsCacheTests.java | 9 +-- .../integration/ClearRolesCacheTests.java | 7 ++- .../integration/LicensingTests.java | 7 ++- .../shield/ShieldPluginTests.java | 7 ++- .../shield/authc/RunAsIntegTests.java | 7 ++- .../authc/pki/PkiOptionalClientAuthTests.java | 7 ++- .../PkiWithoutClientAuthenticationTests.java | 7 ++- .../shield/authc/pki/PkiWithoutSSLTests.java | 7 ++- .../action/RestAuthenticateActionTests.java | 56 ++++++++++--------- .../transport/ssl/SslClientAuthTests.java | 9 +-- .../WatcherSettingsFilterTests.java | 20 ++++--- 16 files changed, 136 insertions(+), 109 deletions(-) diff --git a/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java b/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java index 3f50acc809c..96e9359092a 100644 --- a/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java +++ b/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java @@ -39,10 +39,11 @@ public class IndexAuditIT extends ESIntegTestCase { public void testShieldIndexAuditTrailWorking() throws Exception { try (RestClient restClient = restClient()) { - ElasticsearchResponse response = restClient.performRequest("GET", "/_cluster/health", Collections.emptyMap(), null, + try (ElasticsearchResponse response = restClient.performRequest("GET", "/_cluster/health", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray())))); - assertThat(response.getStatusLine().getStatusCode(), is(200)); + UsernamePasswordToken.basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray()))))) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); + } } final AtomicReference lastClusterState = new AtomicReference<>(); diff --git a/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java b/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java index 0ff3537e54a..73850d50a66 100644 --- a/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java +++ b/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java @@ -59,10 +59,11 @@ public class CustomRealmIT extends ESIntegTestCase { public void testHttpAuthentication() throws Exception { try (RestClient restClient = restClient()) { - ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null, + try (ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null, new BasicHeader(CustomRealm.USER_HEADER, CustomRealm.KNOWN_USER), - new BasicHeader(CustomRealm.PW_HEADER, CustomRealm.KNOWN_PW)); - assertThat(response.getStatusLine().getStatusCode(), is(200)); + new BasicHeader(CustomRealm.PW_HEADER, CustomRealm.KNOWN_PW))) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); + } } } diff --git a/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java b/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java index 1d7426060c0..36ea1a6a24a 100644 --- a/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java +++ b/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java @@ -54,20 +54,22 @@ public class MarvelSettingsFilterTests extends MarvelIntegTestCase { } else { headers = new Header[0]; } - ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes/settings", Collections.emptyMap(), null, headers); - Map responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); - @SuppressWarnings("unchecked") - Map nodes = (Map) responseMap.get("nodes"); - for (Object node : nodes.values()) { + try (ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes/settings", + Collections.emptyMap(), null, headers)) { + Map responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); @SuppressWarnings("unchecked") - Map settings = (Map) ((Map) node).get("settings"); - assertThat(extractValue("xpack.monitoring.agent.exporters._http.type", settings), Matchers.equalTo("http")); - assertThat(extractValue("xpack.monitoring.agent.exporters._http.enabled", settings), Matchers.equalTo("false")); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.auth.username"); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.auth.password"); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.truststore.path"); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.truststore.password"); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.hostname_verification"); + Map nodes = (Map) responseMap.get("nodes"); + for (Object node : nodes.values()) { + @SuppressWarnings("unchecked") + Map settings = (Map) ((Map) node).get("settings"); + assertThat(extractValue("xpack.monitoring.agent.exporters._http.type", settings), Matchers.equalTo("http")); + assertThat(extractValue("xpack.monitoring.agent.exporters._http.enabled", settings), Matchers.equalTo("false")); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.auth.username"); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.auth.password"); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.truststore.path"); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.truststore.password"); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.hostname_verification"); + } } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java index 20e76bf1031..b18bd6baaf1 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java @@ -37,13 +37,14 @@ public abstract class AbstractPrivilegeTestCase extends ShieldIntegTestCase { protected void assertAccessIsAllowed(String user, String method, String uri, String body, Map params) throws IOException { try (RestClient restClient = restClient()) { - ElasticsearchResponse response = restClient.performRequest(method, uri, params, entityOrNull(body), + try (ElasticsearchResponse response = restClient.performRequest(method, uri, params, entityOrNull(body), new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray())))); - StatusLine statusLine = response.getStatusLine(); - String message = String.format(Locale.ROOT, "%s %s: Expected no error got %s %s with body %s", method, uri, - statusLine.getStatusCode(), statusLine.getReasonPhrase(), EntityUtils.toString(response.getEntity())); - assertThat(message, statusLine.getStatusCode(), is(not(greaterThanOrEqualTo(400)))); + UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray()))))) { + StatusLine statusLine = response.getStatusLine(); + String message = String.format(Locale.ROOT, "%s %s: Expected no error got %s %s with body %s", method, uri, + statusLine.getStatusCode(), statusLine.getReasonPhrase(), EntityUtils.toString(response.getEntity())); + assertThat(message, statusLine.getStatusCode(), is(not(greaterThanOrEqualTo(400)))); + } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java index 50590bb7bbc..56cd09794d4 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java @@ -81,12 +81,15 @@ public class BulkUpdateTests extends ShieldIntegTestCase { try (RestClient restClient = restClient()) { StringEntity body = new StringEntity("{\"test\":\"test\"}", RestClient.JSON_CONTENT_TYPE); - ElasticsearchResponse response = restClient.performRequest("PUT", path, Collections.emptyMap(), body, basicAuthHeader); - assertThat(response.getStatusLine().getStatusCode(), equalTo(201)); + try (ElasticsearchResponse response = restClient.performRequest("PUT", path, Collections.emptyMap(), body, basicAuthHeader)) { + assertThat(response.getStatusLine().getStatusCode(), equalTo(201)); + } + + try (ElasticsearchResponse response = restClient.performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(EntityUtils.toString(response.getEntity()), containsString("\"test\":\"test\"")); + } - response = restClient.performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - assertThat(EntityUtils.toString(response.getEntity()), containsString("\"test\":\"test\"")); if (randomBoolean()) { flushAndRefresh(); @@ -94,14 +97,17 @@ public class BulkUpdateTests extends ShieldIntegTestCase { //update with new field body = new StringEntity("{\"doc\": {\"not test\": \"not test\"}}", RestClient.JSON_CONTENT_TYPE); - response = restClient.performRequest("POST", path + "/_update", Collections.emptyMap(), body, basicAuthHeader); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + try (ElasticsearchResponse response = restClient.performRequest("POST", path + "/_update", + Collections.emptyMap(), body, basicAuthHeader)) { + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + } - response = restClient.performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - String responseBody = EntityUtils.toString(response.getEntity()); - assertThat(responseBody, containsString("\"test\":\"test\"")); - assertThat(responseBody, containsString("\"not test\":\"not test\"")); + try (ElasticsearchResponse response = restClient.performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + String responseBody = EntityUtils.toString(response.getEntity()); + assertThat(responseBody, containsString("\"test\":\"test\"")); + assertThat(responseBody, containsString("\"not test\":\"not test\"")); + } // this part is important. Without this, the document may be read from the translog which would bypass the bug where // FLS kicks in because the request can't be found and only returns meta fields @@ -109,14 +115,17 @@ public class BulkUpdateTests extends ShieldIntegTestCase { body = new StringEntity("{\"update\": {\"_index\": \"index1\", \"_type\": \"type\", \"_id\": \"1\"}}\n" + "{\"doc\": {\"bulk updated\":\"bulk updated\"}}\n", RestClient.JSON_CONTENT_TYPE); - response = restClient.performRequest("POST", "/_bulk", Collections.emptyMap(), body, basicAuthHeader); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + try (ElasticsearchResponse response = restClient.performRequest("POST", "/_bulk", + Collections.emptyMap(), body, basicAuthHeader)) { + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + } - response = restClient.performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader); - responseBody = EntityUtils.toString(response.getEntity()); - assertThat(responseBody, containsString("\"test\":\"test\"")); - assertThat(responseBody, containsString("\"not test\":\"not test\"")); - assertThat(responseBody, containsString("\"bulk updated\":\"bulk updated\"")); + try (ElasticsearchResponse response = restClient.performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { + String responseBody = EntityUtils.toString(response.getEntity()); + assertThat(responseBody, containsString("\"test\":\"test\"")); + assertThat(responseBody, containsString("\"not test\":\"not test\"")); + assertThat(responseBody, containsString("\"bulk updated\":\"bulk updated\"")); + } } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java index 241309fc6c5..015f37bd7f0 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java @@ -167,12 +167,13 @@ public class ClearRealmsCacheTests extends ShieldIntegTestCase { static void executeHttpRequest(String path, Map params) throws Exception { try (RestClient restClient = restClient()) { - ElasticsearchResponse response = restClient.performRequest("POST", path, params, null, + try (ElasticsearchResponse response = restClient.performRequest("POST", path, params, null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); - assertNotNull(response.getEntity()); - assertTrue(EntityUtils.toString(response.getEntity()).contains("cluster_name")); + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { + assertNotNull(response.getEntity()); + assertTrue(EntityUtils.toString(response.getEntity()).contains("cluster_name")); + } } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java index ae3cdd7db8c..63f7187acb3 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java @@ -138,11 +138,12 @@ public class ClearRolesCacheTests extends NativeRealmIntegTestCase { path = "/_xpack/security/role/" + Strings.arrayToCommaDelimitedString(rolesToClear) + "/_clear_cache"; } try (RestClient restClient = restClient()) { - ElasticsearchResponse response = restClient.performRequest("POST", path, Collections.emptyMap(), null, + try (ElasticsearchResponse response = restClient.performRequest("POST", path, Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); - assertThat(response.getStatusLine().getStatusCode(), is(RestStatus.OK.getStatus())); + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { + assertThat(response.getStatusLine().getStatusCode(), is(RestStatus.OK.getStatus())); + } } } else { securityClient.prepareClearRolesCache().names(rolesToClear).get(); diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java index fa555000938..4285cd2b4ff 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java @@ -198,9 +198,10 @@ public class LicensingTests extends ShieldIntegTestCase { public void testRestAuthenticationByLicenseType() throws Exception { try (RestClient restClient = restClient()) { - ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null); - // the default of the licensing tests is basic - assertThat(response.getStatusLine().getStatusCode(), is(200)); + try (ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null)) { + // the default of the licensing tests is basic + assertThat(response.getStatusLine().getStatusCode(), is(200)); + } // generate a new license with a mode that enables auth OperationMode mode = randomFrom(OperationMode.GOLD, OperationMode.TRIAL, OperationMode.PLATINUM, OperationMode.STANDARD); diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java index 7d8ac262c3f..6ca7c04d67b 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java @@ -44,11 +44,12 @@ public class ShieldPluginTests extends ShieldIntegTestCase { } logger.info("executing authorized request to /_xpack infos"); - ElasticsearchResponse response = restClient.performRequest("GET", "/_xpack", Collections.emptyMap(), null, + try (ElasticsearchResponse response = restClient.performRequest("GET", "/_xpack", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); - assertThat(response.getStatusLine().getStatusCode(), is(OK.getStatus())); + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { + assertThat(response.getStatusLine().getStatusCode(), is(OK.getStatus())); + } } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java index a1a75f2d1ec..e2599cc6f85 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java @@ -142,12 +142,13 @@ public class RunAsIntegTests extends ShieldIntegTestCase { } // but when running as a different user it should work - ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + try (ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), - new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, ShieldSettingsSource.DEFAULT_USER_NAME)); - assertThat(response.getStatusLine().getStatusCode(), is(200)); + new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, ShieldSettingsSource.DEFAULT_USER_NAME))) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); + } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java index 5198454adc0..2f81cee337b 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java @@ -89,11 +89,12 @@ public class PkiOptionalClientAuthTests extends ShieldIntegTestCase { assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); } - ElasticsearchResponse response = restClient.performRequest("GET", "_nodes", Collections.emptyMap(), null, + try (ElasticsearchResponse response = restClient.performRequest("GET", "_nodes", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); - assertThat(response.getStatusLine().getStatusCode(), is(200)); + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); + } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java index 7026062188f..924336336ac 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java @@ -81,11 +81,12 @@ public class PkiWithoutClientAuthenticationTests extends ShieldIntegTestCase { sc.init(null, trustAllCerts, new SecureRandom()); CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sc).build(); try (RestClient restClient = restClient(httpClient, "https")) { - ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + try (ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); - assertThat(response.getStatusLine().getStatusCode(), is(200)); + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); + } } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java index 33bd6b423e2..004cf0019cd 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java @@ -45,11 +45,12 @@ public class PkiWithoutSSLTests extends ShieldIntegTestCase { public void testThatHttpWorks() throws Exception { try (RestClient restClient = restClient()) { - ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + try (ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); - assertThat(response.getStatusLine().getStatusCode(), is(200)); + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); + } } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java index 4ec2040d1cc..281ac582f29 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java @@ -53,39 +53,41 @@ public class RestAuthenticateActionTests extends ShieldIntegTestCase { public void testAuthenticateApi() throws Exception { try (RestClient restClient = restClient()) { - ElasticsearchResponse response = restClient.performRequest("GET", "/_xpack/security/_authenticate", Collections.emptyMap(), + try (ElasticsearchResponse response = restClient.performRequest("GET", "/_xpack/security/_authenticate", Collections.emptyMap(), null, new BasicHeader("Authorization", basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray())))); - assertThat(response.getStatusLine().getStatusCode(), is(200)); - JsonPath jsonPath = new JsonPath(EntityUtils.toString(response.getEntity())); - assertThat(jsonPath.evaluate("username").toString(), equalTo(ShieldSettingsSource.DEFAULT_USER_NAME)); - @SuppressWarnings("unchecked") - List roles = (List) jsonPath.evaluate("roles"); - assertThat(roles.size(), is(1)); - assertThat(roles, contains(ShieldSettingsSource.DEFAULT_ROLE)); + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); + JsonPath jsonPath = new JsonPath(EntityUtils.toString(response.getEntity())); + assertThat(jsonPath.evaluate("username").toString(), equalTo(ShieldSettingsSource.DEFAULT_USER_NAME)); + @SuppressWarnings("unchecked") + List roles = (List) jsonPath.evaluate("roles"); + assertThat(roles.size(), is(1)); + assertThat(roles, contains(ShieldSettingsSource.DEFAULT_ROLE)); + } } } public void testAuthenticateApiWithoutAuthentication() throws Exception { try (RestClient restClient = restClient()) { - ElasticsearchResponse response = restClient.performRequest("GET", "/_xpack/security/_authenticate", - Collections.emptyMap(), null); - if (anonymousEnabled) { - assertThat(response.getStatusLine().getStatusCode(), is(200)); - JsonPath jsonPath = new JsonPath(EntityUtils.toString(response.getEntity())); - assertThat(jsonPath.evaluate("username").toString(), equalTo("anon")); - @SuppressWarnings("unchecked") - List roles = (List) jsonPath.evaluate("roles"); - assertThat(roles.size(), is(2)); - assertThat(roles, contains(ShieldSettingsSource.DEFAULT_ROLE, "foo")); - } else { - fail("request should have failed"); - } - } catch(ElasticsearchResponseException e) { - if (anonymousEnabled) { - fail("request should have succeeded"); - } else { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); + try (ElasticsearchResponse response = restClient.performRequest("GET", "/_xpack/security/_authenticate", + Collections.emptyMap(), null)) { + if (anonymousEnabled) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); + JsonPath jsonPath = new JsonPath(EntityUtils.toString(response.getEntity())); + assertThat(jsonPath.evaluate("username").toString(), equalTo("anon")); + @SuppressWarnings("unchecked") + List roles = (List) jsonPath.evaluate("roles"); + assertThat(roles.size(), is(2)); + assertThat(roles, contains(ShieldSettingsSource.DEFAULT_ROLE, "foo")); + } else { + fail("request should have failed"); + } + } catch(ElasticsearchResponseException e) { + if (anonymousEnabled) { + fail("request should have succeeded"); + } else { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); + } } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java index 5f18c7eb4e3..e03d4f7f1ec 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java @@ -83,10 +83,11 @@ public class SslClientAuthTests extends ShieldIntegTestCase { CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); try (RestClient restClient = restClient(client, "https")) { - ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null, - new BasicHeader("Authorization", basicAuthHeaderValue(transportClientUsername(), transportClientPassword()))); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - assertThat(EntityUtils.toString(response.getEntity()), containsString("You Know, for Search")); + try (ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null, + new BasicHeader("Authorization", basicAuthHeaderValue(transportClientUsername(), transportClientPassword())))) { + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(EntityUtils.toString(response.getEntity()), containsString("You Know, for Search")); + } } } diff --git a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java index 303e844b5d5..84022c36164 100644 --- a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java +++ b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java @@ -63,15 +63,17 @@ public class WatcherSettingsFilterTests extends AbstractWatcherIntegrationTestCa } else { headers = new Header[0]; } - ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes/settings", Collections.emptyMap(), null, headers); - Map responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); - Map nodes = (Map) responseMap.get("nodes"); - for (Object node : nodes.values()) { - Map settings = (Map) ((Map) node).get("settings"); - assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.user", settings), - is((Object) "_user")); - assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.password", settings), - nullValue()); + try (ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes/settings", + Collections.emptyMap(), null, headers)) { + Map responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); + Map nodes = (Map) responseMap.get("nodes"); + for (Object node : nodes.values()) { + Map settings = (Map) ((Map) node).get("settings"); + assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.user", settings), + is((Object) "_user")); + assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.password", settings), + nullValue()); + } } } } From 601169833bff00b4df166466c9d18a2fd665de2a Mon Sep 17 00:00:00 2001 From: javanna Date: Fri, 3 Jun 2016 17:09:43 +0200 Subject: [PATCH 06/11] [TEST] remove usage of deprecated apis Original commit: elastic/x-pack-elasticsearch@4f4af3f5c5f118c45f9c7cad2ddb3009eb8164da --- .../shield/authc/pki/PkiOptionalClientAuthTests.java | 2 +- .../shield/authc/pki/PkiWithoutClientAuthenticationTests.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java index 2f81cee337b..1684052fe0e 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java @@ -80,7 +80,7 @@ public class PkiOptionalClientAuthTests extends ShieldIntegTestCase { } public void testRestClientWithoutClientCertificate() throws Exception { - CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(getSSLContext()).build(); + CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(getSSLContext()).build(); try (RestClient restClient = restClient(httpClient, "https")) { try { restClient.performRequest("GET", "_nodes", Collections.emptyMap(), null); diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java index 924336336ac..c8be61d519a 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java @@ -79,7 +79,7 @@ public class PkiWithoutClientAuthenticationTests extends ShieldIntegTestCase { public void testThatHttpWorks() throws Exception { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); - CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sc).build(); + CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sc).build(); try (RestClient restClient = restClient(httpClient, "https")) { try (ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, From e240ca8043100c1593f79ddf3a697ea4b533c14a Mon Sep 17 00:00:00 2001 From: javanna Date: Fri, 3 Jun 2016 18:00:53 +0200 Subject: [PATCH 07/11] [TEST] adapt to "create standard RestClient at first request and reuse it" A RestClient instance is now created whenever EsIntegTestCase#getRestClient is invoked for the first time. It is then kept until the cluster is cleared (depending on the cluster scope of the test). Renamed other two restClient methods to createRestClient, as that instance needs to be closed and managed in the tests. Original commit: elastic/x-pack-elasticsearch@3a9d6f6e906dac005c365fc48cf8f90a24e4d9fc --- .../shield/audit/IndexAuditIT.java | 13 ++- .../example/realm/CustomRealmIT.java | 16 ++-- .../shield/MarvelSettingsFilterTests.java | 49 ++++++----- .../AbstractPrivilegeTestCase.java | 20 +++-- .../integration/BulkUpdateTests.java | 81 +++++++++---------- .../integration/ClearRealmsCacheTests.java | 15 ++-- .../integration/ClearRolesCacheTests.java | 13 ++- .../integration/IndexPrivilegeTests.java | 6 +- .../integration/LicensingTests.java | 27 +++---- .../shield/ShieldPluginTests.java | 29 +++---- .../shield/authc/RunAsIntegTests.java | 66 +++++++-------- .../authc/pki/PkiOptionalClientAuthTests.java | 2 +- .../PkiWithoutClientAuthenticationTests.java | 2 +- .../shield/authc/pki/PkiWithoutSSLTests.java | 13 ++- .../action/RestAuthenticateActionTests.java | 61 +++++++------- .../transport/ssl/SslClientAuthTests.java | 4 +- .../shield/user/AnonymousUserIntegTests.java | 5 +- .../watcher/WatcherPluginDisableTests.java | 5 +- .../WatcherSettingsFilterTests.java | 41 +++++----- 19 files changed, 212 insertions(+), 256 deletions(-) diff --git a/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java b/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java index 96e9359092a..4d728a63ac3 100644 --- a/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java +++ b/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java @@ -10,9 +10,8 @@ import org.apache.http.message.BasicHeader; import org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateResponse; import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.RestClient; +import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexTemplateMetaData; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.query.QueryBuilders; @@ -38,12 +37,10 @@ public class IndexAuditIT extends ESIntegTestCase { private static final String PASS = "changeme"; public void testShieldIndexAuditTrailWorking() throws Exception { - try (RestClient restClient = restClient()) { - try (ElasticsearchResponse response = restClient.performRequest("GET", "/_cluster/health", Collections.emptyMap(), null, - new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray()))))) { - assertThat(response.getStatusLine().getStatusCode(), is(200)); - } + try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_cluster/health", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray()))))) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); } final AtomicReference lastClusterState = new AtomicReference<>(); diff --git a/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java b/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java index 73850d50a66..8bbaf98c7ef 100644 --- a/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java +++ b/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java @@ -11,7 +11,6 @@ import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; import org.elasticsearch.client.ElasticsearchResponse; import org.elasticsearch.client.ElasticsearchResponseException; -import org.elasticsearch.client.RestClient; import org.elasticsearch.client.transport.NoNodeAvailableException; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; @@ -32,6 +31,7 @@ import static org.hamcrest.Matchers.is; * Integration test to test authentication with the custom realm */ public class CustomRealmIT extends ESIntegTestCase { + @Override protected Settings externalClusterClientSettings() { return Settings.builder() @@ -46,8 +46,8 @@ public class CustomRealmIT extends ESIntegTestCase { } public void testHttpConnectionWithNoAuthentication() throws Exception { - try (RestClient restClient = restClient()) { - restClient.performRequest("GET", "/", Collections.emptyMap(), null); + try { + getRestClient().performRequest("GET", "/", Collections.emptyMap(), null); fail("request should have failed"); } catch(ElasticsearchResponseException e) { ElasticsearchResponse response = e.getElasticsearchResponse(); @@ -58,12 +58,10 @@ public class CustomRealmIT extends ESIntegTestCase { } public void testHttpAuthentication() throws Exception { - try (RestClient restClient = restClient()) { - try (ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null, - new BasicHeader(CustomRealm.USER_HEADER, CustomRealm.KNOWN_USER), - new BasicHeader(CustomRealm.PW_HEADER, CustomRealm.KNOWN_PW))) { - assertThat(response.getStatusLine().getStatusCode(), is(200)); - } + try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/", Collections.emptyMap(), null, + new BasicHeader(CustomRealm.USER_HEADER, CustomRealm.KNOWN_USER), + new BasicHeader(CustomRealm.PW_HEADER, CustomRealm.KNOWN_PW))) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); } } diff --git a/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java b/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java index 36ea1a6a24a..ef09ede1b18 100644 --- a/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java +++ b/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java @@ -8,7 +8,6 @@ package org.elasticsearch.marvel.shield; import org.apache.http.Header; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.json.JsonXContent; @@ -44,32 +43,30 @@ public class MarvelSettingsFilterTests extends MarvelIntegTestCase { } public void testGetSettingsFiltered() throws Exception { - try (RestClient restClient = restClient()) { - Header[] headers; - if (shieldEnabled) { - headers = new Header[] { - new BasicHeader(BASIC_AUTH_HEADER, - basicAuthHeaderValue(ShieldSettings.TEST_USERNAME, - new SecuredString(ShieldSettings.TEST_PASSWORD.toCharArray())))}; - } else { - headers = new Header[0]; - } - try (ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes/settings", - Collections.emptyMap(), null, headers)) { - Map responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); + Header[] headers; + if (shieldEnabled) { + headers = new Header[] { + new BasicHeader(BASIC_AUTH_HEADER, + basicAuthHeaderValue(ShieldSettings.TEST_USERNAME, + new SecuredString(ShieldSettings.TEST_PASSWORD.toCharArray())))}; + } else { + headers = new Header[0]; + } + try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_nodes/settings", + Collections.emptyMap(), null, headers)) { + Map responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); + @SuppressWarnings("unchecked") + Map nodes = (Map) responseMap.get("nodes"); + for (Object node : nodes.values()) { @SuppressWarnings("unchecked") - Map nodes = (Map) responseMap.get("nodes"); - for (Object node : nodes.values()) { - @SuppressWarnings("unchecked") - Map settings = (Map) ((Map) node).get("settings"); - assertThat(extractValue("xpack.monitoring.agent.exporters._http.type", settings), Matchers.equalTo("http")); - assertThat(extractValue("xpack.monitoring.agent.exporters._http.enabled", settings), Matchers.equalTo("false")); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.auth.username"); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.auth.password"); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.truststore.path"); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.truststore.password"); - assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.hostname_verification"); - } + Map settings = (Map) ((Map) node).get("settings"); + assertThat(extractValue("xpack.monitoring.agent.exporters._http.type", settings), Matchers.equalTo("http")); + assertThat(extractValue("xpack.monitoring.agent.exporters._http.enabled", settings), Matchers.equalTo("false")); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.auth.username"); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.auth.password"); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.truststore.path"); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.truststore.password"); + assertNullSetting(settings, "xpack.monitoring.agent.exporters._http.ssl.hostname_verification"); } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java index b18bd6baaf1..403d7296956 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java @@ -36,15 +36,13 @@ public abstract class AbstractPrivilegeTestCase extends ShieldIntegTestCase { protected void assertAccessIsAllowed(String user, String method, String uri, String body, Map params) throws IOException { - try (RestClient restClient = restClient()) { - try (ElasticsearchResponse response = restClient.performRequest(method, uri, params, entityOrNull(body), - new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray()))))) { - StatusLine statusLine = response.getStatusLine(); - String message = String.format(Locale.ROOT, "%s %s: Expected no error got %s %s with body %s", method, uri, - statusLine.getStatusCode(), statusLine.getReasonPhrase(), EntityUtils.toString(response.getEntity())); - assertThat(message, statusLine.getStatusCode(), is(not(greaterThanOrEqualTo(400)))); - } + try (ElasticsearchResponse response = getRestClient().performRequest(method, uri, params, entityOrNull(body), + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray()))))) { + StatusLine statusLine = response.getStatusLine(); + String message = String.format(Locale.ROOT, "%s %s: Expected no error got %s %s with body %s", method, uri, + statusLine.getStatusCode(), statusLine.getReasonPhrase(), EntityUtils.toString(response.getEntity())); + assertThat(message, statusLine.getStatusCode(), is(not(greaterThanOrEqualTo(400)))); } } @@ -66,8 +64,8 @@ public abstract class AbstractPrivilegeTestCase extends ShieldIntegTestCase { protected void assertAccessIsDenied(String user, String method, String uri, String body, Map params) throws IOException { - try (RestClient restClient = restClient()) { - restClient.performRequest(method, uri, params, entityOrNull(body), + try { + getRestClient().performRequest(method, uri, params, entityOrNull(body), new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray())))); fail("request should have failed"); diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java index 56cd09794d4..4ca7a37f12d 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java @@ -79,53 +79,50 @@ public class BulkUpdateTests extends ShieldIntegTestCase { UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))); - try (RestClient restClient = restClient()) { - StringEntity body = new StringEntity("{\"test\":\"test\"}", RestClient.JSON_CONTENT_TYPE); - try (ElasticsearchResponse response = restClient.performRequest("PUT", path, Collections.emptyMap(), body, basicAuthHeader)) { - assertThat(response.getStatusLine().getStatusCode(), equalTo(201)); - } + StringEntity body = new StringEntity("{\"test\":\"test\"}", RestClient.JSON_CONTENT_TYPE); + try (ElasticsearchResponse response = getRestClient().performRequest("PUT", path, Collections.emptyMap(), body, basicAuthHeader)) { + assertThat(response.getStatusLine().getStatusCode(), equalTo(201)); + } - try (ElasticsearchResponse response = restClient.performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - assertThat(EntityUtils.toString(response.getEntity()), containsString("\"test\":\"test\"")); - } + try (ElasticsearchResponse response = getRestClient().performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(EntityUtils.toString(response.getEntity()), containsString("\"test\":\"test\"")); + } - - if (randomBoolean()) { - flushAndRefresh(); - } - - //update with new field - body = new StringEntity("{\"doc\": {\"not test\": \"not test\"}}", RestClient.JSON_CONTENT_TYPE); - try (ElasticsearchResponse response = restClient.performRequest("POST", path + "/_update", - Collections.emptyMap(), body, basicAuthHeader)) { - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - } - - try (ElasticsearchResponse response = restClient.performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - String responseBody = EntityUtils.toString(response.getEntity()); - assertThat(responseBody, containsString("\"test\":\"test\"")); - assertThat(responseBody, containsString("\"not test\":\"not test\"")); - } - - // this part is important. Without this, the document may be read from the translog which would bypass the bug where - // FLS kicks in because the request can't be found and only returns meta fields + if (randomBoolean()) { flushAndRefresh(); + } - body = new StringEntity("{\"update\": {\"_index\": \"index1\", \"_type\": \"type\", \"_id\": \"1\"}}\n" + - "{\"doc\": {\"bulk updated\":\"bulk updated\"}}\n", RestClient.JSON_CONTENT_TYPE); - try (ElasticsearchResponse response = restClient.performRequest("POST", "/_bulk", - Collections.emptyMap(), body, basicAuthHeader)) { - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - } + //update with new field + body = new StringEntity("{\"doc\": {\"not test\": \"not test\"}}", RestClient.JSON_CONTENT_TYPE); + try (ElasticsearchResponse response = getRestClient().performRequest("POST", path + "/_update", + Collections.emptyMap(), body, basicAuthHeader)) { + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + } - try (ElasticsearchResponse response = restClient.performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { - String responseBody = EntityUtils.toString(response.getEntity()); - assertThat(responseBody, containsString("\"test\":\"test\"")); - assertThat(responseBody, containsString("\"not test\":\"not test\"")); - assertThat(responseBody, containsString("\"bulk updated\":\"bulk updated\"")); - } + try (ElasticsearchResponse response = getRestClient().performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + String responseBody = EntityUtils.toString(response.getEntity()); + assertThat(responseBody, containsString("\"test\":\"test\"")); + assertThat(responseBody, containsString("\"not test\":\"not test\"")); + } + + // this part is important. Without this, the document may be read from the translog which would bypass the bug where + // FLS kicks in because the request can't be found and only returns meta fields + flushAndRefresh(); + + body = new StringEntity("{\"update\": {\"_index\": \"index1\", \"_type\": \"type\", \"_id\": \"1\"}}\n" + + "{\"doc\": {\"bulk updated\":\"bulk updated\"}}\n", RestClient.JSON_CONTENT_TYPE); + try (ElasticsearchResponse response = getRestClient().performRequest("POST", "/_bulk", + Collections.emptyMap(), body, basicAuthHeader)) { + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + } + + try (ElasticsearchResponse response = getRestClient().performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { + String responseBody = EntityUtils.toString(response.getEntity()); + assertThat(responseBody, containsString("\"test\":\"test\"")); + assertThat(responseBody, containsString("\"not test\":\"not test\"")); + assertThat(responseBody, containsString("\"bulk updated\":\"bulk updated\"")); } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java index 015f37bd7f0..2f6ecf5c03e 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java @@ -9,7 +9,6 @@ import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.elasticsearch.action.ActionListener; import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.RestClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; @@ -166,14 +165,12 @@ public class ClearRealmsCacheTests extends ShieldIntegTestCase { } static void executeHttpRequest(String path, Map params) throws Exception { - try (RestClient restClient = restClient()) { - try (ElasticsearchResponse response = restClient.performRequest("POST", path, params, null, - new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { - assertNotNull(response.getEntity()); - assertTrue(EntityUtils.toString(response.getEntity()).contains("cluster_name")); - } + try (ElasticsearchResponse response = getRestClient().performRequest("POST", path, params, null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { + assertNotNull(response.getEntity()); + assertTrue(EntityUtils.toString(response.getEntity()).contains("cluster_name")); } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java index 63f7187acb3..7fa00aff8f7 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java @@ -10,7 +10,6 @@ import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.RestClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; @@ -137,13 +136,11 @@ public class ClearRolesCacheTests extends NativeRealmIntegTestCase { } else { path = "/_xpack/security/role/" + Strings.arrayToCommaDelimitedString(rolesToClear) + "/_clear_cache"; } - try (RestClient restClient = restClient()) { - try (ElasticsearchResponse response = restClient.performRequest("POST", path, Collections.emptyMap(), null, - new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { - assertThat(response.getStatusLine().getStatusCode(), is(RestStatus.OK.getStatus())); - } + try (ElasticsearchResponse response = getRestClient().performRequest("POST", path, Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { + assertThat(response.getStatusLine().getStatusCode(), is(RestStatus.OK.getStatus())); } } else { securityClient.prepareClearRolesCache().names(rolesToClear).get(); diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java index 1eeae9976a0..813c8007d6b 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java @@ -7,7 +7,6 @@ package org.elasticsearch.integration; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.ElasticsearchResponseException; -import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.authc.support.SecuredString; @@ -21,7 +20,6 @@ import java.util.Map; import static java.util.Collections.singletonMap; import static org.apache.lucene.util.LuceneTestCase.BadApple; -import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; //test is just too slow, please fix it to not be sleep-based @@ -306,8 +304,8 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { } public void testThatUnknownUserIsRejectedProperly() throws Exception { - try (RestClient restClient = restClient()){ - restClient.performRequest("GET", "/", Collections.emptyMap(), null, + try { + getRestClient().performRequest("GET", "/", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue("idonotexist", new SecuredString("passwd".toCharArray())))); fail("request should have failed"); diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java index 4285cd2b4ff..608cdf2a4e5 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java @@ -16,7 +16,6 @@ import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.ElasticsearchResponse; import org.elasticsearch.client.ElasticsearchResponseException; -import org.elasticsearch.client.RestClient; import org.elasticsearch.client.transport.NoNodeAvailableException; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.component.AbstractComponent; @@ -197,21 +196,19 @@ public class LicensingTests extends ShieldIntegTestCase { } public void testRestAuthenticationByLicenseType() throws Exception { - try (RestClient restClient = restClient()) { - try (ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null)) { - // the default of the licensing tests is basic - assertThat(response.getStatusLine().getStatusCode(), is(200)); - } + try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/", Collections.emptyMap(), null)) { + // the default of the licensing tests is basic + assertThat(response.getStatusLine().getStatusCode(), is(200)); + } - // generate a new license with a mode that enables auth - OperationMode mode = randomFrom(OperationMode.GOLD, OperationMode.TRIAL, OperationMode.PLATINUM, OperationMode.STANDARD); - enableLicensing(mode); - try { - restClient.performRequest("GET", "/", Collections.emptyMap(), null); - fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); - } + // generate a new license with a mode that enables auth + OperationMode mode = randomFrom(OperationMode.GOLD, OperationMode.TRIAL, OperationMode.PLATINUM, OperationMode.STANDARD); + enableLicensing(mode); + try { + getRestClient().performRequest("GET", "/", Collections.emptyMap(), null); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java index 6ca7c04d67b..5f5217572fe 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java @@ -8,7 +8,6 @@ package org.elasticsearch.shield; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.ElasticsearchResponse; import org.elasticsearch.client.ElasticsearchResponseException; -import org.elasticsearch.client.RestClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; @@ -34,22 +33,20 @@ public class ShieldPluginTests extends ShieldIntegTestCase { } public void testThatPluginIsLoaded() throws IOException { - try (RestClient restClient = restClient()) { - try { - logger.info("executing unauthorized request to /_xpack info"); - restClient.performRequest("GET", "/_xpack", Collections.emptyMap(), null); - fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(UNAUTHORIZED.getStatus())); - } + try { + logger.info("executing unauthorized request to /_xpack info"); + getRestClient().performRequest("GET", "/_xpack", Collections.emptyMap(), null); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(UNAUTHORIZED.getStatus())); + } - logger.info("executing authorized request to /_xpack infos"); - try (ElasticsearchResponse response = restClient.performRequest("GET", "/_xpack", Collections.emptyMap(), null, - new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { - assertThat(response.getStatusLine().getStatusCode(), is(OK.getStatus())); - } + logger.info("executing authorized request to /_xpack infos"); + try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_xpack", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { + assertThat(response.getStatusLine().getStatusCode(), is(OK.getStatus())); } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java index e2599cc6f85..f7cea02f24e 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java @@ -12,7 +12,6 @@ import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; import org.elasticsearch.client.ElasticsearchResponse; import org.elasticsearch.client.ElasticsearchResponseException; -import org.elasticsearch.client.RestClient; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; @@ -45,7 +44,7 @@ public class RunAsIntegTests extends ShieldIntegTestCase { " cluster: [ 'cluster:monitor/nodes/liveness' ]\n" + "run_as_role:\n" + " run_as: [ '" + ShieldSettingsSource.DEFAULT_USER_NAME + "', 'idontexist' ]\n"; - + @Override public Settings nodeSettings(int nodeOrdinal) { return Settings.builder() @@ -118,37 +117,35 @@ public class RunAsIntegTests extends ShieldIntegTestCase { public void testUserImpersonationUsingHttp() throws Exception { // use the transport client user and try to run as - try (RestClient restClient = restClient()) { - try { - restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, - new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(TRANSPORT_CLIENT_USER, - SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), - new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, ShieldSettingsSource.DEFAULT_USER_NAME)); - fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(403)); - } + try { + getRestClient().performRequest("GET", "/_nodes", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(TRANSPORT_CLIENT_USER, + SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), + new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, ShieldSettingsSource.DEFAULT_USER_NAME)); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(403)); + } - try { - //the run as user shouldn't have access to the nodes api - restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, - new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, - SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD)))); - fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(403)); - } - - // but when running as a different user it should work - try (ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + try { + //the run as user shouldn't have access to the nodes api + getRestClient().performRequest("GET", "/_nodes", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, - SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), - new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, ShieldSettingsSource.DEFAULT_USER_NAME))) { - assertThat(response.getStatusLine().getStatusCode(), is(200)); - } + SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD)))); + fail("request should have failed"); + } catch(ElasticsearchResponseException e) { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(403)); + } + + // but when running as a different user it should work + try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_nodes", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, + SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), + new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, ShieldSettingsSource.DEFAULT_USER_NAME))) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); } } @@ -175,8 +172,8 @@ public class RunAsIntegTests extends ShieldIntegTestCase { } public void testEmptyHeaderUsingHttp() throws Exception { - try (RestClient restClient = restClient()) { - restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + try { + getRestClient().performRequest("GET", "/_nodes", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), @@ -210,9 +207,8 @@ public class RunAsIntegTests extends ShieldIntegTestCase { } public void testNonExistentRunAsUserUsingHttp() throws Exception { - - try (RestClient restClient = restClient()) { - restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + try { + getRestClient().performRequest("GET", "/_nodes", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java index 1684052fe0e..2942576a12b 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java @@ -81,7 +81,7 @@ public class PkiOptionalClientAuthTests extends ShieldIntegTestCase { public void testRestClientWithoutClientCertificate() throws Exception { CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(getSSLContext()).build(); - try (RestClient restClient = restClient(httpClient, "https")) { + try (RestClient restClient = createRestClient(httpClient, "https")) { try { restClient.performRequest("GET", "_nodes", Collections.emptyMap(), null); fail("request should have failed"); diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java index c8be61d519a..1c9ac544942 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java @@ -80,7 +80,7 @@ public class PkiWithoutClientAuthenticationTests extends ShieldIntegTestCase { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sc).build(); - try (RestClient restClient = restClient(httpClient, "https")) { + try (RestClient restClient = createRestClient(httpClient, "https")) { try (ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java index 004cf0019cd..e96a9541a7c 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java @@ -8,7 +8,6 @@ package org.elasticsearch.shield.authc.pki; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Client; import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.authc.support.SecuredString; @@ -44,13 +43,11 @@ public class PkiWithoutSSLTests extends ShieldIntegTestCase { } public void testThatHttpWorks() throws Exception { - try (RestClient restClient = restClient()) { - try (ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, - new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, - UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { - assertThat(response.getStatusLine().getStatusCode(), is(200)); - } + try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_nodes", Collections.emptyMap(), null, + new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, + UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java index 281ac582f29..d209624ac7a 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java @@ -9,7 +9,6 @@ import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.elasticsearch.client.ElasticsearchResponse; import org.elasticsearch.client.ElasticsearchResponseException; -import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.authc.support.SecuredString; @@ -52,42 +51,38 @@ public class RestAuthenticateActionTests extends ShieldIntegTestCase { } public void testAuthenticateApi() throws Exception { - try (RestClient restClient = restClient()) { - try (ElasticsearchResponse response = restClient.performRequest("GET", "/_xpack/security/_authenticate", Collections.emptyMap(), - null, new BasicHeader("Authorization", basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, - new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { - assertThat(response.getStatusLine().getStatusCode(), is(200)); - JsonPath jsonPath = new JsonPath(EntityUtils.toString(response.getEntity())); - assertThat(jsonPath.evaluate("username").toString(), equalTo(ShieldSettingsSource.DEFAULT_USER_NAME)); - @SuppressWarnings("unchecked") - List roles = (List) jsonPath.evaluate("roles"); - assertThat(roles.size(), is(1)); - assertThat(roles, contains(ShieldSettingsSource.DEFAULT_ROLE)); - } + try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_xpack/security/_authenticate", Collections.emptyMap(), + null, new BasicHeader("Authorization", basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); + JsonPath jsonPath = new JsonPath(EntityUtils.toString(response.getEntity())); + assertThat(jsonPath.evaluate("username").toString(), equalTo(ShieldSettingsSource.DEFAULT_USER_NAME)); + @SuppressWarnings("unchecked") + List roles = (List) jsonPath.evaluate("roles"); + assertThat(roles.size(), is(1)); + assertThat(roles, contains(ShieldSettingsSource.DEFAULT_ROLE)); } } public void testAuthenticateApiWithoutAuthentication() throws Exception { - try (RestClient restClient = restClient()) { - try (ElasticsearchResponse response = restClient.performRequest("GET", "/_xpack/security/_authenticate", - Collections.emptyMap(), null)) { - if (anonymousEnabled) { - assertThat(response.getStatusLine().getStatusCode(), is(200)); - JsonPath jsonPath = new JsonPath(EntityUtils.toString(response.getEntity())); - assertThat(jsonPath.evaluate("username").toString(), equalTo("anon")); - @SuppressWarnings("unchecked") - List roles = (List) jsonPath.evaluate("roles"); - assertThat(roles.size(), is(2)); - assertThat(roles, contains(ShieldSettingsSource.DEFAULT_ROLE, "foo")); - } else { - fail("request should have failed"); - } - } catch(ElasticsearchResponseException e) { - if (anonymousEnabled) { - fail("request should have succeeded"); - } else { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); - } + try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_xpack/security/_authenticate", + Collections.emptyMap(), null)) { + if (anonymousEnabled) { + assertThat(response.getStatusLine().getStatusCode(), is(200)); + JsonPath jsonPath = new JsonPath(EntityUtils.toString(response.getEntity())); + assertThat(jsonPath.evaluate("username").toString(), equalTo("anon")); + @SuppressWarnings("unchecked") + List roles = (List) jsonPath.evaluate("roles"); + assertThat(roles.size(), is(2)); + assertThat(roles, contains(ShieldSettingsSource.DEFAULT_ROLE, "foo")); + } else { + fail("request should have failed"); + } + } catch(ElasticsearchResponseException e) { + if (anonymousEnabled) { + fail("request should have succeeded"); + } else { + assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java index e03d4f7f1ec..75220748053 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java @@ -62,7 +62,7 @@ public class SslClientAuthTests extends ShieldIntegTestCase { SSLContexts.createDefault(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - try (RestClient restClient = restClient(HttpClients.custom().setSSLSocketFactory(socketFactory).build(), "https")) { + try (RestClient restClient = createRestClient(HttpClients.custom().setSSLSocketFactory(socketFactory).build(), "https")) { restClient.performRequest("GET", "/", Collections.emptyMap(), null); fail("Expected SSLHandshakeException"); } catch (SSLHandshakeException e) { @@ -82,7 +82,7 @@ public class SslClientAuthTests extends ShieldIntegTestCase { CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); - try (RestClient restClient = restClient(client, "https")) { + try (RestClient restClient = createRestClient(client, "https")) { try (ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null, new BasicHeader("Authorization", basicAuthHeaderValue(transportClientUsername(), transportClientPassword())))) { assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java index 0b8b8036e4d..7e591237221 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java @@ -7,7 +7,6 @@ package org.elasticsearch.shield.user; import org.elasticsearch.client.ElasticsearchResponse; import org.elasticsearch.client.ElasticsearchResponseException; -import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.authz.InternalAuthorizationService; @@ -43,8 +42,8 @@ public class AnonymousUserIntegTests extends ShieldIntegTestCase { } public void testAnonymousViaHttp() throws Exception { - try (RestClient restClient = restClient()) { - restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null); + try { + getRestClient().performRequest("GET", "/_nodes", Collections.emptyMap(), null); fail("request should have failed"); } catch(ElasticsearchResponseException e) { int statusCode = e.getElasticsearchResponse().getStatusLine().getStatusCode(); diff --git a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherPluginDisableTests.java b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherPluginDisableTests.java index 004de9874af..ca54d0d9e84 100644 --- a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherPluginDisableTests.java +++ b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherPluginDisableTests.java @@ -9,7 +9,6 @@ import org.apache.http.HttpStatus; import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; import org.elasticsearch.client.ElasticsearchResponseException; -import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.http.HttpServerTransport; @@ -68,8 +67,8 @@ public class WatcherPluginDisableTests extends ESIntegTestCase { public void testRestEndpoints() throws Exception { HttpServerTransport httpServerTransport = internalCluster().getDataNodeInstance(HttpServerTransport.class); - try (RestClient restClient = restClient()) { - restClient.performRequest("GET", "/_xpack/watcher", Collections.emptyMap(), null); + try { + getRestClient().performRequest("GET", "/_xpack/watcher", Collections.emptyMap(), null); fail("request should have failed"); } catch(ElasticsearchResponseException e) { assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); diff --git a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java index 84022c36164..422f5ecac1d 100644 --- a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java +++ b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java @@ -10,7 +10,6 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.json.JsonXContent; @@ -53,27 +52,25 @@ public class WatcherSettingsFilterTests extends AbstractWatcherIntegrationTestCa } public void testGetSettingsSmtpPassword() throws Exception { - try (RestClient restClient = restClient()) { - Header[] headers; - if (shieldEnabled()) { - headers = new Header[] { - new BasicHeader(BASIC_AUTH_HEADER, - basicAuthHeaderValue(MarvelIntegTestCase.ShieldSettings.TEST_USERNAME, - new SecuredString(MarvelIntegTestCase.ShieldSettings.TEST_PASSWORD.toCharArray())))}; - } else { - headers = new Header[0]; - } - try (ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes/settings", - Collections.emptyMap(), null, headers)) { - Map responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); - Map nodes = (Map) responseMap.get("nodes"); - for (Object node : nodes.values()) { - Map settings = (Map) ((Map) node).get("settings"); - assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.user", settings), - is((Object) "_user")); - assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.password", settings), - nullValue()); - } + Header[] headers; + if (shieldEnabled()) { + headers = new Header[] { + new BasicHeader(BASIC_AUTH_HEADER, + basicAuthHeaderValue(MarvelIntegTestCase.ShieldSettings.TEST_USERNAME, + new SecuredString(MarvelIntegTestCase.ShieldSettings.TEST_PASSWORD.toCharArray())))}; + } else { + headers = new Header[0]; + } + try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_nodes/settings", + Collections.emptyMap(), null, headers)) { + Map responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); + Map nodes = (Map) responseMap.get("nodes"); + for (Object node : nodes.values()) { + Map settings = (Map) ((Map) node).get("settings"); + assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.user", settings), + is((Object) "_user")); + assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.password", settings), + nullValue()); } } } From db27d0ab20193784090801f41f85b24e2c53002b Mon Sep 17 00:00:00 2001 From: javanna Date: Fri, 3 Jun 2016 18:28:45 +0200 Subject: [PATCH 08/11] rename ElasticsearchResponse#getFirstHeader to getHeader Original commit: elastic/x-pack-elasticsearch@8ca2f6d6dd985bad4cf7a20f73c1b0034efe482f --- .../java/org/elasticsearch/example/realm/CustomRealmIT.java | 2 +- .../elasticsearch/shield/user/AnonymousUserIntegTests.java | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java b/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java index 8bbaf98c7ef..ac0b4d3b6a6 100644 --- a/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java +++ b/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java @@ -52,7 +52,7 @@ public class CustomRealmIT extends ESIntegTestCase { } catch(ElasticsearchResponseException e) { ElasticsearchResponse response = e.getElasticsearchResponse(); assertThat(response.getStatusLine().getStatusCode(), is(401)); - String value = response.getFirstHeader("WWW-Authenticate"); + String value = response.getHeader("WWW-Authenticate"); assertThat(value, is("custom-challenge")); } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java index 7e591237221..b3446289985 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java @@ -50,12 +50,12 @@ public class AnonymousUserIntegTests extends ShieldIntegTestCase { ElasticsearchResponse response = e.getElasticsearchResponse(); if (authorizationExceptionsEnabled) { assertThat(statusCode, is(403)); - assertThat(response.getFirstHeader("WWW-Authenticate"), nullValue()); + assertThat(response.getHeader("WWW-Authenticate"), nullValue()); assertThat(e.getResponseBody(), containsString("security_exception")); } else { assertThat(statusCode, is(401)); - assertThat(response.getFirstHeader("WWW-Authenticate"), notNullValue()); - assertThat(response.getFirstHeader("WWW-Authenticate"), containsString("Basic")); + assertThat(response.getHeader("WWW-Authenticate"), notNullValue()); + assertThat(response.getHeader("WWW-Authenticate"), containsString("Basic")); assertThat(e.getResponseBody(), containsString("security_exception")); } } From 359bc7b028a6c01e15ac9c016a75e537801a0f01 Mon Sep 17 00:00:00 2001 From: javanna Date: Fri, 3 Jun 2016 23:14:33 +0200 Subject: [PATCH 09/11] fix line length issue Original commit: elastic/x-pack-elasticsearch@e9afa504a5bbbd072b72150b8f81cb58c1f51bcd --- .../shield/rest/action/RestAuthenticateActionTests.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java index d209624ac7a..86c08fc2d82 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java @@ -51,8 +51,9 @@ public class RestAuthenticateActionTests extends ShieldIntegTestCase { } public void testAuthenticateApi() throws Exception { - try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_xpack/security/_authenticate", Collections.emptyMap(), - null, new BasicHeader("Authorization", basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, + try (ElasticsearchResponse response = getRestClient().performRequest( + "GET", "/_xpack/security/_authenticate", Collections.emptyMap(), null, + new BasicHeader("Authorization", basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { assertThat(response.getStatusLine().getStatusCode(), is(200)); JsonPath jsonPath = new JsonPath(EntityUtils.toString(response.getEntity())); From a45b260244eb92b4ccdf5633db64678d137567c6 Mon Sep 17 00:00:00 2001 From: javanna Date: Sat, 4 Jun 2016 01:10:47 +0200 Subject: [PATCH 10/11] [TEST] lower to 5s the wait for the Thread.sleep Original commit: elastic/x-pack-elasticsearch@6efeb937cd37983fb5d65ac3b00ad6eeeb0ef815 --- .../rest-api-spec/test/watcher_mustache/10_webhook.yaml | 2 +- .../rest-api-spec/test/watcher_mustache/20_array_access.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/elasticsearch/qa/smoke-test-watcher-with-mustache/src/test/resources/rest-api-spec/test/watcher_mustache/10_webhook.yaml b/elasticsearch/qa/smoke-test-watcher-with-mustache/src/test/resources/rest-api-spec/test/watcher_mustache/10_webhook.yaml index b770ed31968..1a7ade5b783 100644 --- a/elasticsearch/qa/smoke-test-watcher-with-mustache/src/test/resources/rest-api-spec/test/watcher_mustache/10_webhook.yaml +++ b/elasticsearch/qa/smoke-test-watcher-with-mustache/src/test/resources/rest-api-spec/test/watcher_mustache/10_webhook.yaml @@ -55,7 +55,7 @@ catch: request_timeout cluster.health: wait_for_nodes: 99 - timeout: 10s + timeout: 5s - match: { "timed_out": true } - do: diff --git a/elasticsearch/qa/smoke-test-watcher-with-mustache/src/test/resources/rest-api-spec/test/watcher_mustache/20_array_access.yaml b/elasticsearch/qa/smoke-test-watcher-with-mustache/src/test/resources/rest-api-spec/test/watcher_mustache/20_array_access.yaml index 153d0334d42..bd051ab6d87 100644 --- a/elasticsearch/qa/smoke-test-watcher-with-mustache/src/test/resources/rest-api-spec/test/watcher_mustache/20_array_access.yaml +++ b/elasticsearch/qa/smoke-test-watcher-with-mustache/src/test/resources/rest-api-spec/test/watcher_mustache/20_array_access.yaml @@ -53,7 +53,7 @@ catch: request_timeout cluster.health: wait_for_nodes: 99 - timeout: 10s + timeout: 5s - match: { "timed_out": true } - do: From 8bf2d93fac692a7e52300272e189a8607cd48685 Mon Sep 17 00:00:00 2001 From: javanna Date: Thu, 9 Jun 2016 16:55:39 +0200 Subject: [PATCH 11/11] rename ElasticsearchResponse and ElasticsearchResponseException to Response and ResponseException Original commit: elastic/x-pack-elasticsearch@edfd24f003631b455a535bb33fc0be5696842ae4 --- .../shield/audit/IndexAuditIT.java | 4 ++-- .../example/realm/CustomRealmIT.java | 10 ++++----- .../shield/MarvelSettingsFilterTests.java | 4 ++-- .../AbstractPrivilegeTestCase.java | 10 ++++----- .../integration/BulkUpdateTests.java | 14 ++++++------ .../integration/ClearRealmsCacheTests.java | 4 ++-- .../integration/ClearRolesCacheTests.java | 4 ++-- .../integration/IndexPrivilegeTests.java | 6 ++--- .../integration/LicensingTests.java | 10 ++++----- .../shield/ShieldPluginTests.java | 10 ++++----- .../shield/authc/RunAsIntegTests.java | 22 +++++++++---------- .../authc/pki/PkiOptionalClientAuthTests.java | 10 ++++----- .../PkiWithoutClientAuthenticationTests.java | 4 ++-- .../shield/authc/pki/PkiWithoutSSLTests.java | 4 ++-- .../action/RestAuthenticateActionTests.java | 12 +++++----- .../transport/ssl/SslClientAuthTests.java | 4 ++-- .../shield/user/AnonymousUserIntegTests.java | 10 ++++----- .../xpack/test/rest/XPackRestTestCase.java | 6 ++--- .../watcher/WatcherPluginDisableTests.java | 6 ++--- .../WatcherSettingsFilterTests.java | 4 ++-- 20 files changed, 79 insertions(+), 79 deletions(-) diff --git a/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java b/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java index 4d728a63ac3..98d5ec97b16 100644 --- a/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java +++ b/elasticsearch/qa/shield-audit-tests/src/test/java/org/elasticsearch/shield/audit/IndexAuditIT.java @@ -10,7 +10,7 @@ import org.apache.http.message.BasicHeader; import org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateResponse; import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.Response; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexTemplateMetaData; import org.elasticsearch.common.settings.Settings; @@ -37,7 +37,7 @@ public class IndexAuditIT extends ESIntegTestCase { private static final String PASS = "changeme"; public void testShieldIndexAuditTrailWorking() throws Exception { - try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_cluster/health", Collections.emptyMap(), null, + try (Response response = getRestClient().performRequest("GET", "/_cluster/health", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray()))))) { assertThat(response.getStatusLine().getStatusCode(), is(200)); diff --git a/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java b/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java index ac0b4d3b6a6..2721747ea7a 100644 --- a/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java +++ b/elasticsearch/qa/shield-example-realm/src/test/java/org/elasticsearch/example/realm/CustomRealmIT.java @@ -9,8 +9,8 @@ import org.apache.http.message.BasicHeader; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; -import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.transport.NoNodeAvailableException; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; @@ -49,8 +49,8 @@ public class CustomRealmIT extends ESIntegTestCase { try { getRestClient().performRequest("GET", "/", Collections.emptyMap(), null); fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - ElasticsearchResponse response = e.getElasticsearchResponse(); + } catch(ResponseException e) { + Response response = e.getResponse(); assertThat(response.getStatusLine().getStatusCode(), is(401)); String value = response.getHeader("WWW-Authenticate"); assertThat(value, is("custom-challenge")); @@ -58,7 +58,7 @@ public class CustomRealmIT extends ESIntegTestCase { } public void testHttpAuthentication() throws Exception { - try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/", Collections.emptyMap(), null, + try (Response response = getRestClient().performRequest("GET", "/", Collections.emptyMap(), null, new BasicHeader(CustomRealm.USER_HEADER, CustomRealm.KNOWN_USER), new BasicHeader(CustomRealm.PW_HEADER, CustomRealm.KNOWN_PW))) { assertThat(response.getStatusLine().getStatusCode(), is(200)); diff --git a/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java b/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java index ef09ede1b18..7f5bc46c758 100644 --- a/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java +++ b/elasticsearch/x-pack/marvel/src/test/java/org/elasticsearch/marvel/shield/MarvelSettingsFilterTests.java @@ -7,7 +7,7 @@ package org.elasticsearch.marvel.shield; import org.apache.http.Header; import org.apache.http.message.BasicHeader; -import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.Response; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.json.JsonXContent; @@ -52,7 +52,7 @@ public class MarvelSettingsFilterTests extends MarvelIntegTestCase { } else { headers = new Header[0]; } - try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_nodes/settings", + try (Response response = getRestClient().performRequest("GET", "/_nodes/settings", Collections.emptyMap(), null, headers)) { Map responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); @SuppressWarnings("unchecked") diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java index 403d7296956..27d61768dd6 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/AbstractPrivilegeTestCase.java @@ -10,8 +10,8 @@ import org.apache.http.StatusLine; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; -import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.RestClient; import org.elasticsearch.shield.authc.support.Hasher; import org.elasticsearch.shield.authc.support.SecuredString; @@ -36,7 +36,7 @@ public abstract class AbstractPrivilegeTestCase extends ShieldIntegTestCase { protected void assertAccessIsAllowed(String user, String method, String uri, String body, Map params) throws IOException { - try (ElasticsearchResponse response = getRestClient().performRequest(method, uri, params, entityOrNull(body), + try (Response response = getRestClient().performRequest(method, uri, params, entityOrNull(body), new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray()))))) { StatusLine statusLine = response.getStatusLine(); @@ -69,8 +69,8 @@ public abstract class AbstractPrivilegeTestCase extends ShieldIntegTestCase { new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray())))); fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - StatusLine statusLine = e.getElasticsearchResponse().getStatusLine(); + } catch(ResponseException e) { + StatusLine statusLine = e.getResponse().getStatusLine(); String message = String.format(Locale.ROOT, "%s %s body %s: Expected 403, got %s %s with body %s", method, uri, body, statusLine.getStatusCode(), statusLine.getReasonPhrase(), e.getResponseBody()); assertThat(message, statusLine.getStatusCode(), is(403)); diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java index 4ca7a37f12d..1be0438bfeb 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/BulkUpdateTests.java @@ -12,7 +12,7 @@ import org.apache.http.util.EntityUtils; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.update.UpdateResponse; -import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.Response; import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; @@ -80,11 +80,11 @@ public class BulkUpdateTests extends ShieldIntegTestCase { new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))); StringEntity body = new StringEntity("{\"test\":\"test\"}", RestClient.JSON_CONTENT_TYPE); - try (ElasticsearchResponse response = getRestClient().performRequest("PUT", path, Collections.emptyMap(), body, basicAuthHeader)) { + try (Response response = getRestClient().performRequest("PUT", path, Collections.emptyMap(), body, basicAuthHeader)) { assertThat(response.getStatusLine().getStatusCode(), equalTo(201)); } - try (ElasticsearchResponse response = getRestClient().performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { + try (Response response = getRestClient().performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(EntityUtils.toString(response.getEntity()), containsString("\"test\":\"test\"")); } @@ -95,12 +95,12 @@ public class BulkUpdateTests extends ShieldIntegTestCase { //update with new field body = new StringEntity("{\"doc\": {\"not test\": \"not test\"}}", RestClient.JSON_CONTENT_TYPE); - try (ElasticsearchResponse response = getRestClient().performRequest("POST", path + "/_update", + try (Response response = getRestClient().performRequest("POST", path + "/_update", Collections.emptyMap(), body, basicAuthHeader)) { assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } - try (ElasticsearchResponse response = getRestClient().performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { + try (Response response = getRestClient().performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); String responseBody = EntityUtils.toString(response.getEntity()); assertThat(responseBody, containsString("\"test\":\"test\"")); @@ -113,12 +113,12 @@ public class BulkUpdateTests extends ShieldIntegTestCase { body = new StringEntity("{\"update\": {\"_index\": \"index1\", \"_type\": \"type\", \"_id\": \"1\"}}\n" + "{\"doc\": {\"bulk updated\":\"bulk updated\"}}\n", RestClient.JSON_CONTENT_TYPE); - try (ElasticsearchResponse response = getRestClient().performRequest("POST", "/_bulk", + try (Response response = getRestClient().performRequest("POST", "/_bulk", Collections.emptyMap(), body, basicAuthHeader)) { assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } - try (ElasticsearchResponse response = getRestClient().performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { + try (Response response = getRestClient().performRequest("GET", path, Collections.emptyMap(), null, basicAuthHeader)) { String responseBody = EntityUtils.toString(response.getEntity()); assertThat(responseBody, containsString("\"test\":\"test\"")); assertThat(responseBody, containsString("\"not test\":\"not test\"")); diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java index 2f6ecf5c03e..1cac9ebe17a 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRealmsCacheTests.java @@ -8,7 +8,7 @@ package org.elasticsearch.integration; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.elasticsearch.action.ActionListener; -import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.Response; import org.elasticsearch.common.Strings; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; @@ -165,7 +165,7 @@ public class ClearRealmsCacheTests extends ShieldIntegTestCase { } static void executeHttpRequest(String path, Map params) throws Exception { - try (ElasticsearchResponse response = getRestClient().performRequest("POST", path, params, null, + try (Response response = getRestClient().performRequest("POST", path, params, null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java index 7fa00aff8f7..5475eadfd72 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/ClearRolesCacheTests.java @@ -9,7 +9,7 @@ import org.apache.http.message.BasicHeader; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.Client; -import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.Response; import org.elasticsearch.common.Strings; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; @@ -136,7 +136,7 @@ public class ClearRolesCacheTests extends NativeRealmIntegTestCase { } else { path = "/_xpack/security/role/" + Strings.arrayToCommaDelimitedString(rolesToClear) + "/_clear_cache"; } - try (ElasticsearchResponse response = getRestClient().performRequest("POST", path, Collections.emptyMap(), null, + try (Response response = getRestClient().performRequest("POST", path, Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java index 813c8007d6b..a7b8a1243a4 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/IndexPrivilegeTests.java @@ -6,7 +6,7 @@ package org.elasticsearch.integration; import org.apache.http.message.BasicHeader; -import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.ResponseException; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.authc.support.SecuredString; @@ -309,8 +309,8 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase { new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue("idonotexist", new SecuredString("passwd".toCharArray())))); fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); + } catch(ResponseException e) { + assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401)); } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java index 608cdf2a4e5..99ba156370e 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/integration/LicensingTests.java @@ -14,8 +14,8 @@ import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse; import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.Client; -import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.transport.NoNodeAvailableException; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.component.AbstractComponent; @@ -196,7 +196,7 @@ public class LicensingTests extends ShieldIntegTestCase { } public void testRestAuthenticationByLicenseType() throws Exception { - try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/", Collections.emptyMap(), null)) { + try (Response response = getRestClient().performRequest("GET", "/", Collections.emptyMap(), null)) { // the default of the licensing tests is basic assertThat(response.getStatusLine().getStatusCode(), is(200)); } @@ -207,8 +207,8 @@ public class LicensingTests extends ShieldIntegTestCase { try { getRestClient().performRequest("GET", "/", Collections.emptyMap(), null); fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); + } catch(ResponseException e) { + assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401)); } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java index 5f5217572fe..556de7da39c 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/ShieldPluginTests.java @@ -6,8 +6,8 @@ package org.elasticsearch.shield; import org.apache.http.message.BasicHeader; -import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.ResponseException; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.authc.support.UsernamePasswordToken; @@ -37,12 +37,12 @@ public class ShieldPluginTests extends ShieldIntegTestCase { logger.info("executing unauthorized request to /_xpack info"); getRestClient().performRequest("GET", "/_xpack", Collections.emptyMap(), null); fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(UNAUTHORIZED.getStatus())); + } catch(ResponseException e) { + assertThat(e.getResponse().getStatusLine().getStatusCode(), is(UNAUTHORIZED.getStatus())); } logger.info("executing authorized request to /_xpack infos"); - try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_xpack", Collections.emptyMap(), null, + try (Response response = getRestClient().performRequest("GET", "/_xpack", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java index f7cea02f24e..3f876f936ed 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/RunAsIntegTests.java @@ -10,8 +10,8 @@ import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; -import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; @@ -124,8 +124,8 @@ public class RunAsIntegTests extends ShieldIntegTestCase { SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, ShieldSettingsSource.DEFAULT_USER_NAME)); fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(403)); + } catch(ResponseException e) { + assertThat(e.getResponse().getStatusLine().getStatusCode(), is(403)); } try { @@ -135,12 +135,12 @@ public class RunAsIntegTests extends ShieldIntegTestCase { UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD)))); fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(403)); + } catch(ResponseException e) { + assertThat(e.getResponse().getStatusLine().getStatusCode(), is(403)); } // but when running as a different user it should work - try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_nodes", Collections.emptyMap(), null, + try (Response response = getRestClient().performRequest("GET", "/_nodes", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), @@ -179,8 +179,8 @@ public class RunAsIntegTests extends ShieldIntegTestCase { SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, "")); fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); + } catch(ResponseException e) { + assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401)); } } @@ -214,8 +214,8 @@ public class RunAsIntegTests extends ShieldIntegTestCase { SecuredStringTests.build(ShieldSettingsSource.DEFAULT_PASSWORD))), new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, "idontexist")); fail("request should have failed"); - } catch (ElasticsearchResponseException e) { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(403)); + } catch (ResponseException e) { + assertThat(e.getResponse().getStatusLine().getStatusCode(), is(403)); } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java index 2942576a12b..796d1d5f95b 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiOptionalClientAuthTests.java @@ -8,8 +8,8 @@ package org.elasticsearch.shield.authc.pki; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; -import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.network.NetworkModule; @@ -85,11 +85,11 @@ public class PkiOptionalClientAuthTests extends ShieldIntegTestCase { try { restClient.performRequest("GET", "_nodes", Collections.emptyMap(), null); fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); + } catch(ResponseException e) { + assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401)); } - try (ElasticsearchResponse response = restClient.performRequest("GET", "_nodes", Collections.emptyMap(), null, + try (Response response = restClient.performRequest("GET", "_nodes", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java index 1c9ac544942..939ecf0483b 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutClientAuthenticationTests.java @@ -10,7 +10,7 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Client; -import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.Response; import org.elasticsearch.client.RestClient; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; @@ -81,7 +81,7 @@ public class PkiWithoutClientAuthenticationTests extends ShieldIntegTestCase { sc.init(null, trustAllCerts, new SecureRandom()); CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sc).build(); try (RestClient restClient = createRestClient(httpClient, "https")) { - try (ElasticsearchResponse response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, + try (Response response = restClient.performRequest("GET", "/_nodes", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java index e96a9541a7c..8f60d2b41f3 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/authc/pki/PkiWithoutSSLTests.java @@ -7,7 +7,7 @@ package org.elasticsearch.shield.authc.pki; import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Client; -import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.Response; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.authc.support.SecuredString; @@ -43,7 +43,7 @@ public class PkiWithoutSSLTests extends ShieldIntegTestCase { } public void testThatHttpWorks() throws Exception { - try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_nodes", Collections.emptyMap(), null, + try (Response response = getRestClient().performRequest("GET", "/_nodes", Collections.emptyMap(), null, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, UsernamePasswordToken.basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java index 86c08fc2d82..9e009ef036c 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/rest/action/RestAuthenticateActionTests.java @@ -7,8 +7,8 @@ package org.elasticsearch.shield.rest.action; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; -import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.ResponseException; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.authc.support.SecuredString; @@ -51,7 +51,7 @@ public class RestAuthenticateActionTests extends ShieldIntegTestCase { } public void testAuthenticateApi() throws Exception { - try (ElasticsearchResponse response = getRestClient().performRequest( + try (Response response = getRestClient().performRequest( "GET", "/_xpack/security/_authenticate", Collections.emptyMap(), null, new BasicHeader("Authorization", basicAuthHeaderValue(ShieldSettingsSource.DEFAULT_USER_NAME, new SecuredString(ShieldSettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { @@ -66,7 +66,7 @@ public class RestAuthenticateActionTests extends ShieldIntegTestCase { } public void testAuthenticateApiWithoutAuthentication() throws Exception { - try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_xpack/security/_authenticate", + try (Response response = getRestClient().performRequest("GET", "/_xpack/security/_authenticate", Collections.emptyMap(), null)) { if (anonymousEnabled) { assertThat(response.getStatusLine().getStatusCode(), is(200)); @@ -79,11 +79,11 @@ public class RestAuthenticateActionTests extends ShieldIntegTestCase { } else { fail("request should have failed"); } - } catch(ElasticsearchResponseException e) { + } catch(ResponseException e) { if (anonymousEnabled) { fail("request should have succeeded"); } else { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(401)); + assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401)); } } } diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java index 75220748053..487b76fc1b6 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/transport/ssl/SslClientAuthTests.java @@ -12,7 +12,7 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.elasticsearch.ElasticsearchException; -import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.Response; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.network.NetworkModule; @@ -83,7 +83,7 @@ public class SslClientAuthTests extends ShieldIntegTestCase { CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); try (RestClient restClient = createRestClient(client, "https")) { - try (ElasticsearchResponse response = restClient.performRequest("GET", "/", Collections.emptyMap(), null, + try (Response response = restClient.performRequest("GET", "/", Collections.emptyMap(), null, new BasicHeader("Authorization", basicAuthHeaderValue(transportClientUsername(), transportClientPassword())))) { assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(EntityUtils.toString(response.getEntity()), containsString("You Know, for Search")); diff --git a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java index b3446289985..58995319020 100644 --- a/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java +++ b/elasticsearch/x-pack/shield/src/test/java/org/elasticsearch/shield/user/AnonymousUserIntegTests.java @@ -5,8 +5,8 @@ */ package org.elasticsearch.shield.user; -import org.elasticsearch.client.ElasticsearchResponse; -import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.ResponseException; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.authz.InternalAuthorizationService; @@ -45,9 +45,9 @@ public class AnonymousUserIntegTests extends ShieldIntegTestCase { try { getRestClient().performRequest("GET", "/_nodes", Collections.emptyMap(), null); fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - int statusCode = e.getElasticsearchResponse().getStatusLine().getStatusCode(); - ElasticsearchResponse response = e.getElasticsearchResponse(); + } catch(ResponseException e) { + int statusCode = e.getResponse().getStatusLine().getStatusCode(); + Response response = e.getResponse(); if (authorizationExceptionsEnabled) { assertThat(statusCode, is(403)); assertThat(response.getHeader("WWW-Authenticate"), nullValue()); diff --git a/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java b/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java index 0dedb417891..e023e2644ac 100644 --- a/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java +++ b/elasticsearch/x-pack/src/test/java/org/elasticsearch/xpack/test/rest/XPackRestTestCase.java @@ -8,7 +8,7 @@ package org.elasticsearch.xpack.test.rest; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; -import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.ResponseException; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; @@ -56,7 +56,7 @@ public abstract class XPackRestTestCase extends ESRestTestCase { public void startWatcher() throws Exception { try { getAdminExecutionContext().callApi("xpack.watcher.start", emptyMap(), emptyList(), emptyMap()); - } catch(ElasticsearchResponseException e) { + } catch(ResponseException e) { //TODO ignore for now, needs to be fixed though } } @@ -65,7 +65,7 @@ public abstract class XPackRestTestCase extends ESRestTestCase { public void stopWatcher() throws Exception { try { getAdminExecutionContext().callApi("xpack.watcher.stop", emptyMap(), emptyList(), emptyMap()); - } catch(ElasticsearchResponseException e) { + } catch(ResponseException e) { //TODO ignore for now, needs to be fixed though } } diff --git a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherPluginDisableTests.java b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherPluginDisableTests.java index ca54d0d9e84..5b7899708d2 100644 --- a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherPluginDisableTests.java +++ b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/WatcherPluginDisableTests.java @@ -8,7 +8,7 @@ package org.elasticsearch.xpack.watcher; import org.apache.http.HttpStatus; import org.elasticsearch.action.admin.cluster.node.info.NodeInfo; import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse; -import org.elasticsearch.client.ElasticsearchResponseException; +import org.elasticsearch.client.ResponseException; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.http.HttpServerTransport; @@ -70,8 +70,8 @@ public class WatcherPluginDisableTests extends ESIntegTestCase { try { getRestClient().performRequest("GET", "/_xpack/watcher", Collections.emptyMap(), null); fail("request should have failed"); - } catch(ElasticsearchResponseException e) { - assertThat(e.getElasticsearchResponse().getStatusLine().getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); + } catch(ResponseException e) { + assertThat(e.getResponse().getStatusLine().getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); } } diff --git a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java index 422f5ecac1d..b61fd4e0231 100644 --- a/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java +++ b/elasticsearch/x-pack/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/WatcherSettingsFilterTests.java @@ -9,7 +9,7 @@ import org.apache.http.Header; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; -import org.elasticsearch.client.ElasticsearchResponse; +import org.elasticsearch.client.Response; import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.json.JsonXContent; @@ -61,7 +61,7 @@ public class WatcherSettingsFilterTests extends AbstractWatcherIntegrationTestCa } else { headers = new Header[0]; } - try (ElasticsearchResponse response = getRestClient().performRequest("GET", "/_nodes/settings", + try (Response response = getRestClient().performRequest("GET", "/_nodes/settings", Collections.emptyMap(), null, headers)) { Map responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); Map nodes = (Map) responseMap.get("nodes");