Rest client: move to async client under the hood

Some configuration changes are needed due to the move to the async http client

Original commit: elastic/x-pack-elasticsearch@2f28dec0a0
This commit is contained in:
javanna 2016-07-12 18:25:27 +02:00 committed by Luca Cavanna
parent 1de203dcef
commit c86c433aab
19 changed files with 132 additions and 167 deletions

View File

@ -38,11 +38,10 @@ public class IndexAuditIT extends ESIntegTestCase {
@AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/2354") @AwaitsFix(bugUrl = "https://github.com/elastic/x-plugins/issues/2354")
public void testShieldIndexAuditTrailWorking() throws Exception { public void testShieldIndexAuditTrailWorking() throws Exception {
try (Response response = getRestClient().performRequest("GET", "/", Response response = getRestClient().performRequest("GET", "/",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray()))))) { UsernamePasswordToken.basicAuthHeaderValue(USER, new SecuredString(PASS.toCharArray()))));
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
}
final AtomicReference<ClusterState> lastClusterState = new AtomicReference<>(); final AtomicReference<ClusterState> lastClusterState = new AtomicReference<>();
final AtomicBoolean indexExists = new AtomicBoolean(false); final AtomicBoolean indexExists = new AtomicBoolean(false);
boolean found = awaitBusy(() -> { boolean found = awaitBusy(() -> {

View File

@ -58,11 +58,10 @@ public class CustomRealmIT extends ESIntegTestCase {
} }
public void testHttpAuthentication() throws Exception { public void testHttpAuthentication() throws Exception {
try (Response response = getRestClient().performRequest("GET", "/", Response response = getRestClient().performRequest("GET", "/",
new BasicHeader(CustomRealm.USER_HEADER, CustomRealm.KNOWN_USER), new BasicHeader(CustomRealm.USER_HEADER, CustomRealm.KNOWN_USER),
new BasicHeader(CustomRealm.PW_HEADER, CustomRealm.KNOWN_PW))) { new BasicHeader(CustomRealm.PW_HEADER, CustomRealm.KNOWN_PW));
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
}
} }
public void testTransportClient() throws Exception { public void testTransportClient() throws Exception {

View File

@ -8,8 +8,6 @@ package org.elasticsearch.smoketest;
import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.Name;
import org.elasticsearch.test.rest.RestTestCandidate; import org.elasticsearch.test.rest.RestTestCandidate;
import java.io.IOException;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
public class GraphWithSecurityInsufficientRoleIT extends GraphWithSecurityIT { public class GraphWithSecurityInsufficientRoleIT extends GraphWithSecurityIT {
@ -18,10 +16,10 @@ public class GraphWithSecurityInsufficientRoleIT extends GraphWithSecurityIT {
super(testCandidate); super(testCandidate);
} }
public void test() throws IOException { public void test() throws Exception {
try { try {
super.test(); super.test();
fail(); fail("should have failed because of missing role");
} catch(AssertionError ae) { } catch(AssertionError ae) {
assertThat(ae.getMessage(), containsString("action [indices:data/read/xpack/graph/explore")); assertThat(ae.getMessage(), containsString("action [indices:data/read/xpack/graph/explore"));
assertThat(ae.getMessage(), containsString("returned [403 Forbidden]")); assertThat(ae.getMessage(), containsString("returned [403 Forbidden]"));

View File

@ -47,7 +47,7 @@ public class MonitoringWithSecurityInsufficientRoleIT extends ESRestTestCase {
} }
@Override @Override
public void test() throws IOException { public void test() throws Exception {
try { try {
super.test(); super.test();
fail("should have failed because of missing role"); fail("should have failed because of missing role");

View File

@ -15,14 +15,13 @@ import org.elasticsearch.xpack.monitoring.MonitoringSettings;
import org.elasticsearch.xpack.monitoring.test.MonitoringIntegTestCase; import org.elasticsearch.xpack.monitoring.test.MonitoringIntegTestCase;
import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.SecuredString;
import java.util.Collections;
import java.util.Map; import java.util.Map;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.extractValue; import static org.elasticsearch.common.xcontent.support.XContentMapValues.extractValue;
import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken.BASIC_AUTH_HEADER; import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken.BASIC_AUTH_HEADER;
import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue; import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
public class MonitoringSettingsFilterTests extends MonitoringIntegTestCase { public class MonitoringSettingsFilterTests extends MonitoringIntegTestCase {
@ -52,22 +51,20 @@ public class MonitoringSettingsFilterTests extends MonitoringIntegTestCase {
} else { } else {
headers = new Header[0]; headers = new Header[0];
} }
try (Response response = getRestClient().performRequest("GET", "/_nodes/settings", Response response = getRestClient().performRequest("GET", "/_nodes/settings", headers);
Collections.emptyMap(), null, headers)) { Map<String, Object> responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map();
Map<String, Object> responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); @SuppressWarnings("unchecked")
Map<String, Object> nodes = (Map<String, Object>) responseMap.get("nodes");
for (Object node : nodes.values()) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, Object> nodes = (Map<String, Object>) responseMap.get("nodes"); Map<String, Object> settings = (Map<String, Object>) ((Map<String, Object>) node).get("settings");
for (Object node : nodes.values()) { assertThat(extractValue("xpack.monitoring.collection.exporters._http.type", settings), equalTo("http"));
@SuppressWarnings("unchecked") assertThat(extractValue("xpack.monitoring.collection.exporters._http.enabled", settings), equalTo("false"));
Map<String, Object> settings = (Map<String, Object>) ((Map<String, Object>) node).get("settings"); assertNullSetting(settings, "xpack.monitoring.collection.exporters._http.auth.username");
assertThat(extractValue("xpack.monitoring.collection.exporters._http.type", settings), equalTo("http")); assertNullSetting(settings, "xpack.monitoring.collection.exporters._http.auth.password");
assertThat(extractValue("xpack.monitoring.collection.exporters._http.enabled", settings), equalTo("false")); assertNullSetting(settings, "xpack.monitoring.collection.exporters._http.ssl.truststore.path");
assertNullSetting(settings, "xpack.monitoring.collection.exporters._http.auth.username"); assertNullSetting(settings, "xpack.monitoring.collection.exporters._http.ssl.truststore.password");
assertNullSetting(settings, "xpack.monitoring.collection.exporters._http.auth.password"); assertNullSetting(settings, "xpack.monitoring.collection.exporters._http.ssl.hostname_verification");
assertNullSetting(settings, "xpack.monitoring.collection.exporters._http.ssl.truststore.path");
assertNullSetting(settings, "xpack.monitoring.collection.exporters._http.ssl.truststore.password");
assertNullSetting(settings, "xpack.monitoring.collection.exporters._http.ssl.hostname_verification");
}
} }
} }

View File

@ -18,7 +18,6 @@ import org.elasticsearch.xpack.security.authc.support.Hasher;
import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.SecuredString;
import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
@ -35,35 +34,34 @@ public abstract class AbstractPrivilegeTestCase extends SecurityIntegTestCase {
protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("passwd".toCharArray()))); protected static final String USERS_PASSWD_HASHED = new String(Hasher.BCRYPT.hash(new SecuredString("passwd".toCharArray())));
protected void assertAccessIsAllowed(String user, String method, String uri, String body, protected void assertAccessIsAllowed(String user, String method, String uri, String body,
Map<String, String> params) throws IOException { Map<String, String> params) throws Exception {
try (Response response = getRestClient().performRequest(method, uri, params, entityOrNull(body), Response response = getRestClient().performRequest(method, uri, params, entityOrNull(body),
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray()))))) { UsernamePasswordToken.basicAuthHeaderValue(user, new SecuredString("passwd".toCharArray()))));
StatusLine statusLine = response.getStatusLine(); StatusLine statusLine = response.getStatusLine();
String message = String.format(Locale.ROOT, "%s %s: Expected no error got %s %s with body %s", method, uri, 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())); statusLine.getStatusCode(), statusLine.getReasonPhrase(), EntityUtils.toString(response.getEntity()));
assertThat(message, statusLine.getStatusCode(), is(not(greaterThanOrEqualTo(400)))); assertThat(message, statusLine.getStatusCode(), is(not(greaterThanOrEqualTo(400))));
}
} }
protected void assertAccessIsAllowed(String user, String method, String uri, String body) throws IOException { protected void assertAccessIsAllowed(String user, String method, String uri, String body) throws Exception {
assertAccessIsAllowed(user, method, uri, body, new HashMap<>()); assertAccessIsAllowed(user, method, uri, body, new HashMap<>());
} }
protected void assertAccessIsAllowed(String user, String method, String uri) throws IOException { protected void assertAccessIsAllowed(String user, String method, String uri) throws Exception {
assertAccessIsAllowed(user, method, uri, null, new HashMap<>()); assertAccessIsAllowed(user, method, uri, null, new HashMap<>());
} }
protected void assertAccessIsDenied(String user, String method, String uri, String body) throws IOException { protected void assertAccessIsDenied(String user, String method, String uri, String body) throws Exception {
assertAccessIsDenied(user, method, uri, body, new HashMap<>()); assertAccessIsDenied(user, method, uri, body, new HashMap<>());
} }
protected void assertAccessIsDenied(String user, String method, String uri) throws IOException { protected void assertAccessIsDenied(String user, String method, String uri) throws Exception {
assertAccessIsDenied(user, method, uri, null, new HashMap<>()); assertAccessIsDenied(user, method, uri, null, new HashMap<>());
} }
protected void assertAccessIsDenied(String user, String method, String uri, String body, protected void assertAccessIsDenied(String user, String method, String uri, String body,
Map<String, String> params) throws IOException { Map<String, String> params) throws Exception {
try { try {
getRestClient().performRequest(method, uri, params, entityOrNull(body), getRestClient().performRequest(method, uri, params, entityOrNull(body),
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
@ -72,7 +70,7 @@ public abstract class AbstractPrivilegeTestCase extends SecurityIntegTestCase {
} catch(ResponseException e) { } catch(ResponseException e) {
StatusLine statusLine = e.getResponse().getStatusLine(); 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, 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()); statusLine.getStatusCode(), statusLine.getReasonPhrase(), EntityUtils.toString(e.getResponse().getEntity()));
assertThat(message, statusLine.getStatusCode(), is(403)); assertThat(message, statusLine.getStatusCode(), is(403));
} }
} }

View File

@ -16,14 +16,13 @@ import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClient;
import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.xpack.security.Security;
import org.elasticsearch.xpack.security.authc.support.SecuredString;
import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken;
import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.test.SecurityIntegTestCase;
import org.elasticsearch.test.SecuritySettingsSource; import org.elasticsearch.test.SecuritySettingsSource;
import org.elasticsearch.xpack.XPackPlugin; import org.elasticsearch.xpack.XPackPlugin;
import org.elasticsearch.xpack.security.Security;
import org.elasticsearch.xpack.security.authc.support.SecuredString;
import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken;
import java.io.IOException;
import java.util.Collections; import java.util.Collections;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
@ -73,21 +72,19 @@ public class BulkUpdateTests extends SecurityIntegTestCase {
assertThat(getResponse.getField("bulk updated").getValue(), equalTo("bulk updated")); assertThat(getResponse.getField("bulk updated").getValue(), equalTo("bulk updated"));
} }
public void testThatBulkUpdateDoesNotLoseFieldsHttp() throws IOException { public void testThatBulkUpdateDoesNotLoseFieldsHttp() throws Exception {
final String path = "/index1/type/1"; final String path = "/index1/type/1";
final Header basicAuthHeader = new BasicHeader("Authorization", final Header basicAuthHeader = new BasicHeader("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME,
new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))); new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray())));
StringEntity body = new StringEntity("{\"test\":\"test\"}", RestClient.JSON_CONTENT_TYPE); StringEntity body = new StringEntity("{\"test\":\"test\"}", RestClient.JSON_CONTENT_TYPE);
try (Response response = getRestClient().performRequest("PUT", path, Collections.emptyMap(), body, basicAuthHeader)) { Response response = getRestClient().performRequest("PUT", path, Collections.emptyMap(), body, basicAuthHeader);
assertThat(response.getStatusLine().getStatusCode(), equalTo(201)); assertThat(response.getStatusLine().getStatusCode(), equalTo(201));
}
try (Response response = getRestClient().performRequest("GET", path, basicAuthHeader)) { response = getRestClient().performRequest("GET", path, basicAuthHeader);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(EntityUtils.toString(response.getEntity()), containsString("\"test\":\"test\"")); assertThat(EntityUtils.toString(response.getEntity()), containsString("\"test\":\"test\""));
}
if (randomBoolean()) { if (randomBoolean()) {
flushAndRefresh(); flushAndRefresh();
@ -95,17 +92,14 @@ public class BulkUpdateTests extends SecurityIntegTestCase {
//update with new field //update with new field
body = new StringEntity("{\"doc\": {\"not test\": \"not test\"}}", RestClient.JSON_CONTENT_TYPE); body = new StringEntity("{\"doc\": {\"not test\": \"not test\"}}", RestClient.JSON_CONTENT_TYPE);
try (Response response = getRestClient().performRequest("POST", path + "/_update", response = getRestClient().performRequest("POST", path + "/_update", Collections.emptyMap(), body, basicAuthHeader);
Collections.emptyMap(), body, basicAuthHeader)) { assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
try (Response response = getRestClient().performRequest("GET", path, basicAuthHeader)) { response = getRestClient().performRequest("GET", path, basicAuthHeader);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
String responseBody = EntityUtils.toString(response.getEntity()); String responseBody = EntityUtils.toString(response.getEntity());
assertThat(responseBody, containsString("\"test\":\"test\"")); assertThat(responseBody, containsString("\"test\":\"test\""));
assertThat(responseBody, containsString("\"not test\":\"not 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 // 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 // FLS kicks in because the request can't be found and only returns meta fields
@ -113,16 +107,13 @@ public class BulkUpdateTests extends SecurityIntegTestCase {
body = new StringEntity("{\"update\": {\"_index\": \"index1\", \"_type\": \"type\", \"_id\": \"1\"}}\n" + body = new StringEntity("{\"update\": {\"_index\": \"index1\", \"_type\": \"type\", \"_id\": \"1\"}}\n" +
"{\"doc\": {\"bulk updated\":\"bulk updated\"}}\n", RestClient.JSON_CONTENT_TYPE); "{\"doc\": {\"bulk updated\":\"bulk updated\"}}\n", RestClient.JSON_CONTENT_TYPE);
try (Response response = getRestClient().performRequest("POST", "/_bulk", response = getRestClient().performRequest("POST", "/_bulk", Collections.emptyMap(), body, basicAuthHeader);
Collections.emptyMap(), body, basicAuthHeader)) { assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
try (Response response = getRestClient().performRequest("GET", path, basicAuthHeader)) { response = getRestClient().performRequest("GET", path, basicAuthHeader);
String responseBody = EntityUtils.toString(response.getEntity()); responseBody = EntityUtils.toString(response.getEntity());
assertThat(responseBody, containsString("\"test\":\"test\"")); assertThat(responseBody, containsString("\"test\":\"test\""));
assertThat(responseBody, containsString("\"not test\":\"not test\"")); assertThat(responseBody, containsString("\"not test\":\"not test\""));
assertThat(responseBody, containsString("\"bulk updated\":\"bulk updated\"")); assertThat(responseBody, containsString("\"bulk updated\":\"bulk updated\""));
}
} }
} }

View File

@ -162,13 +162,12 @@ public class ClearRealmsCacheTests extends SecurityIntegTestCase {
} }
static void executeHttpRequest(String path, Map<String, String> params) throws Exception { static void executeHttpRequest(String path, Map<String, String> params) throws Exception {
try (Response response = getRestClient().performRequest("POST", path, params, Response response = getRestClient().performRequest("POST", path, params,
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME,
new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))));
assertNotNull(response.getEntity()); assertNotNull(response.getEntity());
assertTrue(EntityUtils.toString(response.getEntity()).contains("cluster_name")); assertTrue(EntityUtils.toString(response.getEntity()).contains("cluster_name"));
}
} }
} }

View File

@ -137,12 +137,11 @@ public class ClearRolesCacheTests extends NativeRealmIntegTestCase {
} else { } else {
path = "/_xpack/security/role/" + Strings.arrayToCommaDelimitedString(rolesToClear) + "/_clear_cache"; path = "/_xpack/security/role/" + Strings.arrayToCommaDelimitedString(rolesToClear) + "/_clear_cache";
} }
try (Response response = getRestClient().performRequest("POST", path, Response response = getRestClient().performRequest("POST", path,
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME,
new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))));
assertThat(response.getStatusLine().getStatusCode(), is(RestStatus.OK.getStatus())); assertThat(response.getStatusLine().getStatusCode(), is(RestStatus.OK.getStatus()));
}
} else { } else {
securityClient.prepareClearRolesCache().names(rolesToClear).get(); securityClient.prepareClearRolesCache().names(rolesToClear).get();
} }

