Skip to content
Open
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Inspired from [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
### Removed

### Fixed
- Send the headers declared by an `Endpoint` (e.g. the headers of a generic client `Request`) from `RestClientTransport`, `ApacheHttpClient5Transport` and `AwsSdk2Transport`; they were silently dropped ([#1234](https://github.com/opensearch-project/opensearch-java/issues/1234))
- Declare the dependencies the streaming support of `ApacheHttpClient5Transport` needs, without which building the transport failed with `NoClassDefFoundError: org/reactivestreams/Publisher` ([#2294](https://github.com/opensearch-project/opensearch-java/issues/2294))

### Security
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ private <RequestT> SignedRequest prepareRequest(

ContentStreamProvider bodyProvider = body != null ? ContentStreamProvider.fromByteArrayUnsafe(body.getByteArray()) : null;

applyHeadersPreSigning(req, options, body);
applyHeadersPreSigning(req, endpoint.headers(request), options, body);

final AwsCredentialsProvider credentials = getOption(options, AwsSdk2TransportOptions::credentials).orElseGet(
DefaultCredentialsProvider::create
Expand All @@ -392,10 +392,22 @@ private <RequestT> SignedRequest prepareRequest(
return signedReq.toBuilder().request(httpRequest.build()).build();
}

private void applyHeadersPreSigning(SdkHttpRequest.Builder req, TransportOptions options, OpenSearchRequestBodyBuffer body) {
private void applyHeadersPreSigning(
SdkHttpRequest.Builder req,
Map<String, String> endpointHeaders,
TransportOptions options,
OpenSearchRequestBodyBuffer body
) {
applyOptionsHeaders(req, transportOptions);
applyOptionsHeaders(req, options);

// Headers of the options take precedence over the headers of the endpoint
endpointHeaders.forEach((name, value) -> {
if (req.firstMatchingHeader(name).isPresent() == false) {
req.appendHeader(name, value);
}
});

if (body != null) {
req.putHeader("Content-Type", body.getContentType());
String encoding = body.getContentEncoding();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -792,9 +792,18 @@ private <RequestT> HttpUriRequestBase prepareLowLevelRequest(
addRequestBody(clientReq, new ByteArrayEntity(baos.array(), 0, baos.size(), contentType));
}

if (options != null) {
setHeaders(clientReq, options.headers());
// Headers of the options take precedence over the headers of the endpoint
final Collection<Entry<String, String>> optionHeaders = options == null ? Collections.emptyList() : options.headers();
final Collection<Entry<String, String>> headers = new ArrayList<>();
for (Entry<String, String> endpointHeader : endpoint.headers(request).entrySet()) {
if (optionHeaders.stream().noneMatch(h -> h.getKey().equalsIgnoreCase(endpointHeader.getKey()))) {
headers.add(endpointHeader);
}
}
headers.addAll(optionHeaders);
setHeaders(clientReq, headers);

if (options != null) {
if (options.getRequestConfig() != null) {
clientReq.setConfig(options.getRequestConfig());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,18 @@ private <RequestT> org.opensearch.client.Request prepareLowLevelRequest(
? transportOptions.restClientRequestOptions()
: RestClientOptions.of(options).restClientRequestOptions();

final Map<String, String> endpointHeaders = endpoint.headers(request);
if (endpointHeaders.isEmpty() == false) {// Headers of the options take precedence over the headers of the endpoint
final RequestOptions baseOptions = restOptions == null ? RequestOptions.DEFAULT : restOptions;
final RequestOptions.Builder restOptionsBuilder = baseOptions.toBuilder();
endpointHeaders.forEach((name, value) -> {
if (baseOptions.getHeaders().stream().noneMatch(h -> h.getName().equalsIgnoreCase(name))) {
restOptionsBuilder.addHeader(name, value);
}
});
restOptions = restOptionsBuilder.build();
}

if (restOptions != null) {
clientReq.setOptions(restOptions);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/

package org.opensearch.client.transport;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.hc.core5.http.HttpHost;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opensearch.client.RestClient;
import org.opensearch.client.json.jackson.JacksonJsonpMapper;
import org.opensearch.client.opensearch.OpenSearchClient;
import org.opensearch.client.opensearch.generic.Requests;
import org.opensearch.client.transport.httpclient5.ApacheHttpClient5TransportBuilder;
import org.opensearch.client.transport.rest_client.RestClientTransport;

/**
* Verifies that the headers of a generic client request reach the server, in addition to the headers of the transport options.
*/
public class RequestHeadersTest extends Assert {

private HttpServer httpServer;
private final List<Headers> receivedHeaders = Collections.synchronizedList(new ArrayList<>());

@Before
public void setup() throws IOException {
httpServer = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
httpServer.createContext("/", ex -> {
receivedHeaders.add(ex.getRequestHeaders());
ex.sendResponseHeaders(200, -1);
ex.close();
});
httpServer.start();
}

@After
public void tearDown() {
httpServer.stop(0);
}

@Test
public void testRestClientTransport() throws IOException {
InetSocketAddress address = httpServer.getAddress();
HttpHost host = new HttpHost("http", address.getHostString(), address.getPort());

try (OpenSearchTransport transport = new RestClientTransport(RestClient.builder(host).build(), new JacksonJsonpMapper())) {
assertHeadersSent(transport);
}
}

@Test
public void testApacheHttpClient5Transport() throws Exception {
InetSocketAddress address = httpServer.getAddress();
HttpHost host = new HttpHost("http", address.getHostString(), address.getPort());

try (OpenSearchTransport transport = ApacheHttpClient5TransportBuilder.builder(host).build()) {
assertHeadersSent(transport);
}
}

// Scenario: a generic request has two headers and the transport options have another one plus one of the same name (different
// letter case) as a request header.
// Expected: the server receives all the distinct headers, and only the value of the options for the shared one.
private void assertHeadersSent(OpenSearchTransport transport) throws IOException {
OpenSearchClient client = new OpenSearchClient(transport).withTransportOptions(
transport.options().with(b -> b.addHeader("X-Option-Header", "option-value").addHeader("x-shared-header", "option-shared"))
);

client.generic()
.execute(
Requests.builder()
.method("POST")
.endpoint("/")
.headers(
Arrays.asList(
new AbstractMap.SimpleEntry<>("X-Request-Header", "request-value"),
new AbstractMap.SimpleEntry<>("X-Shared-Header", "request-shared")
)
)
.json("{}")
.build()
);

assertEquals(1, receivedHeaders.size());
Headers headers = receivedHeaders.get(0);
assertEquals("request-value", headers.getFirst("X-Request-Header"));
assertEquals("option-value", headers.getFirst("X-Option-Header"));
assertEquals(Collections.singletonList("option-shared"), headers.get("X-Shared-Header"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,11 @@
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -211,6 +214,10 @@ public String getRequestUri() {
public String getHeader(String name) throws ProtocolException {
return Optional.ofNullable(request.getHeader(name)).map(Header::getValue).orElse(null);
}

public List<String> getHeaderValues(String name) {
return Arrays.stream(request.getHeaders(name)).map(Header::getValue).collect(Collectors.toList());
}
}

private HttpRequestHandler hardcodedJsonHandler(String json) {
Expand Down Expand Up @@ -402,6 +409,44 @@ public void testOptionsWithBody() throws Exception {
);
}

// Scenario: a generic request carries a custom header. Expected: the server receives it.
@Test
public void testGenericRequestHeadersAreSent() throws Exception {
Requests.JsonBodyBuilder request = Requests.builder()
.method("POST")
.endpoint("/")
.headers(Collections.singletonList(new AbstractMap.SimpleEntry<>("X-Test-Header", "test-value")))
.json("{}");

getTestClient().generic().execute(request.build());

ReceivedRequest req = receivedRequests.poll();
assertNotNull(req);
assertEquals("test-value", req.getHeader("X-Test-Header"));
}

// Scenario: a generic request and the transport options set the same header, with different letter case.
// Expected: the server receives only the value of the transport options.
@Test
public void testOptionHeadersTakePrecedenceOverGenericRequestHeaders() throws Exception {
OpenSearchClient client = getTestClient();
client = client.withTransportOptions(client._transport().options().with(b -> b.addHeader("x-test-header", "option-value")));

client.generic()
.execute(
Requests.builder()
.method("POST")
.endpoint("/")
.headers(Collections.singletonList(new AbstractMap.SimpleEntry<>("X-Test-Header", "request-value")))
.json("{}")
.build()
);

ReceivedRequest req = receivedRequests.poll();
assertNotNull(req);
assertEquals(Collections.singletonList("option-value"), req.getHeaderValues("X-Test-Header"));
}

private void assertSigV4Request(
OpenSearchClientAction request,
String method,
Expand Down
Loading