Search in sources :

Example 71 with BasicHeader

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());
    }
}
Also used : Response(org.elasticsearch.client.Response) ResponseException(org.elasticsearch.client.ResponseException) BasicHeader(org.apache.http.message.BasicHeader)

Example 72 with BasicHeader

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"));
}
Also used : Response(org.elasticsearch.client.Response) BasicHeader(org.apache.http.message.BasicHeader)

Example 73 with BasicHeader

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"));
}
Also used : Response(org.elasticsearch.client.Response) BasicHeader(org.apache.http.message.BasicHeader)

Example 74 with BasicHeader

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();
}
Also used : Path(java.nio.file.Path) InputStream(java.io.InputStream) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) SSLIOSessionStrategy(org.apache.http.nio.conn.ssl.SSLIOSessionStrategy) CertificateException(java.security.cert.CertificateException) SSLContext(javax.net.ssl.SSLContext) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(java.security.KeyStore) KeyManagementException(java.security.KeyManagementException) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap) BasicHeader(org.apache.http.message.BasicHeader)

Example 75 with BasicHeader

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);
    }
}
Also used : HashMap(java.util.HashMap) ResponseException(org.elasticsearch.client.ResponseException) ClientYamlSuiteRestPath(org.elasticsearch.test.rest.yaml.restspec.ClientYamlSuiteRestPath) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) Response(org.elasticsearch.client.Response) ClientYamlSuiteRestApi(org.elasticsearch.test.rest.yaml.restspec.ClientYamlSuiteRestApi) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) HashMap(java.util.HashMap) Map(java.util.Map) BasicHeader(org.apache.http.message.BasicHeader)

Aggregations

BasicHeader (org.apache.http.message.BasicHeader)128 Header (org.apache.http.Header)67 Test (org.junit.Test)29 List (java.util.List)21 HashMap (java.util.HashMap)19 HttpGet (org.apache.http.client.methods.HttpGet)18 BasicStatusLine (org.apache.http.message.BasicStatusLine)17 ProtocolVersion (org.apache.http.ProtocolVersion)16 StatusLine (org.apache.http.StatusLine)16 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)16 IOException (java.io.IOException)15 HttpURLConnection (java.net.HttpURLConnection)15 URL (java.net.URL)15 HttpResponse (org.apache.http.HttpResponse)15 Response (org.elasticsearch.client.Response)10 ArrayList (java.util.ArrayList)9 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)9 TestHttpResponse (org.robolectric.shadows.httpclient.TestHttpResponse)9 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)8 StringEntity (org.apache.http.entity.StringEntity)8