View File

@ -169,10 +169,9 @@ public class LicensingTests extends SecurityIntegTestCase {
} }
public void testRestAuthenticationByLicenseType() throws Exception { public void testRestAuthenticationByLicenseType() throws Exception {
try (Response response = getRestClient().performRequest("GET", "/")) { Response response = getRestClient().performRequest("GET", "/");
// the default of the licensing tests is basic // the default of the licensing tests is basic
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
}
// generate a new license with a mode that enables auth // generate a new license with a mode that enables auth
OperationMode mode = randomFrom(OperationMode.GOLD, OperationMode.TRIAL, OperationMode.PLATINUM, OperationMode.STANDARD); OperationMode mode = randomFrom(OperationMode.GOLD, OperationMode.TRIAL, OperationMode.PLATINUM, OperationMode.STANDARD);

View File

@ -14,8 +14,6 @@ import org.elasticsearch.test.SecuritySettingsSource;
import org.elasticsearch.xpack.security.authc.support.SecuredString; import org.elasticsearch.xpack.security.authc.support.SecuredString;
import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken;
import java.io.IOException;
import static org.elasticsearch.rest.RestStatus.OK; import static org.elasticsearch.rest.RestStatus.OK;
import static org.elasticsearch.rest.RestStatus.UNAUTHORIZED; import static org.elasticsearch.rest.RestStatus.UNAUTHORIZED;
import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue; import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
@ -31,7 +29,7 @@ public class SecurityPluginTests extends SecurityIntegTestCase {
.build(); .build();
} }
public void testThatPluginIsLoaded() throws IOException { public void testThatPluginIsLoaded() throws Exception {
try { try {
logger.info("executing unauthorized request to /_xpack info"); logger.info("executing unauthorized request to /_xpack info");
getRestClient().performRequest("GET", "/_xpack"); getRestClient().performRequest("GET", "/_xpack");
@ -41,11 +39,10 @@ public class SecurityPluginTests extends SecurityIntegTestCase {
} }
logger.info("executing authorized request to /_xpack infos"); logger.info("executing authorized request to /_xpack infos");
try (Response response = getRestClient().performRequest("GET", "/_xpack", Response response = getRestClient().performRequest("GET", "/_xpack",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME,
new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))));
assertThat(response.getStatusLine().getStatusCode(), is(OK.getStatus())); assertThat(response.getStatusLine().getStatusCode(), is(OK.getStatus()));
}
} }
} }

