Merge pull request #2976 from bratwurzt/issue_2975

Empty/null username and password in ElasticsearchHibernatePropertiesBuilder throws exception, multiple hosts not possible
This commit is contained in:
Tadgh 2021-09-10 10:55:05 -04:00 committed by GitHub
commit 3e55f47a03
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 91 additions and 78 deletions

View File

@ -31,12 +31,11 @@ In addition, the Elasticsearch client service, `ElasticsearchSvcImpl` will need
```java ```java
@Bean() @Bean()
public ElasticsearchSvcImpl elasticsearchSvc() { public ElasticsearchSvcImpl elasticsearchSvc() {
String elasticsearchHost = "localhost"; String elasticsearchHost = "localhost:9200";
String elasticsearchUserId = "elastic"; String elasticsearchUsername = "elastic";
String elasticsearchPassword = "changeme"; String elasticsearchPassword = "changeme";
int elasticsearchPort = 9301;
return new ElasticsearchSvcImpl(elasticsearchHost, elasticsearchPort, elasticsearchUserId, elasticsearchPassword); return new ElasticsearchSvcImpl(elasticsearchHost, elasticsearchUsername, elasticsearchPassword);
} }
``` ```

View File

@ -1087,7 +1087,7 @@ public class SearchCoordinatorSvcImpl implements ISearchCoordinatorSvc {
ourLog.trace("Performing count"); ourLog.trace("Performing count");
ISearchBuilder sb = newSearchBuilder(); ISearchBuilder sb = newSearchBuilder();
Iterator<Long> countIterator = sb.createCountQuery(myParams, mySearch.getUuid(), myRequest, myRequestPartitionId); Iterator<Long> countIterator = sb.createCountQuery(myParams, mySearch.getUuid(), myRequest, myRequestPartitionId);
Long count = countIterator.hasNext() ? countIterator.next() : 0; Long count = countIterator.hasNext() ? countIterator.next() : 0L;
ourLog.trace("Got count {}", count); ourLog.trace("Got count {}", count);
TransactionTemplate txTemplate = new TransactionTemplate(myManagedTxManager); TransactionTemplate txTemplate = new TransactionTemplate(myManagedTxManager);

View File

@ -37,6 +37,7 @@ import org.hibernate.search.backend.elasticsearch.cfg.ElasticsearchIndexSettings
import org.hibernate.search.mapper.orm.schema.management.SchemaManagementStrategyName; import org.hibernate.search.mapper.orm.schema.management.SchemaManagementStrategyName;
import org.slf4j.Logger; import org.slf4j.Logger;
import javax.annotation.Nullable;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Properties; import java.util.Properties;
@ -49,13 +50,13 @@ import static org.slf4j.LoggerFactory.getLogger;
* FHIR JPA server. This class also injects a starter template into the ES cluster. * FHIR JPA server. This class also injects a starter template into the ES cluster.
*/ */
public class ElasticsearchHibernatePropertiesBuilder { public class ElasticsearchHibernatePropertiesBuilder {
private static final Logger ourLog = getLogger(ElasticsearchHibernatePropertiesBuilder.class); private static final Logger ourLog = getLogger(ElasticsearchHibernatePropertiesBuilder.class);
private IndexStatus myRequiredIndexStatus = IndexStatus.YELLOW.YELLOW; private IndexStatus myRequiredIndexStatus = IndexStatus.YELLOW;
private SchemaManagementStrategyName myIndexSchemaManagementStrategy = SchemaManagementStrategyName.CREATE; private SchemaManagementStrategyName myIndexSchemaManagementStrategy = SchemaManagementStrategyName.CREATE;
private String myRestUrl; private String myHosts;
private String myUsername; private String myUsername;
private String myPassword; private String myPassword;
private long myIndexManagementWaitTimeoutMillis = 10000L; private long myIndexManagementWaitTimeoutMillis = 10000L;
@ -77,11 +78,8 @@ public class ElasticsearchHibernatePropertiesBuilder {
// the below properties are used for ElasticSearch integration // the below properties are used for ElasticSearch integration
theProperties.put(BackendSettings.backendKey(BackendSettings.TYPE), "elasticsearch"); theProperties.put(BackendSettings.backendKey(BackendSettings.TYPE), "elasticsearch");
theProperties.put(BackendSettings.backendKey(ElasticsearchIndexSettings.ANALYSIS_CONFIGURER), HapiElasticsearchAnalysisConfigurer.class.getName()); theProperties.put(BackendSettings.backendKey(ElasticsearchIndexSettings.ANALYSIS_CONFIGURER), HapiElasticsearchAnalysisConfigurer.class.getName());
theProperties.put(BackendSettings.backendKey(ElasticsearchBackendSettings.HOSTS), myHosts);
theProperties.put(BackendSettings.backendKey(ElasticsearchBackendSettings.HOSTS), myRestUrl);
theProperties.put(BackendSettings.backendKey(ElasticsearchBackendSettings.PROTOCOL), myProtocol); theProperties.put(BackendSettings.backendKey(ElasticsearchBackendSettings.PROTOCOL), myProtocol);
if (StringUtils.isNotBlank(myUsername)) { if (StringUtils.isNotBlank(myUsername)) {
@ -102,8 +100,7 @@ public class ElasticsearchHibernatePropertiesBuilder {
//This tells elasticsearch to use our custom index naming strategy. //This tells elasticsearch to use our custom index naming strategy.
theProperties.put(BackendSettings.backendKey(ElasticsearchBackendSettings.LAYOUT_STRATEGY), IndexNamePrefixLayoutStrategy.class.getName()); theProperties.put(BackendSettings.backendKey(ElasticsearchBackendSettings.LAYOUT_STRATEGY), IndexNamePrefixLayoutStrategy.class.getName());
injectStartupTemplate(myProtocol, myRestUrl, myUsername, myPassword); injectStartupTemplate(myProtocol, myHosts, myUsername, myPassword);
} }
public ElasticsearchHibernatePropertiesBuilder setRequiredIndexStatus(IndexStatus theRequiredIndexStatus) { public ElasticsearchHibernatePropertiesBuilder setRequiredIndexStatus(IndexStatus theRequiredIndexStatus) {
@ -111,11 +108,8 @@ public class ElasticsearchHibernatePropertiesBuilder {
return this; return this;
} }
public ElasticsearchHibernatePropertiesBuilder setRestUrl(String theRestUrl) { public ElasticsearchHibernatePropertiesBuilder setHosts(String hosts) {
if (theRestUrl.contains("://")) { myHosts = hosts;
throw new ConfigurationException("Elasticsearch URL cannot include a protocol, that is a separate property. Remove http:// or https:// from this URL.");
}
myRestUrl = theRestUrl;
return this; return this;
} }
@ -150,18 +144,13 @@ public class ElasticsearchHibernatePropertiesBuilder {
* TODO GGG HS: In HS6.1, we should have a native way of performing index settings manipulation at bootstrap time, so this should * TODO GGG HS: In HS6.1, we should have a native way of performing index settings manipulation at bootstrap time, so this should
* eventually be removed in favour of whatever solution they come up with. * eventually be removed in favour of whatever solution they come up with.
*/ */
void injectStartupTemplate(String theProtocol, String theHostAndPort, String theUsername, String thePassword) { void injectStartupTemplate(String theProtocol, String theHosts, @Nullable String theUsername, @Nullable String thePassword) {
PutIndexTemplateRequest ngramTemplate = new PutIndexTemplateRequest("ngram-template") PutIndexTemplateRequest ngramTemplate = new PutIndexTemplateRequest("ngram-template")
.patterns(Arrays.asList("*resourcetable-*", "*termconcept-*")) .patterns(Arrays.asList("*resourcetable-*", "*termconcept-*"))
.settings(Settings.builder().put("index.max_ngram_diff", 50)); .settings(Settings.builder().put("index.max_ngram_diff", 50));
int colonIndex = theHostAndPort.indexOf(":");
String host = theHostAndPort.substring(0, colonIndex);
Integer port = Integer.valueOf(theHostAndPort.substring(colonIndex + 1));
String qualifiedHost = theProtocol + "://" + host;
try { try {
RestHighLevelClient elasticsearchHighLevelRestClient = ElasticsearchRestClientFactory.createElasticsearchHighLevelRestClient(qualifiedHost, port, theUsername, thePassword); RestHighLevelClient elasticsearchHighLevelRestClient = ElasticsearchRestClientFactory.createElasticsearchHighLevelRestClient(theProtocol, theHosts, theUsername, thePassword);
ourLog.info("Adding starter template for large ngram diffs"); ourLog.info("Adding starter template for large ngram diffs");
AcknowledgedResponse acknowledgedResponse = elasticsearchHighLevelRestClient.indices().putTemplate(ngramTemplate, RequestOptions.DEFAULT); AcknowledgedResponse acknowledgedResponse = elasticsearchHighLevelRestClient.indices().putTemplate(ngramTemplate, RequestOptions.DEFAULT);
assert acknowledgedResponse.isAcknowledged(); assert acknowledgedResponse.isAcknowledged();

View File

@ -20,6 +20,8 @@ package ca.uhn.fhir.jpa.search.lastn;
* #L% * #L%
*/ */
import ca.uhn.fhir.context.ConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
@ -27,45 +29,51 @@ import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider; import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.RestHighLevelClient;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ElasticsearchRestClientFactory { public class ElasticsearchRestClientFactory {
private static String determineScheme(String theHostname) { static public RestHighLevelClient createElasticsearchHighLevelRestClient(
int schemeIdx = theHostname.indexOf("://"); String protocol, String hosts, @Nullable String theUsername, @Nullable String thePassword) {
if (schemeIdx > 0) {
return theHostname.substring(0, schemeIdx); if (hosts.contains("://")) {
} else { throw new ConfigurationException("Elasticsearch URLs cannot include a protocol, that is a separate property. Remove http:// or https:// from this URL.");
return "http";
} }
} String[] hostArray = hosts.split(",");
List<Node> clientNodes = Arrays.stream(hostArray)
private static String stripHostOfScheme(String theHostname) { .map(String::trim)
int schemeIdx = theHostname.indexOf("://"); .filter(s -> s.contains(":"))
if (schemeIdx > 0) { .map(h -> {
return theHostname.substring(schemeIdx + 3); int colonIndex = h.indexOf(":");
} else { String host = h.substring(0, colonIndex);
return theHostname; int port = Integer.parseInt(h.substring(colonIndex + 1));
return new Node(new HttpHost(host, port, protocol));
})
.collect(Collectors.toList());
if (hostArray.length != clientNodes.size()) {
throw new ConfigurationException("Elasticsearch URLs have to contain ':' as a host:port separator. Example: localhost:9200,localhost:9201,localhost:9202");
} }
RestClientBuilder clientBuilder = RestClient.builder(clientNodes.toArray(new Node[0]));
if (StringUtils.isNotBlank(theUsername) && StringUtils.isNotBlank(thePassword)) {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(theUsername, thePassword));
clientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider));
}
Header[] defaultHeaders = new Header[]{new BasicHeader("Content-Type", "application/json")};
clientBuilder.setDefaultHeaders(defaultHeaders);
return new RestHighLevelClient(clientBuilder);
} }
static public RestHighLevelClient createElasticsearchHighLevelRestClient(String theHostname, int thePort, String theUsername, String thePassword) {
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(theUsername, thePassword));
RestClientBuilder clientBuilder = RestClient.builder(
new HttpHost(stripHostOfScheme(theHostname), thePort, determineScheme(theHostname)))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
.setDefaultCredentialsProvider(credentialsProvider));
Header[] defaultHeaders = new Header[]{new BasicHeader("Content-Type", "application/json")};
clientBuilder.setDefaultHeaders(defaultHeaders);
return new RestHighLevelClient(clientBuilder);
}
} }

View File

@ -68,11 +68,11 @@ import org.elasticsearch.search.aggregations.bucket.terms.ParsedTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.ParsedTopHits; import org.elasticsearch.search.aggregations.metrics.ParsedTopHits;
import org.elasticsearch.search.aggregations.support.ValueType;
import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Nullable;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -125,13 +125,13 @@ public class ElasticsearchSvcImpl implements IElasticsearchSvc {
private PartitionSettings myPartitionSettings; private PartitionSettings myPartitionSettings;
//This constructor used to inject a dummy partitionsettings in test. //This constructor used to inject a dummy partitionsettings in test.
public ElasticsearchSvcImpl(PartitionSettings thePartitionSetings, String theHostname, int thePort, String theUsername, String thePassword) { public ElasticsearchSvcImpl(PartitionSettings thePartitionSetings, String theHostname, @Nullable String theUsername, @Nullable String thePassword) {
this(theHostname, thePort, theUsername, thePassword); this(theHostname, theUsername, thePassword);
this.myPartitionSettings = thePartitionSetings; this.myPartitionSettings = thePartitionSetings;
} }
public ElasticsearchSvcImpl(String theHostname, int thePort, String theUsername, String thePassword) { public ElasticsearchSvcImpl(String theHostname, @Nullable String theUsername, @Nullable String thePassword) {
myRestHighLevelClient = ElasticsearchRestClientFactory.createElasticsearchHighLevelRestClient(theHostname, thePort, theUsername, thePassword); myRestHighLevelClient = ElasticsearchRestClientFactory.createElasticsearchHighLevelRestClient("http", theHostname, theUsername, thePassword);
try { try {
createObservationIndexIfMissing(); createObservationIndexIfMissing();

View File

@ -128,7 +128,7 @@ public class ElasticsearchWithPrefixConfig {
.settings(Settings.builder().put("index.max_ngram_diff", 50)); .settings(Settings.builder().put("index.max_ngram_diff", 50));
try { try {
RestHighLevelClient elasticsearchHighLevelRestClient = ElasticsearchRestClientFactory.createElasticsearchHighLevelRestClient("http://" + host, httpPort, "", ""); RestHighLevelClient elasticsearchHighLevelRestClient = ElasticsearchRestClientFactory.createElasticsearchHighLevelRestClient("http", host + ":" + httpPort, "", "");
AcknowledgedResponse acknowledgedResponse = elasticsearchHighLevelRestClient.indices().putTemplate(ngramTemplate, RequestOptions.DEFAULT); AcknowledgedResponse acknowledgedResponse = elasticsearchHighLevelRestClient.indices().putTemplate(ngramTemplate, RequestOptions.DEFAULT);
assert acknowledgedResponse.isAcknowledged(); assert acknowledgedResponse.isAcknowledged();
} catch (IOException theE) { } catch (IOException theE) {

View File

@ -41,7 +41,7 @@ public class TestR4ConfigWithElasticSearch extends TestR4Config {
.setIndexSchemaManagementStrategy(SchemaManagementStrategyName.CREATE) .setIndexSchemaManagementStrategy(SchemaManagementStrategyName.CREATE)
.setIndexManagementWaitTimeoutMillis(10000) .setIndexManagementWaitTimeoutMillis(10000)
.setRequiredIndexStatus(IndexStatus.YELLOW) .setRequiredIndexStatus(IndexStatus.YELLOW)
.setRestUrl(host+ ":" + httpPort) .setHosts(host + ":" + httpPort)
.setProtocol("http") .setProtocol("http")
.setUsername("") .setUsername("")
.setPassword("") .setPassword("")

View File

@ -21,7 +21,7 @@ public class TestR4ConfigWithElasticsearchClient extends TestR4ConfigWithElastic
public ElasticsearchSvcImpl myElasticsearchSvc() { public ElasticsearchSvcImpl myElasticsearchSvc() {
int elasticsearchPort = elasticContainer().getMappedPort(9200); int elasticsearchPort = elasticContainer().getMappedPort(9200);
String host = elasticContainer().getHost(); String host = elasticContainer().getHost();
return new ElasticsearchSvcImpl(host, elasticsearchPort, "", ""); return new ElasticsearchSvcImpl(host + ":" + elasticsearchPort, null, null);
} }
@PreDestroy @PreDestroy

View File

@ -33,7 +33,7 @@ public class ElasticsearchPrefixTest {
public void test() throws IOException { public void test() throws IOException {
//Given //Given
RestHighLevelClient elasticsearchHighLevelRestClient = ElasticsearchRestClientFactory.createElasticsearchHighLevelRestClient( RestHighLevelClient elasticsearchHighLevelRestClient = ElasticsearchRestClientFactory.createElasticsearchHighLevelRestClient(
"http://" + elasticsearchContainer.getHost(), elasticsearchContainer.getMappedPort(9200), "", ""); "http", elasticsearchContainer.getHost() + ":" + elasticsearchContainer.getMappedPort(9200), "", "");
//When //When
RestClient lowLevelClient = elasticsearchHighLevelRestClient.getLowLevelClient(); RestClient lowLevelClient = elasticsearchHighLevelRestClient.getLowLevelClient();

View File

@ -23,17 +23,11 @@ class ElasticsearchHibernatePropertiesBuilderTest {
ElasticsearchHibernatePropertiesBuilder myPropertiesBuilder = spy(ElasticsearchHibernatePropertiesBuilder.class); ElasticsearchHibernatePropertiesBuilder myPropertiesBuilder = spy(ElasticsearchHibernatePropertiesBuilder.class);
@BeforeEach
public void prepMocks() {
//ensures we don't try to reach out to a real ES server on apply.
doNothing().when(myPropertiesBuilder).injectStartupTemplate(any(), any(), any(), any());
}
@Test @Test
public void testRestUrlCannotContainProtocol() { public void testHostsCannotContainProtocol() {
String host = "localhost:9200"; String host = "localhost:9200";
String protocolHost = "https://" + host; String protocolHost = "https://" + host;
String failureMessage = "Elasticsearch URL cannot include a protocol, that is a separate property. Remove http:// or https:// from this URL."; String failureMessage = "Elasticsearch URLs cannot include a protocol, that is a separate property. Remove http:// or https:// from this URL.";
myPropertiesBuilder myPropertiesBuilder
.setProtocol("https") .setProtocol("https")
@ -42,19 +36,42 @@ class ElasticsearchHibernatePropertiesBuilderTest {
//SUT //SUT
try { try {
myPropertiesBuilder.setRestUrl(protocolHost); myPropertiesBuilder.setHosts(protocolHost)
.apply(new Properties());
fail(); fail();
} catch (ConfigurationException e ) { } catch (ConfigurationException e ) {
assertThat(e.getMessage(), is(equalTo(failureMessage))); assertThat(e.getMessage(), is(equalTo(failureMessage)));
} }
doNothing().when(myPropertiesBuilder).injectStartupTemplate(any(), any(), any(), any());
Properties properties = new Properties(); Properties properties = new Properties();
myPropertiesBuilder myPropertiesBuilder
.setRestUrl(host) .setHosts(host)
.apply(properties); .apply(properties);
assertThat(properties.getProperty(BackendSettings.backendKey(ElasticsearchBackendSettings.HOSTS)), is(equalTo(host))); assertThat(properties.getProperty(BackendSettings.backendKey(ElasticsearchBackendSettings.HOSTS)), is(equalTo(host)));
} }
@Test
public void testHostsValueValidation() {
String host = "localhost_9200,localhost:9201,localhost:9202";
String failureMessage = "Elasticsearch URLs have to contain ':' as a host:port separator. Example: localhost:9200,localhost:9201,localhost:9202";
myPropertiesBuilder
.setProtocol("https")
.setHosts(host)
.setUsername("whatever")
.setPassword("whatever");
//SUT
try {
myPropertiesBuilder
.apply(new Properties());
fail();
} catch (ConfigurationException e ) {
assertThat(e.getMessage(), is(equalTo(failureMessage)));
}
}
} }

View File

@ -68,7 +68,7 @@ public class LastNElasticsearchSvcMultipleObservationsIT {
public void before() throws IOException { public void before() throws IOException {
PartitionSettings partitionSettings = new PartitionSettings(); PartitionSettings partitionSettings = new PartitionSettings();
partitionSettings.setPartitioningEnabled(false); partitionSettings.setPartitioningEnabled(false);
elasticsearchSvc = new ElasticsearchSvcImpl(partitionSettings, elasticsearchContainer.getHost(), elasticsearchContainer.getMappedPort(9200), "", ""); elasticsearchSvc = new ElasticsearchSvcImpl(partitionSettings, elasticsearchContainer.getHost() + ":" + elasticsearchContainer.getMappedPort(9200), null, null);
if (!indexLoaded) { if (!indexLoaded) {
createMultiplePatientsAndObservations(); createMultiplePatientsAndObservations();

View File

@ -97,7 +97,7 @@ public class LastNElasticsearchSvcSingleObservationIT {
public void before() { public void before() {
PartitionSettings partitionSettings = new PartitionSettings(); PartitionSettings partitionSettings = new PartitionSettings();
partitionSettings.setPartitioningEnabled(false); partitionSettings.setPartitioningEnabled(false);
elasticsearchSvc = new ElasticsearchSvcImpl(partitionSettings, elasticsearchContainer.getHost(), elasticsearchContainer.getMappedPort(9200), "", ""); elasticsearchSvc = new ElasticsearchSvcImpl(partitionSettings, elasticsearchContainer.getHost() + ":" + elasticsearchContainer.getMappedPort(9200), "", "");
} }
@AfterEach @AfterEach