Switch security to new style Requests (#32290)

In #29623 we added `Request` object flavored requests to the low level
REST client and in #30315 we deprecated the old `performRequest`s. This
changes all calls in the `x-pack/plugin/security` project to use the new
versions.
This commit is contained in:
Nik Everett 2018-07-30 18:16:26 -04:00 committed by GitHub
parent 670630948b
commit 4101fc4e3d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 161 additions and 137 deletions

View File

@ -5,15 +5,12 @@
*/
package org.elasticsearch.integration;
import org.apache.http.Header;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
@ -24,10 +21,8 @@ import org.elasticsearch.xpack.core.XPackSettings;
import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken;
import java.io.IOException;
import java.util.Collections;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
public class BulkUpdateTests extends SecurityIntegTestCase {
@ -77,46 +72,48 @@ public class BulkUpdateTests extends SecurityIntegTestCase {
public void testThatBulkUpdateDoesNotLoseFieldsHttp() throws IOException {
final String path = "/index1/type/1";
final Header basicAuthHeader = new BasicHeader("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray())));
final RequestOptions.Builder optionsBuilder = RequestOptions.DEFAULT.toBuilder();
optionsBuilder.addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray())));
final RequestOptions options = optionsBuilder.build();
StringEntity body = new StringEntity("{\"test\":\"test\"}", ContentType.APPLICATION_JSON);
Response response = getRestClient().performRequest("PUT", path, Collections.emptyMap(), body, basicAuthHeader);
assertThat(response.getStatusLine().getStatusCode(), equalTo(201));
Request createRequest = new Request("PUT", path);
createRequest.setOptions(options);
createRequest.setJsonEntity("{\"test\":\"test\"}");
getRestClient().performRequest(createRequest);
response = getRestClient().performRequest("GET", path, basicAuthHeader);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(EntityUtils.toString(response.getEntity()), containsString("\"test\":\"test\""));
Request getRequest = new Request("GET", path);
getRequest.setOptions(options);
assertThat(EntityUtils.toString(getRestClient().performRequest(getRequest).getEntity()), containsString("\"test\":\"test\""));
if (randomBoolean()) {
flushAndRefresh();
}
//update with new field
body = new StringEntity("{\"doc\": {\"not test\": \"not test\"}}", ContentType.APPLICATION_JSON);
response = getRestClient().performRequest("POST", path + "/_update", Collections.emptyMap(), body, basicAuthHeader);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
Request updateRequest = new Request("POST", path + "/_update");
updateRequest.setOptions(options);
updateRequest.setJsonEntity("{\"doc\": {\"not test\": \"not test\"}}");
getRestClient().performRequest(updateRequest);
response = getRestClient().performRequest("GET", path, 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\""));
String afterUpdate = EntityUtils.toString(getRestClient().performRequest(getRequest).getEntity());
assertThat(afterUpdate, containsString("\"test\":\"test\""));
assertThat(afterUpdate, 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", ContentType.APPLICATION_JSON);
response = getRestClient().performRequest("POST", "/_bulk", Collections.emptyMap(), body, basicAuthHeader);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
Request bulkRequest = new Request("POST", "/_bulk");
bulkRequest.setOptions(options);
bulkRequest.setJsonEntity(
"{\"update\": {\"_index\": \"index1\", \"_type\": \"type\", \"_id\": \"1\"}}\n" +
"{\"doc\": {\"bulk updated\":\"bulk updated\"}}\n");
getRestClient().performRequest(bulkRequest);
response = getRestClient().performRequest("GET", path, 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\""));
String afterBulk = EntityUtils.toString(getRestClient().performRequest(getRequest).getEntity());
assertThat(afterBulk, containsString("\"test\":\"test\""));
assertThat(afterBulk, containsString("\"not test\":\"not test\""));
assertThat(afterBulk, containsString("\"bulk updated\":\"bulk updated\""));
}
}

View File

@ -5,10 +5,11 @@
*/
package org.elasticsearch.integration;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.SecureString;
@ -160,10 +161,15 @@ public class ClearRealmsCacheTests extends SecurityIntegTestCase {
}
static void executeHttpRequest(String path, Map<String, String> params) throws Exception {
Response response = getRestClient().performRequest("POST", path, params,
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))));
Request request = new Request("POST", path);
for (Map.Entry<String, String> param : params.entrySet()) {
request.addParameter(param.getKey(), param.getValue());
}
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray())));
request.setOptions(options);
Response response = getRestClient().performRequest(request);
assertNotNull(response.getEntity());
assertTrue(EntityUtils.toString(response.getEntity()).contains("cluster_name"));
}