View File

@ -140,13 +140,12 @@ public class RunAsIntegTests extends SecurityIntegTestCase {
} }
// but when running as a different user it should work // but when running as a different user it should work
try (Response response = getRestClient().performRequest("GET", "/_nodes", Response response = getRestClient().performRequest("GET", "/_nodes",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER,
SecuredStringTests.build(SecuritySettingsSource.DEFAULT_PASSWORD))), SecuredStringTests.build(SecuritySettingsSource.DEFAULT_PASSWORD))),
new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, SecuritySettingsSource.DEFAULT_USER_NAME))) { new BasicHeader(InternalAuthenticationService.RUN_AS_USER_HEADER, SecuritySettingsSource.DEFAULT_USER_NAME));
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
}
} }
public void testEmptyUserImpersonationHeader() throws Exception { public void testEmptyUserImpersonationHeader() throws Exception {

View File

@ -5,12 +5,11 @@
*/ */
package org.elasticsearch.xpack.security.authc.pki; package org.elasticsearch.xpack.security.authc.pki;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.SSLSocketFactoryHttpConfigCallback;
import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
@ -79,8 +78,8 @@ public class PkiOptionalClientAuthTests extends SecurityIntegTestCase {
} }
public void testRestClientWithoutClientCertificate() throws Exception { public void testRestClientWithoutClientCertificate() throws Exception {
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(getSSLContext()); SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(getSSLContext());
try (RestClient restClient = createRestClient(new SSLSocketFactoryHttpConfigCallback(sslConnectionSocketFactory), "https")) { try (RestClient restClient = createRestClient(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy), "https")) {
try { try {
restClient.performRequest("GET", "_nodes"); restClient.performRequest("GET", "_nodes");
fail("request should have failed"); fail("request should have failed");
@ -88,12 +87,11 @@ public class PkiOptionalClientAuthTests extends SecurityIntegTestCase {
assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401)); assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401));
} }
try (Response response = restClient.performRequest("GET", "_nodes", Response response = restClient.performRequest("GET", "_nodes",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME,
new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))));
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
}
} }
} }

