Skip to content

Switch remaining x-pack tests to new style Requests #33108

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 24, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
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);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shall we remove rather than leave it commented out?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is there to tell us to convert one day so I figured I'd keep it.


final MonitoringBulkResponse bulkResponse =
new MonitoringBulkRequestBuilder(client())
Expand Down
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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