View File

@ -5,7 +5,8 @@
*/
package org.elasticsearch.integration;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.xpack.core.security.authc.support.Hasher;
@ -388,9 +389,12 @@ public class IndexPrivilegeTests extends AbstractPrivilegeTestCase {
public void testThatUnknownUserIsRejectedProperly() throws Exception {
try {
getRestClient().performRequest("GET", "/",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue("idonotexist", new SecureString("passwd".toCharArray()))));
Request request = new Request("GET", "/");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization",
UsernamePasswordToken.basicAuthHeaderValue("idonotexist", new SecureString("passwd".toCharArray())));
request.setOptions(options);
getRestClient().performRequest(request);
fail("request should have failed");
} catch(ResponseException e) {
assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401));

View File

@ -5,7 +5,6 @@
*/
package org.elasticsearch.license;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.ElasticsearchSecurityException;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
@ -15,6 +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.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.transport.NoNodeAvailableException;
@ -189,31 +190,36 @@ public class LicensingTests extends SecurityIntegTestCase {
}
public void testRestAuthenticationByLicenseType() throws Exception {
Response response = getRestClient().performRequest("GET", "/");
Response unauthorizedRootResponse = getRestClient().performRequest(new Request("GET", "/"));
// the default of the licensing tests is basic
assertThat(response.getStatusLine().getStatusCode(), is(200));
assertThat(unauthorizedRootResponse.getStatusLine().getStatusCode(), is(200));
ResponseException e = expectThrows(ResponseException.class,
() -> getRestClient().performRequest("GET", "/_xpack/security/_authenticate"));
() -> getRestClient().performRequest(new Request("GET", "/_xpack/security/_authenticate")));
assertThat(e.getResponse().getStatusLine().getStatusCode(), is(403));
// generate a new license with a mode that enables auth
License.OperationMode mode = randomFrom(License.OperationMode.GOLD, License.OperationMode.TRIAL,
License.OperationMode.PLATINUM, License.OperationMode.STANDARD);
enableLicensing(mode);
e = expectThrows(ResponseException.class, () -> getRestClient().performRequest("GET", "/"));
e = expectThrows(ResponseException.class, () -> getRestClient().performRequest(new Request("GET", "/")));
assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401));
e = expectThrows(ResponseException.class,
() -> getRestClient().performRequest("GET", "/_xpack/security/_authenticate"));
() -> getRestClient().performRequest(new Request("GET", "/_xpack/security/_authenticate")));
assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401));
final String basicAuthValue = UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()));
response = getRestClient().performRequest("GET", "/", new BasicHeader("Authorization", basicAuthValue));
assertThat(response.getStatusLine().getStatusCode(), is(200));
response = getRestClient().performRequest("GET", "/_xpack/security/_authenticate",
new BasicHeader("Authorization", basicAuthValue));
assertThat(response.getStatusLine().getStatusCode(), is(200));
RequestOptions.Builder optionsBuilder = RequestOptions.DEFAULT.toBuilder();
optionsBuilder.addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray())));
RequestOptions options = optionsBuilder.build();
Request rootRequest = new Request("GET", "/");
rootRequest.setOptions(options);
Response authorizedRootResponse = getRestClient().performRequest(rootRequest);
assertThat(authorizedRootResponse.getStatusLine().getStatusCode(), is(200));
Request authenticateRequest = new Request("GET", "/_xpack/security/_authenticate");
authenticateRequest.setOptions(options);
Response authorizedAuthenticateResponse = getRestClient().performRequest(authenticateRequest);
assertThat(authorizedAuthenticateResponse.getStatusLine().getStatusCode(), is(200));
}
public void testSecurityActionsByLicenseType() throws Exception {

View File

@ -5,12 +5,8 @@
*/
package org.elasticsearch.test;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicHeader;
import org.apache.http.nio.entity.NStringEntity;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.util.set.Sets;
@ -26,7 +22,6 @@ import org.junit.Before;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
/**
@ -82,23 +77,22 @@ public abstract class NativeRealmIntegTestCase extends SecurityIntegTestCase {
public void setupReservedPasswords(RestClient restClient) throws IOException {
logger.info("setting up reserved passwords for test");
{
String payload = "{\"password\": \"" + new String(reservedPassword.getChars()) + "\"}";
HttpEntity entity = new NStringEntity(payload, ContentType.APPLICATION_JSON);
BasicHeader authHeader = new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(ElasticUser.NAME, BOOTSTRAP_PASSWORD));
String route = "/_xpack/security/user/elastic/_password";
Response response = restClient.performRequest("PUT", route, Collections.emptyMap(), entity, authHeader);
assertEquals(response.getStatusLine().getReasonPhrase(), 200, response.getStatusLine().getStatusCode());
Request request = new Request("PUT", "/_xpack/security/user/elastic/_password");
request.setJsonEntity("{\"password\": \"" + new String(reservedPassword.getChars()) + "\"}");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(ElasticUser.NAME, BOOTSTRAP_PASSWORD));
request.setOptions(options);
restClient.performRequest(request);
}
RequestOptions.Builder optionsBuilder = RequestOptions.DEFAULT.toBuilder();
optionsBuilder.addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(ElasticUser.NAME, reservedPassword));
RequestOptions options = optionsBuilder.build();
for (String username : Arrays.asList(KibanaUser.NAME, LogstashSystemUser.NAME, BeatsSystemUser.NAME)) {
String payload = "{\"password\": \"" + new String(reservedPassword.getChars()) + "\"}";
HttpEntity entity = new NStringEntity(payload, ContentType.APPLICATION_JSON);
BasicHeader authHeader = new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(ElasticUser.NAME, reservedPassword));
String route = "/_xpack/security/user/" + username + "/_password";
Response response = restClient.performRequest("PUT", route, Collections.emptyMap(), entity, authHeader);
assertEquals(response.getStatusLine().getReasonPhrase(), 200, response.getStatusLine().getStatusCode());
Request request = new Request("PUT", "/_xpack/security/user/" + username + "/_password");
request.setJsonEntity("{\"password\": \"" + new String(reservedPassword.getChars()) + "\"}");
request.setOptions(options);
restClient.performRequest(request);
}
logger.info("setting up reserved passwords finished");
}

View File

@ -5,14 +5,14 @@
*/
package org.elasticsearch.xpack.security;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.test.SecurityIntegTestCase;
import org.elasticsearch.test.SecuritySettingsSource;
import org.elasticsearch.test.SecuritySettingsSourceField;
import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken;
import java.io.IOException;
@ -31,17 +31,20 @@ public class SecurityPluginTests extends SecurityIntegTestCase {
public void testThatPluginIsLoaded() throws IOException {
try {
logger.info("executing unauthorized request to /_xpack info");
getRestClient().performRequest("GET", "/_xpack");
getRestClient().performRequest(new Request("GET", "/_xpack"));
fail("request should have failed");
} catch(ResponseException e) {
assertThat(e.getResponse().getStatusLine().getStatusCode(), is(UNAUTHORIZED.getStatus()));
}
logger.info("executing authorized request to /_xpack infos");
Response response = getRestClient().performRequest("GET", "/_xpack",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))));
Request request = new Request("GET", "/_xpack");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization", basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray())));
request.setOptions(options);
Response response = getRestClient().performRequest(request);
assertThat(response.getStatusLine().getStatusCode(), is(OK.getStatus()));
}
}

