use of org.apache.http.message.BasicHeader in project elasticsearch by elastic.
the class CorsRegexIT method testThatPreFlightRequestReturnsNullOnNonMatch.
public void testThatPreFlightRequestReturnsNullOnNonMatch() throws IOException {
try {
getRestClient().performRequest("OPTIONS", "/", new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", "http://evil-host:9200"), new BasicHeader("Access-Control-Request-Method", "GET"));
fail("request should have failed");
} catch (ResponseException e) {
Response response = e.getResponse();
// a rejected origin gets a FORBIDDEN - 403
assertThat(response.getStatusLine().getStatusCode(), is(403));
assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue());
assertThat(response.getHeader("Access-Control-Allow-Methods"), nullValue());
}
}
use of org.apache.http.message.BasicHeader in project elasticsearch by elastic.
the class CorsRegexIT method testThatRegularExpressionWorksOnMatch.
public void testThatRegularExpressionWorksOnMatch() throws IOException {
String corsValue = "http://localhost:9200";
Response response = getRestClient().performRequest("GET", "/", new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue));
assertResponseWithOriginheader(response, corsValue);
corsValue = "https://localhost:9200";
response = getRestClient().performRequest("GET", "/", new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue));
assertResponseWithOriginheader(response, corsValue);
assertThat(response.getHeader("Access-Control-Allow-Credentials"), is("true"));
}
use of org.apache.http.message.BasicHeader in project elasticsearch by elastic.
the class CorsRegexIT method testThatPreFlightRequestWorksOnMatch.
public void testThatPreFlightRequestWorksOnMatch() throws IOException {
String corsValue = "http://localhost:9200";
Response response = getRestClient().performRequest("OPTIONS", "/", new BasicHeader("User-Agent", "Mozilla Bar"), new BasicHeader("Origin", corsValue), new BasicHeader("Access-Control-Request-Method", "GET"));
assertResponseWithOriginheader(response, corsValue);
assertNotNull(response.getHeader("Access-Control-Allow-Methods"));
}
use of org.apache.http.message.BasicHeader in project elasticsearch by elastic.
the class ESRestTestCase method buildClient.
protected RestClient buildClient(Settings settings, HttpHost[] hosts) throws IOException {
RestClientBuilder builder = RestClient.builder(hosts);
String keystorePath = settings.get(TRUSTSTORE_PATH);
if (keystorePath != null) {
final String keystorePass = settings.get(TRUSTSTORE_PASSWORD);
if (keystorePass == null) {
throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD);
}
Path path = PathUtils.get(keystorePath);
if (!Files.exists(path)) {
throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file");
}
try {
KeyStore keyStore = KeyStore.getInstance("jks");
try (InputStream is = Files.newInputStream(path)) {
keyStore.load(is, keystorePass.toCharArray());
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build();
SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslcontext);
builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy));
} catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException | CertificateException e) {
throw new RuntimeException("Error setting up ssl", e);
}
}
try (ThreadContext threadContext = new ThreadContext(settings)) {
Header[] defaultHeaders = new Header[threadContext.getHeaders().size()];
int i = 0;
for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) {
defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue());
}
builder.setDefaultHeaders(defaultHeaders);
}
return builder.build();
}
use of org.apache.http.message.BasicHeader in project elasticsearch by elastic.
the class ClientYamlTestClient method callApi.
/**
* Calls an api with the provided parameters and body
*/
public ClientYamlTestResponse callApi(String apiName, Map<String, String> params, HttpEntity entity, Map<String, String> headers) throws IOException {
if ("raw".equals(apiName)) {
// Raw requests are bit simpler....
Map<String, String> queryStringParams = new HashMap<>(params);
String method = Objects.requireNonNull(queryStringParams.remove("method"), "Method must be set to use raw request");
String path = "/" + Objects.requireNonNull(queryStringParams.remove("path"), "Path must be set to use raw request");
// And everything else is a url parameter!
try {
Response response = restClient.performRequest(method, path, queryStringParams, entity);
return new ClientYamlTestResponse(response);
} catch (ResponseException e) {
throw new ClientYamlTestResponseException(e);
}
}
ClientYamlSuiteRestApi restApi = restApi(apiName);
//divide params between ones that go within query string and ones that go within path
Map<String, String> pathParts = new HashMap<>();
Map<String, String> queryStringParams = new HashMap<>();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (restApi.getPathParts().contains(entry.getKey())) {
pathParts.put(entry.getKey(), entry.getValue());
} else {
if (restApi.getParams().contains(entry.getKey()) || restSpec.isGlobalParameter(entry.getKey()) || restSpec.isClientParameter(entry.getKey())) {
queryStringParams.put(entry.getKey(), entry.getValue());
} else {
throw new IllegalArgumentException("param [" + entry.getKey() + "] not supported in [" + restApi.getName() + "] " + "api");
}
}
}
List<String> supportedMethods = restApi.getSupportedMethods(pathParts.keySet());
String requestMethod;
if (entity != null) {
if (!restApi.isBodySupported()) {
throw new IllegalArgumentException("body is not supported by [" + restApi.getName() + "] api");
}
String contentType = entity.getContentType().getValue();
//randomly test the GET with source param instead of GET/POST with body
if (sendBodyAsSourceParam(supportedMethods, contentType)) {
logger.debug("sending the request body as source param with GET method");
queryStringParams.put("source", EntityUtils.toString(entity));
queryStringParams.put("source_content_type", contentType);
requestMethod = HttpGet.METHOD_NAME;
entity = null;
} else {
requestMethod = RandomizedTest.randomFrom(supportedMethods);
}
} else {
if (restApi.isBodyRequired()) {
throw new IllegalArgumentException("body is required by [" + restApi.getName() + "] api");
}
requestMethod = RandomizedTest.randomFrom(supportedMethods);
}
//the rest path to use is randomized out of the matching ones (if more than one)
ClientYamlSuiteRestPath restPath = RandomizedTest.randomFrom(restApi.getFinalPaths(pathParts));
//Encode rules for path and query string parameters are different. We use URI to encode the path.
//We need to encode each path part separately, as each one might contain slashes that need to be escaped, which needs to
//be done manually.
String requestPath;
if (restPath.getPathParts().length == 0) {
requestPath = "/";
} else {
StringBuilder finalPath = new StringBuilder();
for (String pathPart : restPath.getPathParts()) {
try {
finalPath.append('/');
// We append "/" to the path part to handle parts that start with - or other invalid characters
URI uri = new URI(null, null, null, -1, "/" + pathPart, null, null);
//manually escape any slash that each part may contain
finalPath.append(uri.getRawPath().substring(1).replaceAll("/", "%2F"));
} catch (URISyntaxException e) {
throw new RuntimeException("unable to build uri", e);
}
}
requestPath = finalPath.toString();
}
Header[] requestHeaders = new Header[headers.size()];
int index = 0;
for (Map.Entry<String, String> header : headers.entrySet()) {
logger.info("Adding header {}\n with value {}", header.getKey(), header.getValue());
requestHeaders[index++] = new BasicHeader(header.getKey(), header.getValue());
}
logger.debug("calling api [{}]", apiName);
try {
Response response = restClient.performRequest(requestMethod, requestPath, queryStringParams, entity, requestHeaders);
return new ClientYamlTestResponse(response);
} catch (ResponseException e) {
throw new ClientYamlTestResponseException(e);
}
}
Aggregations