View File

@ -6,12 +6,11 @@
package org.elasticsearch.xpack.security.authc.pki; package org.elasticsearch.xpack.security.authc.pki;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
import org.elasticsearch.client.Client; import org.elasticsearch.client.Client;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.SSLSocketFactoryHttpConfigCallback;
import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
@ -78,14 +77,13 @@ public class PkiWithoutClientAuthenticationTests extends SecurityIntegTestCase {
public void testThatHttpWorks() throws Exception { public void testThatHttpWorks() throws Exception {
SSLContext sc = SSLContext.getInstance("SSL"); SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom()); sc.init(null, trustAllCerts, new SecureRandom());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sc); SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sc);
try (RestClient restClient = createRestClient(new SSLSocketFactoryHttpConfigCallback(sslConnectionSocketFactory), "https")) { try (RestClient restClient = createRestClient(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy), "https")) {
try (Response response = restClient.performRequest("GET", "/_nodes", Response response = restClient.performRequest("GET", "/_nodes",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME,
new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))));
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
}
} }
} }
} }

View File

@ -41,11 +41,10 @@ public class PkiWithoutSSLTests extends SecurityIntegTestCase {
} }
public void testThatHttpWorks() throws Exception { public void testThatHttpWorks() throws Exception {
try (Response response = getRestClient().performRequest("GET", "/_nodes", Response response = getRestClient().performRequest("GET", "/_nodes",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME,
new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))));
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
}
} }
} }