View File

@ -5,12 +5,13 @@
*/
package org.elasticsearch.xpack.security.audit.index;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.common.settings.Settings;
@ -89,10 +90,12 @@ public class AuditTrailTests extends SecurityIntegTestCase {
public void testAuditAccessDeniedWithRunAsUser() throws Exception {
try {
getRestClient().performRequest("GET", "/.security/_search",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(AUTHENTICATE_USER, TEST_PASSWORD_SECURE_STRING)),
new BasicHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, EXECUTE_USER));
Request request = new Request("GET", "/.security/_search");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(AUTHENTICATE_USER, TEST_PASSWORD_SECURE_STRING));
options.addHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, EXECUTE_USER);
request.setOptions(options);
getRestClient().performRequest(request);
fail("request should have failed");
} catch (final ResponseException e) {
assertThat(e.getResponse().getStatusLine().getStatusCode(), is(403));
@ -111,10 +114,12 @@ public class AuditTrailTests extends SecurityIntegTestCase {
public void testAuditRunAsDeniedEmptyUser() throws Exception {
try {
getRestClient().performRequest("GET", "/.security/_search",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(AUTHENTICATE_USER, TEST_PASSWORD_SECURE_STRING)),
new BasicHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, ""));
Request request = new Request("GET", "/.security/_search");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(AUTHENTICATE_USER, TEST_PASSWORD_SECURE_STRING));
options.addHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, "");
request.setOptions(options);
getRestClient().performRequest(request);
fail("request should have failed");
} catch (final ResponseException e) {
assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401));

