Skip to content

Commit

Permalink
Switch remaining x-pack tests to new style Requests
Browse files Browse the repository at this point in the history
In elastic#29623 we added `Request` object flavored requests to the low level
REST client and in elastic#30315 we deprecated the old `performRequest`s. This
changes all calls in the `x-pack/qa/saml-idp-tests` and
`x-pack/qa/security-setup-password-tests` projects to use the new
versions.
  • Loading branch information
nik9000 committed Aug 23, 2018
1 parent 8f8d3a5 commit 4db99d5
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 46 deletions.
Expand Up @@ -120,8 +120,10 @@ public void testMonitoringBulk() throws Exception {

// REST is the realistic way that these operations happen, so it's the most realistic way to integration test it too
// Use Monitoring Bulk API to index 3 documents
//final Response bulkResponse = getRestClient().performRequest("POST", "/_xpack/monitoring/_bulk",
// parameters, createBulkEntity());
//final Request bulkRequest = new Request("POST", "/_xpack/monitoring/_bulk");
//<<add all parameters>
//bulkRequest.setJsonEntity(createBulkEntity());
//final Response bulkResponse = getRestClient().performRequest(request);

final MonitoringBulkResponse bulkResponse =
new MonitoringBulkRequestBuilder(client())
Expand Down
Expand Up @@ -24,8 +24,6 @@
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.DefaultCookieSpec;
Expand All @@ -39,6 +37,8 @@
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cli.SuppressForbidden;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.common.CheckedFunction;
import org.elasticsearch.common.Strings;
Expand Down Expand Up @@ -85,7 +85,6 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.Collections.emptyMap;
import static org.elasticsearch.common.xcontent.XContentHelper.convertToMap;
import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
import static org.hamcrest.Matchers.contains;
Expand Down Expand Up @@ -176,9 +175,9 @@ protected Settings restAdminSettings() {
*/
@Before
public void setKibanaPassword() throws IOException {
final HttpEntity json = new StringEntity("{ \"password\" : \"" + KIBANA_PASSWORD + "\" }", ContentType.APPLICATION_JSON);
final Response response = adminClient().performRequest("PUT", "/_xpack/security/user/kibana/_password", emptyMap(), json);
assertOK(response);
Request request = new Request("PUT", "/_xpack/security/user/kibana/_password");
request.setJsonEntity("{ \"password\" : \"" + KIBANA_PASSWORD + "\" }");
adminClient().performRequest(request);
}

/**
Expand All @@ -188,21 +187,19 @@ public void setKibanaPassword() throws IOException {
*/
@Before
public void setupRoleMapping() throws IOException {
final StringEntity json = new StringEntity(Strings // top-level
.toString(XContentBuilder.builder(XContentType.JSON.xContent())
.startObject()
.array("roles", new String[] { "kibana_user"} )
.field("enabled", true)
.startObject("rules")
Request request = new Request("PUT", "/_xpack/security/role_mapping/thor-kibana");
request.setJsonEntity(Strings.toString(XContentBuilder.builder(XContentType.JSON.xContent())
.startObject()
.array("roles", new String[] { "kibana_user"} )
.field("enabled", true)
.startObject("rules")
.startArray("all")
.startObject().startObject("field").field("username", "thor").endObject().endObject()
.startObject().startObject("field").field("realm.name", "shibboleth").endObject().endObject()
.startObject().startObject("field").field("username", "thor").endObject().endObject()
.startObject().startObject("field").field("realm.name", "shibboleth").endObject().endObject()
.endArray() // "all"
.endObject() // "rules"
.endObject()), ContentType.APPLICATION_JSON);

final Response response = adminClient().performRequest("PUT", "/_xpack/security/role_mapping/thor-kibana", emptyMap(), json);
assertOK(response);
.endObject() // "rules"
.endObject()));
adminClient().performRequest(request);
}

/**
Expand Down Expand Up @@ -251,10 +248,11 @@ public void testLoginUser() throws Exception {
* is for the expected user with the expected name and roles.
*/
private void verifyElasticsearchAccessToken(String accessToken) throws IOException {
final BasicHeader authorization = new BasicHeader("Authorization", "Bearer " + accessToken);
final Response response = client().performRequest("GET", "/_xpack/security/_authenticate", authorization);
assertOK(response);
final Map<String, Object> map = parseResponseAsMap(response.getEntity());
Request request = new Request("GET", "/_xpack/security/_authenticate");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization", "Bearer " + accessToken);
request.setOptions(options);
final Map<String, Object> map = entityAsMap(client().performRequest(request));
assertThat(map.get("username"), equalTo("thor"));
assertThat(map.get("full_name"), equalTo("Thor Odinson"));
assertSingletonList(map.get("roles"), "kibana_user");
Expand All @@ -272,12 +270,11 @@ private void verifyElasticsearchAccessToken(String accessToken) throws IOExcepti
* can be used to get a new valid access token and refresh token.
*/
private void verifyElasticsearchRefreshToken(String refreshToken) throws IOException {
final String body = "{ \"grant_type\":\"refresh_token\", \"refresh_token\":\"" + refreshToken + "\" }";
final Response response = client().performRequest("POST", "/_xpack/security/oauth2/token",
emptyMap(), new StringEntity(body, ContentType.APPLICATION_JSON), kibanaAuth());
assertOK(response);
Request request = new Request("POST", "/_xpack/security/oauth2/token");
request.setJsonEntity("{ \"grant_type\":\"refresh_token\", \"refresh_token\":\"" + refreshToken + "\" }");
kibanaAuth(request);

final Map<String, Object> result = parseResponseAsMap(response.getEntity());
final Map<String, Object> result = entityAsMap(client().performRequest(request));
final Object newRefreshToken = result.get("refresh_token");
assertThat(newRefreshToken, notNullValue());
assertThat(newRefreshToken, instanceOf(String.class));
Expand Down Expand Up @@ -463,10 +460,10 @@ private String getUrl(String path) {
* sends a redirect to that page.
*/
private void httpLogin(HttpExchange http) throws IOException {
final Response prepare = client().performRequest("POST", "/_xpack/security/saml/prepare",
emptyMap(), new StringEntity("{}", ContentType.APPLICATION_JSON), kibanaAuth());
assertOK(prepare);
final Map<String, Object> body = parseResponseAsMap(prepare.getEntity());
Request request = new Request("POST", "/_xpack/security/saml/prepare");
request.setJsonEntity("{}");
kibanaAuth(request);
final Map<String, Object> body = entityAsMap(client().performRequest(request));
logger.info("Created SAML authentication request {}", body);
http.getResponseHeaders().add("Set-Cookie", REQUEST_ID_COOKIE + "=" + body.get("id"));
http.getResponseHeaders().add("Location", (String) body.get("redirect"));
Expand Down Expand Up @@ -504,9 +501,10 @@ private Response samlAuthenticate(HttpExchange http) throws IOException {
final String id = getCookie(REQUEST_ID_COOKIE, http);
assertThat(id, notNullValue());

final String body = "{ \"content\" : \"" + saml + "\", \"ids\": [\"" + id + "\"] }";
return client().performRequest("POST", "/_xpack/security/saml/authenticate",
emptyMap(), new StringEntity(body, ContentType.APPLICATION_JSON), kibanaAuth());
Request request = new Request("POST", "/_xpack/security/saml/authenticate");
request.setJsonEntity("{ \"content\" : \"" + saml + "\", \"ids\": [\"" + id + "\"] }");
kibanaAuth(request);
return client().performRequest(request);
}

private List<NameValuePair> parseRequestForm(HttpExchange http) throws IOException {
Expand Down Expand Up @@ -542,9 +540,11 @@ private static void assertSingletonList(Object value, String expectedElement) {
assertThat(((List<?>) value), contains(expectedElement));
}

private static BasicHeader kibanaAuth() {
final String auth = UsernamePasswordToken.basicAuthHeaderValue("kibana", new SecureString(KIBANA_PASSWORD.toCharArray()));
return new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER, auth);
private static void kibanaAuth(Request request) {
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization",
UsernamePasswordToken.basicAuthHeaderValue("kibana", new SecureString(KIBANA_PASSWORD.toCharArray())));
request.setOptions(options);
}

private CloseableHttpClient getHttpClient() throws Exception {
Expand Down
Expand Up @@ -5,8 +5,9 @@
*/
package org.elasticsearch.xpack.security.authc.esnative.tool;

import org.apache.http.message.BasicHeader;
import org.elasticsearch.cli.MockTerminal;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.SuppressForbidden;
Expand Down Expand Up @@ -52,7 +53,7 @@ public void testSetupPasswordToolAutoSetup() throws Exception {
final Path configPath = PathUtils.get(testConfigDir);
setSystemPropsForTool(configPath);

Response nodesResponse = client().performRequest("GET", "/_nodes/http");
Response nodesResponse = client().performRequest(new Request("GET", "/_nodes/http"));
Map<String, Object> nodesMap = entityAsMap(nodesResponse);

Map<String,Object> nodes = (Map<String,Object>) nodesMap.get("nodes");
Expand Down Expand Up @@ -102,10 +103,11 @@ public void testSetupPasswordToolAutoSetup() throws Exception {
final String basicHeader = "Basic " +
Base64.getEncoder().encodeToString((entry.getKey() + ":" + entry.getValue()).getBytes(StandardCharsets.UTF_8));
try {
Response authenticateResponse = client().performRequest("GET", "/_xpack/security/_authenticate",
new BasicHeader("Authorization", basicHeader));
assertEquals(200, authenticateResponse.getStatusLine().getStatusCode());
Map<String, Object> userInfoMap = entityAsMap(authenticateResponse);
Request request = new Request("GET", "/_xpack/security/_authenticate");
RequestOptions.Builder options = request.getOptions().toBuilder();
options.addHeader("Authorization", basicHeader);
request.setOptions(options);
Map<String, Object> userInfoMap = entityAsMap(client().performRequest(request));
assertEquals(entry.getKey(), userInfoMap.get("username"));
} catch (IOException e) {
throw new UncheckedIOException(e);
Expand Down

0 comments on commit 4db99d5

Please sign in to comment.