View File

@ -52,23 +52,22 @@ public class RestAuthenticateActionTests extends SecurityIntegTestCase {
} }
public void testAuthenticateApi() throws Exception { public void testAuthenticateApi() throws Exception {
try (Response response = getRestClient().performRequest( Response response = getRestClient().performRequest("GET", "/_xpack/security/_authenticate",
"GET", "/_xpack/security/_authenticate",
new BasicHeader("Authorization", basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME, new BasicHeader("Authorization", basicAuthHeaderValue(SecuritySettingsSource.DEFAULT_USER_NAME,
new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))))) { new SecuredString(SecuritySettingsSource.DEFAULT_PASSWORD.toCharArray()))));
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
ObjectPath objectPath = ObjectPath.createFromXContent(XContentFactory.xContent(XContentType.JSON), ObjectPath objectPath = ObjectPath.createFromXContent(XContentFactory.xContent(XContentType.JSON),
EntityUtils.toString(response.getEntity())); EntityUtils.toString(response.getEntity()));
assertThat(objectPath.evaluate("username").toString(), equalTo(SecuritySettingsSource.DEFAULT_USER_NAME)); assertThat(objectPath.evaluate("username").toString(), equalTo(SecuritySettingsSource.DEFAULT_USER_NAME));
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<String> roles = (List<String>) objectPath.evaluate("roles"); List<String> roles = (List<String>) objectPath.evaluate("roles");
assertThat(roles.size(), is(1)); assertThat(roles.size(), is(1));
assertThat(roles, contains(SecuritySettingsSource.DEFAULT_ROLE)); assertThat(roles, contains(SecuritySettingsSource.DEFAULT_ROLE));
}
} }
public void testAuthenticateApiWithoutAuthentication() throws Exception { public void testAuthenticateApiWithoutAuthentication() throws Exception {
try (Response response = getRestClient().performRequest("GET", "/_xpack/security/_authenticate")) { try {
Response response = getRestClient().performRequest("GET", "/_xpack/security/_authenticate");
if (anonymousEnabled) { if (anonymousEnabled) {
assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(response.getStatusLine().getStatusCode(), is(200));
ObjectPath objectPath = ObjectPath.createFromXContent(XContentFactory.xContent(XContentType.JSON), ObjectPath objectPath = ObjectPath.createFromXContent(XContentFactory.xContent(XContentType.JSON),

View File

@ -6,14 +6,14 @@
package org.elasticsearch.xpack.security.transport.ssl; package org.elasticsearch.xpack.security.transport.ssl;
import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.SSLSocketFactoryHttpConfigCallback;
import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.network.NetworkModule;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
@ -28,14 +28,15 @@ import org.elasticsearch.xpack.security.transport.netty.SecurityNettyHttpServerT
import org.elasticsearch.xpack.security.transport.netty.SecurityNettyTransport; import org.elasticsearch.xpack.security.transport.netty.SecurityNettyTransport;
import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.security.cert.CertPathBuilderException;
import static org.elasticsearch.test.SecuritySettingsSource.getSSLSettingsForStore; import static org.elasticsearch.test.SecuritySettingsSource.getSSLSettingsForStore;
import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue; import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
public class SslClientAuthTests extends SecurityIntegTestCase { public class SslClientAuthTests extends SecurityIntegTestCase {
@Override @Override
@ -56,32 +57,29 @@ public class SslClientAuthTests extends SecurityIntegTestCase {
return true; return true;
} }
public void testThatHttpFailsWithoutSslClientAuth() throws IOException { public void testThatHttpFailsWithoutSslClientAuth() throws Exception {
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(SSLContexts.createDefault(), NoopHostnameVerifier.INSTANCE);
SSLContexts.createDefault(), try (RestClient restClient = createRestClient(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy), "https")) {
NoopHostnameVerifier.INSTANCE);
try (RestClient restClient = createRestClient(new SSLSocketFactoryHttpConfigCallback(socketFactory), "https")) {
restClient.performRequest("GET", "/"); restClient.performRequest("GET", "/");
fail("Expected SSLHandshakeException"); fail("Expected SSLHandshakeException");
} catch (SSLHandshakeException e) { } catch (SSLHandshakeException e) {
assertThat(e.getMessage(), containsString("unable to find valid certification path to requested target")); Throwable t = ExceptionsHelper.unwrap(e, CertPathBuilderException.class);
assertThat(t, instanceOf(CertPathBuilderException.class));
assertThat(t.getMessage(), containsString("unable to find valid certification path to requested target"));
} }
} }
public void testThatHttpWorksWithSslClientAuth() throws IOException { public void testThatHttpWorksWithSslClientAuth() throws Exception {
Settings settings = Settings.builder() Settings settings = Settings.builder()
.put(getSSLSettingsForStore("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testclient.jks", "testclient")) .put(getSSLSettingsForStore("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testclient.jks", "testclient"))
.build(); .build();
ClientSSLService sslService = new ClientSSLService(settings, new Global(settings)); ClientSSLService sslService = new ClientSSLService(settings, new Global(settings));
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslService.sslContext(), NoopHostnameVerifier.INSTANCE);
sslService.sslContext(), try (RestClient restClient = createRestClient(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy), "https")) {
NoopHostnameVerifier.INSTANCE); Response response = restClient.performRequest("GET", "/",
try (RestClient restClient = createRestClient(new SSLSocketFactoryHttpConfigCallback(socketFactory), "https")) { new BasicHeader("Authorization", basicAuthHeaderValue(transportClientUsername(), transportClientPassword())));
try (Response response = restClient.performRequest("GET", "/", assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
new BasicHeader("Authorization", basicAuthHeaderValue(transportClientUsername(), transportClientPassword())))) { assertThat(EntityUtils.toString(response.getEntity()), containsString("You Know, for Search"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(EntityUtils.toString(response.getEntity()), containsString("You Know, for Search"));
}
} }
} }

View File

@ -5,6 +5,7 @@
*/ */
package org.elasticsearch.xpack.security.user; package org.elasticsearch.xpack.security.user;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.ResponseException;
import org.elasticsearch.common.network.NetworkModule; import org.elasticsearch.common.network.NetworkModule;
@ -49,12 +50,12 @@ public class AnonymousUserIntegTests extends SecurityIntegTestCase {
if (authorizationExceptionsEnabled) { if (authorizationExceptionsEnabled) {
assertThat(statusCode, is(403)); assertThat(statusCode, is(403));
assertThat(response.getHeader("WWW-Authenticate"), nullValue()); assertThat(response.getHeader("WWW-Authenticate"), nullValue());
assertThat(e.getResponseBody(), containsString("security_exception")); assertThat(EntityUtils.toString(response.getEntity()), containsString("security_exception"));
} else { } else {
assertThat(statusCode, is(401)); assertThat(statusCode, is(401));
assertThat(response.getHeader("WWW-Authenticate"), notNullValue()); assertThat(response.getHeader("WWW-Authenticate"), notNullValue());
assertThat(response.getHeader("WWW-Authenticate"), containsString("Basic")); assertThat(response.getHeader("WWW-Authenticate"), containsString("Basic"));
assertThat(e.getResponseBody(), containsString("security_exception")); assertThat(EntityUtils.toString(response.getEntity()), containsString("security_exception"));
} }
} }
} }

View File

@ -20,7 +20,6 @@ import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.junit.After; import org.junit.After;
import java.io.IOException; import java.io.IOException;
import java.util.Collections;
import java.util.Map; import java.util.Map;
import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken.BASIC_AUTH_HEADER; import static org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken.BASIC_AUTH_HEADER;
@ -58,17 +57,15 @@ public class WatcherSettingsFilterTests extends AbstractWatcherIntegrationTestCa
} else { } else {
headers = new Header[0]; headers = new Header[0];
} }
try (Response response = getRestClient().performRequest("GET", "/_nodes/settings", Response response = getRestClient().performRequest("GET", "/_nodes/settings", headers);
Collections.emptyMap(), null, headers)) { Map<String, Object> responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map();
Map<String, Object> responseMap = JsonXContent.jsonXContent.createParser(response.getEntity().getContent()).map(); Map<String, Object> nodes = (Map<String, Object>) responseMap.get("nodes");
Map<String, Object> nodes = (Map<String, Object>) responseMap.get("nodes"); for (Object node : nodes.values()) {
for (Object node : nodes.values()) { Map<String, Object> settings = (Map<String, Object>) ((Map<String, Object>) node).get("settings");
Map<String, Object> settings = (Map<String, Object>) ((Map<String, Object>) node).get("settings"); assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.user", settings),
assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.user", settings), is((Object) "_user"));
is((Object) "_user")); assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.password", settings),
assertThat(XContentMapValues.extractValue("xpack.notification.email.account._email.smtp.password", settings), nullValue());
nullValue());
}
} }
} }
} }