View File

@ -5,12 +5,12 @@
*/
package org.elasticsearch.xpack.security.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.Response;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.SecureString;
@ -126,11 +126,13 @@ public class RunAsIntegTests extends SecurityIntegTestCase {
public void testUserImpersonationUsingHttp() throws Exception {
// use the transport client user and try to run as
try {
getRestClient().performRequest("GET", "/_nodes",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(TRANSPORT_CLIENT_USER,
TEST_PASSWORD_SECURE_STRING)),
new BasicHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, SecuritySettingsSource.TEST_USER_NAME));
Request request = new Request("GET", "/_nodes");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization",
UsernamePasswordToken.basicAuthHeaderValue(TRANSPORT_CLIENT_USER, TEST_PASSWORD_SECURE_STRING));
options.addHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, SecuritySettingsSource.TEST_USER_NAME);
request.setOptions(options);
getRestClient().performRequest(request);
fail("request should have failed");
} catch(ResponseException e) {
assertThat(e.getResponse().getStatusLine().getStatusCode(), is(403));
@ -139,10 +141,11 @@ public class RunAsIntegTests extends SecurityIntegTestCase {
if (runAsHasSuperUserRole == false) {
try {
//the run as user shouldn't have access to the nodes api
getRestClient().performRequest("GET", "/_nodes",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER,
TEST_PASSWORD_SECURE_STRING)));
Request request = new Request("GET", "/_nodes");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, TEST_PASSWORD_SECURE_STRING));
request.setOptions(options);
getRestClient().performRequest(request);
fail("request should have failed");
} catch (ResponseException e) {
assertThat(e.getResponse().getStatusLine().getStatusCode(), is(403));
@ -150,12 +153,7 @@ public class RunAsIntegTests extends SecurityIntegTestCase {
}
// but when running as a different user it should work
Response response = getRestClient().performRequest("GET", "/_nodes",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER,
TEST_PASSWORD_SECURE_STRING)),
new BasicHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, SecuritySettingsSource.TEST_USER_NAME));
assertThat(response.getStatusLine().getStatusCode(), is(200));
getRestClient().performRequest(requestForUserRunAsUser(SecuritySettingsSource.TEST_USER_NAME));
}
public void testEmptyUserImpersonationHeader() throws Exception {
@ -183,11 +181,7 @@ public class RunAsIntegTests extends SecurityIntegTestCase {
public void testEmptyHeaderUsingHttp() throws Exception {
try {
getRestClient().performRequest("GET", "/_nodes",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER,
TEST_PASSWORD_SECURE_STRING)),
new BasicHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, ""));
getRestClient().performRequest(requestForUserRunAsUser(""));
fail("request should have failed");
} catch(ResponseException e) {
assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401));
@ -219,17 +213,22 @@ public class RunAsIntegTests extends SecurityIntegTestCase {
public void testNonExistentRunAsUserUsingHttp() throws Exception {
try {
getRestClient().performRequest("GET", "/_nodes",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER,
TEST_PASSWORD_SECURE_STRING)),
new BasicHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, "idontexist"));
getRestClient().performRequest(requestForUserRunAsUser("idontexist"));
fail("request should have failed");
} catch (ResponseException e) {
assertThat(e.getResponse().getStatusLine().getStatusCode(), is(403));
}
}
private static Request requestForUserRunAsUser(String user) {
Request request = new Request("GET", "/_nodes");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(RUN_AS_USER, TEST_PASSWORD_SECURE_STRING));
options.addHeader(AuthenticationServiceField.RUN_AS_USER_HEADER, user);
request.setOptions(options);
return request;
}
// build our own here to better mimic an actual client...
TransportClient getTransportClient(Settings extraSettings) {
NodesInfoResponse nodeInfos = client().admin().cluster().prepareNodesInfo().get();

View File

@ -5,8 +5,9 @@
*/
package org.elasticsearch.xpack.security.authc.pki;
import org.apache.http.message.BasicHeader;
import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient;
@ -76,13 +77,15 @@ public class PkiOptionalClientAuthTests extends SecuritySingleNodeTestCase {
public void testRestClientWithoutClientCertificate() throws Exception {
SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(getSSLContext());
try (RestClient restClient = createRestClient(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy), "https")) {
ResponseException e = expectThrows(ResponseException.class, () -> restClient.performRequest("GET", "_nodes"));
ResponseException e = expectThrows(ResponseException.class, () -> restClient.performRequest(new Request("GET", "_nodes")));
assertThat(e.getResponse().getStatusLine().getStatusCode(), is(401));
Response response = restClient.performRequest("GET", "_nodes",
new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))));
Request request = new Request("GET", "_nodes");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray())));
request.setOptions(options);
Response response = restClient.performRequest(request);
assertThat(response.getStatusLine().getStatusCode(), is(200));
}
}

