This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-27479-es-api-key in repository https://gitbox.apache.org/repos/asf/camel.git
commit 6150fd5b43c79956a052c567d20029fbab7f7954 Author: Claus Ibsen <[email protected]> AuthorDate: Mon Nov 23 20:49:55 2026 +0100 CAMEL-27479: camel-elasticsearch - add an apiKey option to log in with an Elasticsearch API key The new apiKey component option (security, secret) sends Authorization: ApiKey on the requests to the cluster nodes. It takes the encoded key as Elasticsearch shows it, or id:key, which Camel encodes. The header is added by a request interceptor that matches the target host against the nodes, like the basic authentication credentials since CAMEL-25706. A default header of the RestClient would be copied by HttpClient onto a redirect to any host. Setting both apiKey and user fails when the endpoint is created. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../camel/catalog/components/elasticsearch.json | 13 +- .../catalog/docs/elasticsearch-component.adoc | 18 +++ .../es/ElasticsearchComponentConfigurer.java | 6 + .../apache/camel/component/es/elasticsearch.json | 13 +- .../src/main/docs/elasticsearch-component.adoc | 18 +++ .../camel/component/es/ElasticsearchComponent.java | 21 +++ .../component/es/ElasticsearchConfiguration.java | 12 ++ .../camel/component/es/ElasticsearchProducer.java | 6 +- .../component/es/NodeScopedApiKeyInterceptor.java | 67 +++++++++ .../es/NodeScopedCredentialsProvider.java | 23 ++- .../es/ElasticsearchProducerApiKeyTest.java | 159 +++++++++++++++++++++ .../es/integration/ElasticsearchApiKeyIT.java | 110 ++++++++++++++ .../dsl/ElasticsearchComponentBuilderFactory.java | 20 +++ 13 files changed, 467 insertions(+), 19 deletions(-) diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/elasticsearch.json b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/elasticsearch.json index b5161a1c6f7a..190077f7dd74 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/elasticsearch.json +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/elasticsearch.json @@ -35,12 +35,13 @@ "enableSniffer": { "index": 8, "kind": "property", "displayName": "Enable Sniffer", "group": "advanced", "label": "advanced", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Enable automatically discover nodes from a running Elasticsearch cluster. If this option is used in conjunction with Spring Boot, then it's managed by the Spring Boot configuration (see: Disable Sniffer i [...] "sniffAfterFailureDelay": { "index": 9, "kind": "property", "displayName": "Sniff After Failure Delay", "group": "advanced", "label": "advanced", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 60000, "description": "The delay of a sniff execution scheduled after a failure (in milliseconds)" }, "snifferInterval": { "index": 10, "kind": "property", "displayName": "Sniffer Interval", "group": "advanced", "label": "advanced", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 300000, "description": "The interval between consecutive ordinary sniff executions in milliseconds. Will be honoured when sniffOnFailure is disabled or when there are no failures between consecutive sniff executions" }, - "certificatePath": { "index": 11, "kind": "property", "displayName": "Certificate Path", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "description": "The path of the self-signed certificate to use to access to Elasticsearch." }, - "enableSSL": { "index": 12, "kind": "property", "displayName": "Enable SSL", "group": "security", "label": "security", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Enable SSL" }, - "password": { "index": 13, "kind": "property", "displayName": "Password", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "description": "Password for authenticating" }, - "sslContextParameters": { "index": 14, "kind": "property", "displayName": "Ssl Context Parameters", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "org.apache.camel.support.jsse.SSLContextParameters", "deprecated": false, "autowired": false, "secret": false, "description": "To configure security using SSLContextParameters. When configured, this takes precedence over the certificatePath option." }, - "useGlobalSslContextParameters": { "index": 15, "kind": "property", "displayName": "Use Global Ssl Context Parameters", "group": "security", "label": "security", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Enable usage of global SSL context parameters." }, - "user": { "index": 16, "kind": "property", "displayName": "User", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "description": "Basic authenticate user" } + "apiKey": { "index": 11, "kind": "property", "displayName": "Api Key", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "description": "API key to authenticate with, sent in the Authorization header instead of a user and password. Either the encoded key as Elasticsearch shows it when the key is created, or the id and the key separated by a colon [...] + "certificatePath": { "index": 12, "kind": "property", "displayName": "Certificate Path", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "description": "The path of the self-signed certificate to use to access to Elasticsearch." }, + "enableSSL": { "index": 13, "kind": "property", "displayName": "Enable SSL", "group": "security", "label": "security", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Enable SSL" }, + "password": { "index": 14, "kind": "property", "displayName": "Password", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "description": "Password for authenticating" }, + "sslContextParameters": { "index": 15, "kind": "property", "displayName": "Ssl Context Parameters", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "org.apache.camel.support.jsse.SSLContextParameters", "deprecated": false, "autowired": false, "secret": false, "description": "To configure security using SSLContextParameters. When configured, this takes precedence over the certificatePath option." }, + "useGlobalSslContextParameters": { "index": 16, "kind": "property", "displayName": "Use Global Ssl Context Parameters", "group": "security", "label": "security", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Enable usage of global SSL context parameters." }, + "user": { "index": 17, "kind": "property", "displayName": "User", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "description": "Basic authenticate user" } }, "headers": { "CamelElasticsearchOperation": { "index": 0, "kind": "header", "displayName": "", "group": "producer", "label": "", "required": false, "javaType": "org.apache.camel.component.es.ElasticsearchOperation", "enum": [ "Index", "Update", "Bulk", "GetById", "MultiGet", "MultiSearch", "Delete", "DeleteIndex", "Search", "Exists", "Ping" ], "deprecated": false, "autowired": false, "secret": false, "description": "The operation to perform", "constantName": "org.apache.camel.component.es.Elastic [...] diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/elasticsearch-component.adoc b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/elasticsearch-component.adoc index ec04531a9a8c..24e4198b8f07 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/elasticsearch-component.adoc +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/elasticsearch-component.adoc @@ -134,6 +134,24 @@ elasticsearchComponent.setCertificatePath(certPath); camelContext.addComponent("elasticsearch", elasticsearchComponent); ---- +=== Authenticate with an API key + +Instead of a user and password, the component can log in with an Elasticsearch API key, which is what Elastic +recommends, also on Elastic Cloud. Set the `apiKey` option to the encoded key as Elasticsearch shows it when the key +is created (the `encoded` field of the response), or to the id and the key separated by a colon (`id:key`). Camel sends +it as the `Authorization: ApiKey ...` header. + +[source,properties] +---- +camel.component.elasticsearch.host-addresses=myelkhost:9200 +camel.component.elasticsearch.enable-ssl=true +camel.component.elasticsearch.api-key={{elasticsearch.api-key}} +---- + +The key is only sent to the hosts of `hostAddresses` and to the nodes the sniffer finds, never to another host, such as +the target of a redirect. Setting both `apiKey` and `user` fails when the endpoint is created. When the component uses a +client set with the `client` option, the `apiKey` option is not used, as for `user` and `password`. + === Document type For all the search operations, it is possible to indicate the type of document to retrieve to get the result already unmarshalled with the expected type. diff --git a/components/camel-elasticsearch/src/generated/java/org/apache/camel/component/es/ElasticsearchComponentConfigurer.java b/components/camel-elasticsearch/src/generated/java/org/apache/camel/component/es/ElasticsearchComponentConfigurer.java index db8b80ba3965..e1ab7ffdb9ec 100644 --- a/components/camel-elasticsearch/src/generated/java/org/apache/camel/component/es/ElasticsearchComponentConfigurer.java +++ b/components/camel-elasticsearch/src/generated/java/org/apache/camel/component/es/ElasticsearchComponentConfigurer.java @@ -24,6 +24,8 @@ public class ElasticsearchComponentConfigurer extends PropertyConfigurerSupport public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { ElasticsearchComponent target = (ElasticsearchComponent) obj; switch (ignoreCase ? name.toLowerCase(Locale.ROOT) : name) { + case "apikey": + case "apiKey": target.setApiKey(property(camelContext, java.lang.String.class, value)); return true; case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "certificatepath": @@ -67,6 +69,8 @@ public class ElasticsearchComponentConfigurer extends PropertyConfigurerSupport @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase(Locale.ROOT) : name) { + case "apikey": + case "apiKey": return java.lang.String.class; case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "certificatepath": @@ -106,6 +110,8 @@ public class ElasticsearchComponentConfigurer extends PropertyConfigurerSupport public Object getOptionValue(Object obj, String name, boolean ignoreCase) { ElasticsearchComponent target = (ElasticsearchComponent) obj; switch (ignoreCase ? name.toLowerCase(Locale.ROOT) : name) { + case "apikey": + case "apiKey": return target.getApiKey(); case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "certificatepath": diff --git a/components/camel-elasticsearch/src/generated/resources/META-INF/org/apache/camel/component/es/elasticsearch.json b/components/camel-elasticsearch/src/generated/resources/META-INF/org/apache/camel/component/es/elasticsearch.json index b5161a1c6f7a..190077f7dd74 100644 --- a/components/camel-elasticsearch/src/generated/resources/META-INF/org/apache/camel/component/es/elasticsearch.json +++ b/components/camel-elasticsearch/src/generated/resources/META-INF/org/apache/camel/component/es/elasticsearch.json @@ -35,12 +35,13 @@ "enableSniffer": { "index": 8, "kind": "property", "displayName": "Enable Sniffer", "group": "advanced", "label": "advanced", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Enable automatically discover nodes from a running Elasticsearch cluster. If this option is used in conjunction with Spring Boot, then it's managed by the Spring Boot configuration (see: Disable Sniffer i [...] "sniffAfterFailureDelay": { "index": 9, "kind": "property", "displayName": "Sniff After Failure Delay", "group": "advanced", "label": "advanced", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 60000, "description": "The delay of a sniff execution scheduled after a failure (in milliseconds)" }, "snifferInterval": { "index": 10, "kind": "property", "displayName": "Sniffer Interval", "group": "advanced", "label": "advanced", "required": false, "type": "integer", "javaType": "int", "deprecated": false, "autowired": false, "secret": false, "defaultValue": 300000, "description": "The interval between consecutive ordinary sniff executions in milliseconds. Will be honoured when sniffOnFailure is disabled or when there are no failures between consecutive sniff executions" }, - "certificatePath": { "index": 11, "kind": "property", "displayName": "Certificate Path", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "description": "The path of the self-signed certificate to use to access to Elasticsearch." }, - "enableSSL": { "index": 12, "kind": "property", "displayName": "Enable SSL", "group": "security", "label": "security", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Enable SSL" }, - "password": { "index": 13, "kind": "property", "displayName": "Password", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "description": "Password for authenticating" }, - "sslContextParameters": { "index": 14, "kind": "property", "displayName": "Ssl Context Parameters", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "org.apache.camel.support.jsse.SSLContextParameters", "deprecated": false, "autowired": false, "secret": false, "description": "To configure security using SSLContextParameters. When configured, this takes precedence over the certificatePath option." }, - "useGlobalSslContextParameters": { "index": 15, "kind": "property", "displayName": "Use Global Ssl Context Parameters", "group": "security", "label": "security", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Enable usage of global SSL context parameters." }, - "user": { "index": 16, "kind": "property", "displayName": "User", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "description": "Basic authenticate user" } + "apiKey": { "index": 11, "kind": "property", "displayName": "Api Key", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "description": "API key to authenticate with, sent in the Authorization header instead of a user and password. Either the encoded key as Elasticsearch shows it when the key is created, or the id and the key separated by a colon [...] + "certificatePath": { "index": 12, "kind": "property", "displayName": "Certificate Path", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": false, "description": "The path of the self-signed certificate to use to access to Elasticsearch." }, + "enableSSL": { "index": 13, "kind": "property", "displayName": "Enable SSL", "group": "security", "label": "security", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Enable SSL" }, + "password": { "index": 14, "kind": "property", "displayName": "Password", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "description": "Password for authenticating" }, + "sslContextParameters": { "index": 15, "kind": "property", "displayName": "Ssl Context Parameters", "group": "security", "label": "security", "required": false, "type": "object", "javaType": "org.apache.camel.support.jsse.SSLContextParameters", "deprecated": false, "autowired": false, "secret": false, "description": "To configure security using SSLContextParameters. When configured, this takes precedence over the certificatePath option." }, + "useGlobalSslContextParameters": { "index": 16, "kind": "property", "displayName": "Use Global Ssl Context Parameters", "group": "security", "label": "security", "required": false, "type": "boolean", "javaType": "boolean", "deprecated": false, "autowired": false, "secret": false, "defaultValue": false, "description": "Enable usage of global SSL context parameters." }, + "user": { "index": 17, "kind": "property", "displayName": "User", "group": "security", "label": "security", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "autowired": false, "secret": true, "security": "secret", "description": "Basic authenticate user" } }, "headers": { "CamelElasticsearchOperation": { "index": 0, "kind": "header", "displayName": "", "group": "producer", "label": "", "required": false, "javaType": "org.apache.camel.component.es.ElasticsearchOperation", "enum": [ "Index", "Update", "Bulk", "GetById", "MultiGet", "MultiSearch", "Delete", "DeleteIndex", "Search", "Exists", "Ping" ], "deprecated": false, "autowired": false, "secret": false, "description": "The operation to perform", "constantName": "org.apache.camel.component.es.Elastic [...] diff --git a/components/camel-elasticsearch/src/main/docs/elasticsearch-component.adoc b/components/camel-elasticsearch/src/main/docs/elasticsearch-component.adoc index ec04531a9a8c..24e4198b8f07 100644 --- a/components/camel-elasticsearch/src/main/docs/elasticsearch-component.adoc +++ b/components/camel-elasticsearch/src/main/docs/elasticsearch-component.adoc @@ -134,6 +134,24 @@ elasticsearchComponent.setCertificatePath(certPath); camelContext.addComponent("elasticsearch", elasticsearchComponent); ---- +=== Authenticate with an API key + +Instead of a user and password, the component can log in with an Elasticsearch API key, which is what Elastic +recommends, also on Elastic Cloud. Set the `apiKey` option to the encoded key as Elasticsearch shows it when the key +is created (the `encoded` field of the response), or to the id and the key separated by a colon (`id:key`). Camel sends +it as the `Authorization: ApiKey ...` header. + +[source,properties] +---- +camel.component.elasticsearch.host-addresses=myelkhost:9200 +camel.component.elasticsearch.enable-ssl=true +camel.component.elasticsearch.api-key={{elasticsearch.api-key}} +---- + +The key is only sent to the hosts of `hostAddresses` and to the nodes the sniffer finds, never to another host, such as +the target of a redirect. Setting both `apiKey` and `user` fails when the endpoint is created. When the component uses a +client set with the `client` option, the `apiKey` option is not used, as for `user` and `password`. + === Document type For all the search operations, it is possible to indicate the type of document to retrieve to get the result already unmarshalled with the expected type. diff --git a/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/ElasticsearchComponent.java b/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/ElasticsearchComponent.java index cc515070799e..bd5bfbf3d5e7 100644 --- a/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/ElasticsearchComponent.java +++ b/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/ElasticsearchComponent.java @@ -53,6 +53,8 @@ public class ElasticsearchComponent extends DefaultComponent implements SSLConte private String user; @Metadata(label = "security", security = "secret") private String password; + @Metadata(label = "security", security = "secret") + private String apiKey; @Metadata(label = "security") private boolean enableSSL; @Metadata(label = "security") @@ -87,6 +89,7 @@ public class ElasticsearchComponent extends DefaultComponent implements SSLConte config.setUser(this.getUser()); config.setEnableSSL(this.isEnableSSL()); config.setPassword(this.getPassword()); + config.setApiKey(this.getApiKey()); config.setCertificatePath(this.getCertificatePath()); config.setSslContextParameters(this.getSslContextParameters()); config.setEnableSniffer(this.isEnableSniffer()); @@ -95,6 +98,11 @@ public class ElasticsearchComponent extends DefaultComponent implements SSLConte config.setClusterName(remaining); config.setEnableDocumentOnlyMode(this.isEnableDocumentOnlyMode()); + if (config.getApiKey() != null && config.getUser() != null) { + throw new IllegalArgumentException( + "Both apiKey and user are configured on the elasticsearch component: use either apiKey, or user and password"); + } + Endpoint endpoint = new ElasticsearchEndpoint(uri, this, config, client); setProperties(endpoint, parameters); if (config.getSslContextParameters() == null) { @@ -193,6 +201,19 @@ public class ElasticsearchComponent extends DefaultComponent implements SSLConte this.password = password; } + /** + * API key to authenticate with, sent in the Authorization header instead of a user and password. Either the encoded + * key as Elasticsearch shows it when the key is created, or the id and the key separated by a colon (id:key). The + * key is only sent to the configured hosts and the nodes found by the sniffer. + */ + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + public boolean isEnableSSL() { return enableSSL; } diff --git a/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/ElasticsearchConfiguration.java b/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/ElasticsearchConfiguration.java index 1d28482c670e..fb9017931b41 100644 --- a/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/ElasticsearchConfiguration.java +++ b/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/ElasticsearchConfiguration.java @@ -32,6 +32,7 @@ public class ElasticsearchConfiguration { private List<HttpHost> hostAddressesList; private String user; private String password; + private String apiKey; @UriPath @Metadata(required = true) @@ -210,6 +211,17 @@ public class ElasticsearchConfiguration { this.password = password; } + /** + * API key to authenticate with, instead of a user and password + */ + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + /** * Enable SSL */ diff --git a/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/ElasticsearchProducer.java b/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/ElasticsearchProducer.java index 58dc6f4862a7..e42895622a61 100644 --- a/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/ElasticsearchProducer.java +++ b/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/ElasticsearchProducer.java @@ -519,7 +519,7 @@ class ElasticsearchProducer extends DefaultAsyncProducer { } } - private RestClient createClient() { + RestClient createClient() { final RestClientBuilder builder = RestClient.builder(configuration.getHostAddressesList().toArray(new HttpHost[0])); // the credentials provider reads the nodes from the client, as the sniffer can change them final AtomicReference<RestClient> restClientRef = new AtomicReference<>(); @@ -531,6 +531,10 @@ class ElasticsearchProducer extends DefaultAsyncProducer { if (credentialsProvider != null) { httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } + if (configuration.getApiKey() != null) { + httpClientBuilder.addInterceptorLast( + new NodeScopedApiKeyInterceptor(configuration.getApiKey(), () -> nodeHosts(restClientRef.get()))); + } if (configuration.getSslContextParameters() != null) { // Use SSLContextParameters (allows configuring named groups, signature schemes, cipher suites and // protocols), e.g. for post-quantum readiness on JDK 25+ diff --git a/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/NodeScopedApiKeyInterceptor.java b/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/NodeScopedApiKeyInterceptor.java new file mode 100644 index 000000000000..4fa54a449664 --- /dev/null +++ b/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/NodeScopedApiKeyInterceptor.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.es; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Collection; +import java.util.function.Supplier; + +import org.apache.http.HttpHeaders; +import org.apache.http.HttpHost; +import org.apache.http.HttpRequest; +import org.apache.http.HttpRequestInterceptor; +import org.apache.http.protocol.HttpContext; +import org.apache.http.protocol.HttpCoreContext; + +/** + * Adds the API key in the Authorization header of the requests to the nodes of the cluster the client talks to: the + * configured hosts, and the nodes found by the sniffer when it is enabled. A request to any other host, such as the + * target of a redirect, does not get the key. + * <p> + * The key is not set as a default header of the client, because HttpClient copies the headers of the original request + * onto a redirect, whatever its host. An interceptor runs for each request, with the host it is sent to. + */ +final class NodeScopedApiKeyInterceptor implements HttpRequestInterceptor { + + private final String authorization; + private final Supplier<? extends Collection<HttpHost>> nodes; + + NodeScopedApiKeyInterceptor(String apiKey, Supplier<? extends Collection<HttpHost>> nodes) { + this.authorization = "ApiKey " + encode(apiKey); + this.nodes = nodes; + } + + @Override + public void process(HttpRequest request, HttpContext context) { + HttpHost target = HttpCoreContext.adapt(context).getTargetHost(); + if (NodeScopedCredentialsProvider.isNode(nodes.get(), target)) { + request.setHeader(HttpHeaders.AUTHORIZATION, authorization); + } + } + + /** + * The key as Elasticsearch shows it when it is created is already encoded: base64 never contains a colon. A key + * given as id:key is encoded here. + */ + static String encode(String apiKey) { + if (apiKey.indexOf(':') >= 0) { + return Base64.getEncoder().encodeToString(apiKey.getBytes(StandardCharsets.UTF_8)); + } + return apiKey; + } +} diff --git a/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/NodeScopedCredentialsProvider.java b/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/NodeScopedCredentialsProvider.java index d4a2fac52a04..42ea6780f41a 100644 --- a/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/NodeScopedCredentialsProvider.java +++ b/components/camel-elasticsearch/src/main/java/org/apache/camel/component/es/NodeScopedCredentialsProvider.java @@ -42,16 +42,27 @@ final class NodeScopedCredentialsProvider implements CredentialsProvider { @Override public Credentials getCredentials(AuthScope authScope) { HttpHost origin = authScope != null ? authScope.getOrigin() : null; - if (origin != null) { - for (HttpHost node : nodes.get()) { - if (sameAuthority(node, origin)) { - return credentials; - } - } + if (isNode(nodes.get(), origin)) { + return credentials; } return null; } + /** + * Whether the host is one of the nodes: the same scheme, host name (in any case) and port. + */ + static boolean isNode(Collection<HttpHost> nodes, HttpHost host) { + if (host == null || nodes == null) { + return false; + } + for (HttpHost node : nodes) { + if (sameAuthority(node, host)) { + return true; + } + } + return false; + } + /** * Ignored: the credentials come from the endpoint configuration only. HttpClient calls this for the user info of a * request URI. diff --git a/components/camel-elasticsearch/src/test/java/org/apache/camel/component/es/ElasticsearchProducerApiKeyTest.java b/components/camel-elasticsearch/src/test/java/org/apache/camel/component/es/ElasticsearchProducerApiKeyTest.java new file mode 100644 index 000000000000..6adaba7f9d4f --- /dev/null +++ b/components/camel-elasticsearch/src/test/java/org/apache/camel/component/es/ElasticsearchProducerApiKeyTest.java @@ -0,0 +1,159 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.es; + +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import com.sun.net.httpserver.HttpServer; +import org.apache.camel.CamelContext; +import org.apache.camel.ResolveEndpointFailedException; +import org.apache.camel.impl.DefaultCamelContext; +import org.elasticsearch.client.Request; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.RestClient; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class ElasticsearchProducerApiKeyTest { + + private static final String NO_HEADER = "<none>"; + + private final Map<String, String> authorizations = new ConcurrentHashMap<>(); + private HttpServer node; + private HttpServer other; + + @BeforeEach + void startServers() throws Exception { + other = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + other.createContext("/", exchange -> { + record("other", exchange.getRequestHeaders().getFirst("Authorization")); + byte[] body = "{}".getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, body.length); + exchange.getResponseBody().write(body); + exchange.close(); + }); + other.start(); + + node = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + node.createContext("/", exchange -> { + record("node", exchange.getRequestHeaders().getFirst("Authorization")); + exchange.getResponseHeaders().add("Location", "http://127.0.0.1:" + other.getAddress().getPort() + "/"); + exchange.sendResponseHeaders(302, -1); + exchange.close(); + }); + node.start(); + } + + @AfterEach + void stopServers() { + if (node != null) { + node.stop(0); + } + if (other != null) { + other.stop(0); + } + } + + @Test + void sendsTheApiKeyToTheNodesOnlyAndNotToARedirectTarget() throws Exception { + try (CamelContext context = new DefaultCamelContext()) { + context.start(); + ElasticsearchComponent component = component(context); + component.setApiKey("VnVhQ2ZHY0JDZGJrUW0tZTVhT3g6dWkybHAyYXhUTm1zeWFrdzl0dk5udw=="); + + Response response = send(context); + + assertEquals(200, response.getStatusLine().getStatusCode()); + assertEquals("ApiKey VnVhQ2ZHY0JDZGJrUW0tZTVhT3g6dWkybHAyYXhUTm1zeWFrdzl0dk5udw==", authorizations.get("node")); + assertEquals(NO_HEADER, authorizations.get("other")); + } + } + + @Test + void encodesAnApiKeyGivenAsIdAndKey() throws Exception { + try (CamelContext context = new DefaultCamelContext()) { + context.start(); + ElasticsearchComponent component = component(context); + component.setApiKey("my-id:my-key"); + + send(context); + + String encoded = Base64.getEncoder().encodeToString("my-id:my-key".getBytes(StandardCharsets.UTF_8)); + assertEquals("ApiKey " + encoded, authorizations.get("node")); + assertEquals(NO_HEADER, authorizations.get("other")); + } + } + + @Test + void sendsNoAuthorizationWithoutAnApiKey() throws Exception { + try (CamelContext context = new DefaultCamelContext()) { + context.start(); + component(context); + + send(context); + + assertEquals(NO_HEADER, authorizations.get("node")); + assertEquals(NO_HEADER, authorizations.get("other")); + } + } + + @Test + void failsWhenBothApiKeyAndUserAreSet() throws Exception { + try (CamelContext context = new DefaultCamelContext()) { + context.start(); + ElasticsearchComponent component = component(context); + component.setApiKey("my-id:my-key"); + component.setUser("elastic"); + component.setPassword("secret"); + + ResolveEndpointFailedException e = assertThrows(ResolveEndpointFailedException.class, + () -> context.getEndpoint("elasticsearch:test-cluster")); + IllegalArgumentException cause = assertInstanceOf(IllegalArgumentException.class, e.getCause()); + assertEquals("Both apiKey and user are configured on the elasticsearch component: use either apiKey, or user and" + + " password", + cause.getMessage()); + } + } + + private void record(String server, String authorization) { + authorizations.put(server, authorization != null ? authorization : NO_HEADER); + } + + private ElasticsearchComponent component(CamelContext context) { + ElasticsearchComponent component = new ElasticsearchComponent(context); + component.setHostAddresses("127.0.0.1:" + node.getAddress().getPort()); + context.addComponent("elasticsearch", component); + return component; + } + + private static Response send(CamelContext context) throws Exception { + ElasticsearchEndpoint endpoint = context.getEndpoint("elasticsearch:test-cluster", ElasticsearchEndpoint.class); + try (RestClient client = new ElasticsearchProducer(endpoint, endpoint.getConfiguration()).createClient()) { + return client.performRequest(new Request("GET", "/")); + } + } +} diff --git a/components/camel-elasticsearch/src/test/java/org/apache/camel/component/es/integration/ElasticsearchApiKeyIT.java b/components/camel-elasticsearch/src/test/java/org/apache/camel/component/es/integration/ElasticsearchApiKeyIT.java new file mode 100644 index 000000000000..18f5e299f8ee --- /dev/null +++ b/components/camel-elasticsearch/src/test/java/org/apache/camel/component/es/integration/ElasticsearchApiKeyIT.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.es.integration; + +import java.util.Map; + +import co.elastic.clients.elasticsearch.security.CreateApiKeyResponse; +import org.apache.camel.CamelContext; +import org.apache.camel.CamelExecutionException; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.es.ElasticsearchComponent; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Logs in with an API key only: the components have no user and password. + */ +class ElasticsearchApiKeyIT extends ElasticsearchTestSupport { + + private static CreateApiKeyResponse apiKey; + + @Override + protected void setupResources() throws Exception { + super.setupResources(); + if (apiKey == null) { + // created with the user and password of the test container + apiKey = client.security().createApiKey(b -> b.name("camel-elasticsearch-api-key-it")); + } + } + + @Override + protected CamelContext createCamelContext() throws Exception { + CamelContext context = super.createCamelContext(); + configure(context.getComponent("elasticsearch", ElasticsearchComponent.class), apiKey.encoded()); + + ElasticsearchComponent idAndKey = new ElasticsearchComponent(); + configure(idAndKey, apiKey.id() + ":" + apiKey.apiKey()); + context.addComponent("elasticsearch-id-key", idAndKey); + + ElasticsearchComponent wrongKey = new ElasticsearchComponent(); + configure(wrongKey, apiKey.id() + ":wrong"); + context.addComponent("elasticsearch-wrong-key", wrongKey); + return context; + } + + private static void configure(ElasticsearchComponent component, String key) { + component.setEnableSSL(service.getSslContext().isPresent()); + component.setHostAddresses(service.getHttpHostAddress()); + service.getCertificatePath() + .ifPresent(certificatePath -> component.setCertificatePath("file:%s".formatted(certificatePath))); + component.setUser(null); + component.setPassword(null); + component.setApiKey(key); + } + + @Test + void indexAndGetWithTheEncodedApiKey() { + Map<String, String> map = createIndexedData(); + String indexId = template.requestBody("direct:index", map, String.class); + assertNotNull(indexId, "indexId should be set"); + + Object document = template.requestBody("direct:get", indexId); + assertNotNull(document, "the document should be found"); + } + + @Test + void pingWithTheIdAndKey() { + assertEquals(Boolean.TRUE, template.requestBody("direct:ping-id-key", "test", Boolean.class)); + } + + @Test + void failsWithAWrongApiKey() { + Map<String, String> map = createIndexedData(); + assertThrows(CamelExecutionException.class, () -> template.requestBody("direct:index-wrong-key", map)); + } + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from("direct:index") + .to("elasticsearch://elasticsearch?operation=Index&indexName=api-key"); + from("direct:get") + .to("elasticsearch://elasticsearch?operation=GetById&indexName=api-key"); + from("direct:ping-id-key") + .to("elasticsearch-id-key://elasticsearch?operation=Ping"); + from("direct:index-wrong-key") + .to("elasticsearch-wrong-key://elasticsearch?operation=Index&indexName=api-key"); + } + }; + } +} diff --git a/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/ElasticsearchComponentBuilderFactory.java b/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/ElasticsearchComponentBuilderFactory.java index 798aa9e8c354..aaccd87bb2f4 100644 --- a/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/ElasticsearchComponentBuilderFactory.java +++ b/dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/ElasticsearchComponentBuilderFactory.java @@ -261,6 +261,25 @@ public interface ElasticsearchComponentBuilderFactory { return this; } + /** + * API key to authenticate with, sent in the Authorization header + * instead of a user and password. Either the encoded key as + * Elasticsearch shows it when the key is created, or the id and the key + * separated by a colon (id:key). The key is only sent to the configured + * hosts and the nodes found by the sniffer. + * + * The option is a: <code>java.lang.String</code> type. + * + * Group: security + * + * @param apiKey the value to set + * @return the dsl builder + */ + default ElasticsearchComponentBuilder apiKey(java.lang.String apiKey) { + doSetProperty("apiKey", apiKey); + return this; + } + /** * The path of the self-signed certificate to use to access to * Elasticsearch. @@ -383,6 +402,7 @@ public interface ElasticsearchComponentBuilderFactory { case "enableSniffer": ((ElasticsearchComponent) component).setEnableSniffer((boolean) value); return true; case "sniffAfterFailureDelay": ((ElasticsearchComponent) component).setSniffAfterFailureDelay((int) value); return true; case "snifferInterval": ((ElasticsearchComponent) component).setSnifferInterval((int) value); return true; + case "apiKey": ((ElasticsearchComponent) component).setApiKey((java.lang.String) value); return true; case "certificatePath": ((ElasticsearchComponent) component).setCertificatePath((java.lang.String) value); return true; case "enableSSL": ((ElasticsearchComponent) component).setEnableSSL((boolean) value); return true; case "password": ((ElasticsearchComponent) component).setPassword((java.lang.String) value); return true;