View File

@ -5,7 +5,8 @@
*/
package org.elasticsearch.xpack.security.rest.action;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.common.settings.SecureString;
@ -52,11 +53,12 @@ public class RestAuthenticateActionTests extends SecurityIntegTestCase {
}
public void testAuthenticateApi() throws Exception {
Response response = getRestClient().performRequest("GET", "/_xpack/security/_authenticate",
new BasicHeader("Authorization", basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()))));
assertThat(response.getStatusLine().getStatusCode(), is(200));
ObjectPath objectPath = ObjectPath.createFromResponse(response);
Request request = new Request("GET", "/_xpack/security/_authenticate");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization", basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray())));
request.setOptions(options);
ObjectPath objectPath = ObjectPath.createFromResponse(getRestClient().performRequest(request));
assertThat(objectPath.evaluate("username").toString(), equalTo(SecuritySettingsSource.TEST_USER_NAME));
List<String> roles = objectPath.evaluate("roles");
assertThat(roles.size(), is(1));
@ -65,7 +67,7 @@ public class RestAuthenticateActionTests extends SecurityIntegTestCase {
public void testAuthenticateApiWithoutAuthentication() throws Exception {
try {
Response response = getRestClient().performRequest("GET", "/_xpack/security/_authenticate");
Response response = getRestClient().performRequest(new Request("GET", "/_xpack/security/_authenticate"));
if (anonymousEnabled) {
assertThat(response.getStatusLine().getStatusCode(), is(200));
ObjectPath objectPath = ObjectPath.createFromResponse(response);

View File

@ -6,6 +6,7 @@
package org.elasticsearch.xpack.security.user;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.common.settings.Settings;
@ -46,7 +47,7 @@ public class AnonymousUserIntegTests extends SecurityIntegTestCase {
public void testAnonymousViaHttp() throws Exception {
try {
getRestClient().performRequest("GET", "/_nodes");
getRestClient().performRequest(new Request("GET", "/_nodes"));
fail("request should have failed");
} catch(ResponseException e) {
int statusCode = e.getResponse().getStatusLine().getStatusCode();

View File

@ -6,12 +6,13 @@
package org.elasticsearch.xpack.ssl;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.message.BasicHeader;
import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.transport.TransportClient;
@ -71,7 +72,7 @@ public class SSLClientAuthTests extends SecurityIntegTestCase {
public void testThatHttpFailsWithoutSslClientAuth() throws IOException {
SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(SSLContexts.createDefault(), NoopHostnameVerifier.INSTANCE);
try (RestClient restClient = createRestClient(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy), "https")) {
restClient.performRequest("GET", "/");
restClient.performRequest(new Request("GET", "/"));
fail("Expected SSLHandshakeException");
} catch (IOException e) {
Throwable t = ExceptionsHelper.unwrap(e, CertPathBuilderException.class);
@ -87,8 +88,11 @@ public class SSLClientAuthTests extends SecurityIntegTestCase {
public void testThatHttpWorksWithSslClientAuth() throws IOException {
SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(getSSLContext(), NoopHostnameVerifier.INSTANCE);
try (RestClient restClient = createRestClient(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy), "https")) {
Response response = restClient.performRequest("GET", "/",
new BasicHeader("Authorization", basicAuthHeaderValue(transportClientUsername(), transportClientPassword())));
Request request = new Request("GET", "/");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization", basicAuthHeaderValue(transportClientUsername(), transportClientPassword()));
request.setOptions(options);
Response response = restClient.performRequest(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
assertThat(EntityUtils.toString(response.getEntity()), containsString("You Know, for Search"));
}