This is an automated email from the ASF dual-hosted git repository.

cdeppisch pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new d14e45e10d1 CAMEL-21383: Add Knative client OIDC support
d14e45e10d1 is described below

commit d14e45e10d125324a7174fc0d80bd4398a1c1c50
Author: Christoph Deppisch <[email protected]>
AuthorDate: Fri Oct 25 22:19:41 2024 +0200

    CAMEL-21383: Add Knative client OIDC support
    
    - Adds OpenID Connect support to Knative Http client
    - Autoconfigure options via system property or environment variables
    - Sets proper Authorization headers with access token on each request
    - Renew OIDC tokens on forbidden response
    - Disable token cache
---
 .../src/main/docs/knative-http-component.adoc      |  85 +++++-
 .../knative/http/KnativeHttpProducer.java          |   5 +
 .../component/knative/http/KnativeHttpSupport.java |   6 +-
 .../knative/http/KnativeOidcClientOptions.java     | 146 ++++++++++
 .../knative/http/KnativeOidcInterceptor.java       |  87 ++++++
 ...ntOptions.java => KnativeSslClientOptions.java} |   6 +-
 .../component/knative/http/KnativeHttpServer.java  |  13 +-
 .../component/knative/http/KnativeHttpTest.java    | 321 ++++++++++++++++++++-
 .../src/test/resources/oidc/renewed_token.txt      |   1 +
 .../src/test/resources/oidc/token.txt              |   1 +
 10 files changed, 652 insertions(+), 19 deletions(-)

diff --git 
a/components/camel-knative/camel-knative-http/src/main/docs/knative-http-component.adoc
 
b/components/camel-knative/camel-knative-http/src/main/docs/knative-http-component.adoc
index b129096ada3..b424b276467 100644
--- 
a/components/camel-knative/camel-knative-http/src/main/docs/knative-http-component.adoc
+++ 
b/components/camel-knative/camel-knative-http/src/main/docs/knative-http-component.adoc
@@ -83,10 +83,10 @@ You can set the client options on the Knative Http producer 
factory as follows:
 [source,java]
 ----
 import org.apache.camel.component.knative.KnativeComponent;
-import org.apache.camel.component.knative.http.KnativeHttpClientOptions;
+import org.apache.camel.component.knative.http.KnativeSslClientOptions;
 import org.apache.camel.component.knative.http.KnativeHttpProducerFactory;
 
-KnativeHttpClientOptions sslClientOptions = new 
KnativeHttpClientOptions(context);
+KnativeSslClientOptions sslClientOptions = new 
KnativeSslClientOptions(context);
 sslClientOptions.setSslEnabled(true);
 sslClientOptions.setKeyPath("keystore/client.pem");
 sslClientOptions.setKeyCertPath("keystore/client.crt");
@@ -114,7 +114,7 @@ TIP: When there is no proper trust certificate available 
(e.g. on test environme
 sslClientOptions.setTrustOptions(TrustAllOptions.INSTANCE);
 ----
 
-==== Autoconfiguration SSL options via environment variables
+==== Autoconfigure SSL options via environment variables
 
 The Knative client options are able to perform autoconfiguration based on 
resolving properties from system property or environment variable settings.
 During the initialization phase the client options automatically look for 
environment settings that configure the options.
@@ -133,10 +133,10 @@ camel.knative.client.ssl.enabled=true
 camel.knative.client.ssl.key.path=keystore/client.pem
 camel.knative.client.ssl.key.cert.path=keystore/client.crt
 
-camel.component.knative.producerFactory.clientOptions=#class:org.apache.camel.component.knative.http.KnativeHttpClientOptions
+camel.component.knative.producerFactory.clientOptions=#class:org.apache.camel.component.knative.http.KnativeSslClientOptions
 ----
 
-This will instantiate a new instance of 
`org.apache.camel.component.knative.http.KnativeHttpClientOptions` and perform 
the autoconfiguration via system property and environment variable settings on 
that instance.
+This will instantiate a new instance of 
`org.apache.camel.component.knative.http.KnativeSslClientOptions` and perform 
the autoconfiguration via system property and environment variable settings on 
that instance.
 
 TIP: By default, the SSL client options will verify the hostname of the 
Knative broker as part of the SSL handshake.
 In test environments this often leads to SSL handshake errors. You can disable 
the hostname verification for the client options with 
`camel.knative.client.ssl.verify.hostname=false`
@@ -167,4 +167,77 @@ spec:
             value: "true"
           - name: CAMEL_KNATIVE_CLIENT_SSL_KEY_CERT_PATH
             value: /knative-certs/knative-eventing-bundle.pem
-----
\ No newline at end of file
+----
+
+=== OpenID Connect support
+
+OpenID Connect (OIDC) is an identity authentication protocol that works with 
OAuth 2.0 to standardize the process for authenticating and authorizing users.
+
+Knative eventing supports OIDC access tokens that get injected as part of a 
`SinkBinding` resource. The injection is done in the form of a volume mount on 
the sink binding subject (usually the app deployment).
+
+This means the OIDC access token is mounted as a file into the application 
container so Camel client may read the token and set proper `Authorization` 
Http headers on each request.
+
+You need to enable OIDC support on the Knative Http client in the options like 
this:
+
+.Example
+[source,java]
+----
+import org.apache.camel.component.knative.KnativeComponent;
+import org.apache.camel.component.knative.http.KnativeOidcClientOptions;
+import org.apache.camel.component.knative.http.KnativeHttpProducerFactory;
+
+KnativeOidcClientOptions oidcClientOptions = new 
KnativeOidcClientOptions(context);
+oidcClientOptions.setOidcEnabled(true);
+oidcClientOptions.setOidcTokenPath("oidc/token");
+
+KnativeComponent component = context.getComponent("knative", 
KnativeComponent.class);
+if (component.getProducerFactory() instanceof KnativeHttpProducerFactory 
httpProducerFactory) {
+    httpProducerFactory.setClientOptions(oidcClientOptions);
+}
+----
+
+As a result each request of the Knative client will have an `Authorization` 
Http header with the access token.
+
+==== Autoconfigure OIDC options via environment variables
+
+The Knative client options are able to perform autoconfiguration based on 
resolving properties from system property or environment variable settings.
+During the initialization phase the client automatically looks for environment 
settings that configure the options.
+
+All environment settings that configure the Knative client OIDC options use a 
specific property key prefix
+
+* camel.knative.client.oidc.<property_name>
+* CAMEL_KNATIVE_CLIENT_OIDC_<PROPERTY_NAME>
+
+You can use this kind of autoconfiguration to enable OIDC on the Knative 
client with property based config only.
+
+.application.properties
+[source,properties]
+----
+camel.knative.client.oidc.enabled=true
+camel.knative.client.oidc.token.path=oidc/token
+
+camel.component.knative.producerFactory.clientOptions=#class:org.apache.camel.component.knative.http.KnativeOidcClientOptions
+----
+
+This will instantiate a new instance of 
`org.apache.camel.component.knative.http.KnativeOidcClientOptions` and perform 
the autoconfiguration via system property and environment variable settings on 
that instance.
+
+=== OIDC token renewal
+
+The OIDC tokens may expire and get renewed by Knative eventing. The renewal 
means that the volume mount is updated with the new token automatically.
+
+In order to refresh the token the Camel Knative client must read the token 
again.
+The Knative client options supports the token renewal on a `401 forbidden` 
response from the Knative broker.
+
+Once the client has received the forbidden answer it automatically reloads the 
token from the volume mount to perform the renewal.
+
+As an alternative to that you may disable the token cache on the client so the 
token is always read from the volume mount for each request.
+
+.application.properties
+[source,properties]
+----
+camel.knative.client.oidc.enabled=true
+camel.knative.client.oidc.token.path=oidc/token
+
+camel.knative.client.oidc.renew.tokens.on.forbidden=false
+camel.knative.client.oidc.cache.tokens=false
+----
diff --git 
a/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpProducer.java
 
b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpProducer.java
index 0a9e2f467fe..867f9b3c9b8 100644
--- 
a/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpProducer.java
+++ 
b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpProducer.java
@@ -27,6 +27,7 @@ import io.vertx.core.http.HttpHeaders;
 import io.vertx.ext.web.client.HttpResponse;
 import io.vertx.ext.web.client.WebClient;
 import io.vertx.ext.web.client.WebClientOptions;
+import io.vertx.ext.web.client.impl.WebClientBase;
 import org.apache.camel.AsyncCallback;
 import org.apache.camel.CamelException;
 import org.apache.camel.Endpoint;
@@ -170,6 +171,10 @@ public class KnativeHttpProducer extends 
DefaultAsyncProducer {
         this.uri = getUrl(serviceDefinition);
         this.host = getHost(serviceDefinition);
         this.client = WebClient.create(vertx, clientOptions);
+
+        if (clientOptions instanceof KnativeOidcClientOptions 
oidcClientOptions) {
+            ((WebClientBase) this.client).addInterceptor(new 
KnativeOidcInterceptor(oidcClientOptions));
+        }
     }
 
     @Override
diff --git 
a/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpSupport.java
 
b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpSupport.java
index 8cb47c14a30..a9665be83ec 100644
--- 
a/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpSupport.java
+++ 
b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpSupport.java
@@ -147,9 +147,9 @@ public final class KnativeHttpSupport {
      * @param  camelContext the current context.
      * @return              client options or empty
      */
-    public static Optional<KnativeHttpClientOptions> 
lookupClientOptions(CamelContext camelContext) {
-        KnativeHttpClientOptions clientOptions
-                = CamelContextHelper.findSingleByType(camelContext, 
KnativeHttpClientOptions.class);
+    public static Optional<KnativeSslClientOptions> 
lookupClientOptions(CamelContext camelContext) {
+        KnativeSslClientOptions clientOptions
+                = CamelContextHelper.findSingleByType(camelContext, 
KnativeSslClientOptions.class);
         if (clientOptions != null) {
             return Optional.of(clientOptions);
         }
diff --git 
a/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeOidcClientOptions.java
 
b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeOidcClientOptions.java
new file mode 100644
index 00000000000..cfcb4d22232
--- /dev/null
+++ 
b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeOidcClientOptions.java
@@ -0,0 +1,146 @@
+/*
+ * 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.knative.http;
+
+import java.io.IOException;
+import java.util.Optional;
+
+import io.vertx.ext.web.client.OAuth2WebClientOptions;
+import org.apache.camel.CamelContext;
+import org.apache.camel.spi.PropertiesComponent;
+import org.apache.camel.support.ResourceHelper;
+import org.apache.camel.util.IOHelper;
+
+/**
+ * Knative client options are able to autoconfigure OpenID Connect 
authentication with the use of an access token. The
+ * path to the OIDC access token is configurable via system property or 
environment variable settings. Usually the token
+ * is mounted by a Kubernetes volume and gets refreshed over time. The options 
provide a procedure to renew the token.
+ * Basically that means reading the token again from the given path to get the 
updated value. As an alternative to that
+ * you can disable token caching so the token is read for each request.
+ */
+public class KnativeOidcClientOptions extends KnativeSslClientOptions {
+
+    private static final String PROPERTY_PREFIX = "camel.knative.client.oidc.";
+
+    private final OAuth2WebClientOptions oAuth2ClientOptions = new 
OAuth2WebClientOptions().setRenewTokenOnForbidden(true);
+
+    private boolean oidcEnabled;
+
+    private String oidcTokenPath;
+
+    private String oidcToken;
+
+    private boolean cacheTokens = true;
+
+    public KnativeOidcClientOptions() {
+    }
+
+    public KnativeOidcClientOptions(CamelContext camelContext) {
+        super(camelContext);
+    }
+
+    /**
+     * Configures this web client options instance based on properties and 
environment variables resolved with the given
+     * Camel context.
+     */
+    public void configureOptions(CamelContext camelContext) {
+        super.configureOptions(camelContext);
+
+        PropertiesComponent propertiesComponent = 
camelContext.getPropertiesComponent();
+
+        boolean oidcEnabled = Boolean.parseBoolean(
+                propertiesComponent.resolveProperty(PROPERTY_PREFIX + 
"enabled").orElse("false"));
+        setOidcEnabled(oidcEnabled);
+
+        if (oidcEnabled) {
+            Optional<String> oidcTokenPath = 
propertiesComponent.resolveProperty(PROPERTY_PREFIX + "token.path");
+            oidcTokenPath.ifPresent(token -> this.oidcTokenPath = token);
+
+            boolean renewTokenOnForbidden = Boolean.parseBoolean(
+                    propertiesComponent.resolveProperty(PROPERTY_PREFIX + 
"renew.tokens.on.forbidden").orElse("true"));
+
+            
oAuth2ClientOptions.setRenewTokenOnForbidden(renewTokenOnForbidden);
+
+            boolean cacheTokens = Boolean.parseBoolean(
+                    propertiesComponent.resolveProperty(PROPERTY_PREFIX + 
"cache.tokens").orElse("true"));
+            setCacheTokens(cacheTokens);
+        }
+    }
+
+    /**
+     * Read OIDC token from given path. Caches the token for future usage.
+     */
+    public String retrieveOidcToken() {
+        if (oidcToken == null || !cacheTokens) {
+            try {
+                oidcToken = IOHelper
+                        
.loadText(ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(),
 oidcTokenPath))
+                        .trim();
+            } catch (IOException e) {
+                throw new RuntimeException(e);
+            }
+        }
+
+        return oidcToken;
+    }
+
+    /**
+     * Force renew of token by reading again from token path. Token may have 
been renewed already via volume mount
+     * update.
+     */
+    public String renewOidcToken() {
+        oidcToken = null;
+        return retrieveOidcToken();
+    }
+
+    public void setOidcEnabled(boolean oidcEnabled) {
+        this.oidcEnabled = oidcEnabled;
+    }
+
+    public boolean isOidcEnabled() {
+        return oidcEnabled;
+    }
+
+    public void setCacheTokens(boolean cacheTokens) {
+        this.cacheTokens = cacheTokens;
+    }
+
+    public boolean isCacheTokens() {
+        return cacheTokens;
+    }
+
+    public void setOidcTokenPath(String oidcTokenPath) {
+        this.oidcTokenPath = oidcTokenPath;
+    }
+
+    public String getOidcTokenPath() {
+        return oidcTokenPath;
+    }
+
+    public void setRenewTokenOnForbidden(boolean enabled) {
+        this.oAuth2ClientOptions.setRenewTokenOnForbidden(enabled);
+    }
+
+    public boolean isRenewTokenOnForbidden() {
+        return this.oAuth2ClientOptions.isRenewTokenOnForbidden();
+    }
+
+    public OAuth2WebClientOptions getOAuth2ClientOptions() {
+        return oAuth2ClientOptions;
+    }
+}
diff --git 
a/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeOidcInterceptor.java
 
b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeOidcInterceptor.java
new file mode 100644
index 00000000000..4fc9b539c22
--- /dev/null
+++ 
b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeOidcInterceptor.java
@@ -0,0 +1,87 @@
+/*
+ * 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.knative.http;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import io.vertx.core.Handler;
+import io.vertx.core.http.HttpHeaders;
+import io.vertx.ext.web.client.impl.HttpContext;
+import org.apache.camel.RuntimeCamelException;
+
+public class KnativeOidcInterceptor implements Handler<HttpContext<?>> {
+
+    private final Set<HttpContext<?>> dejaVu = new HashSet<>();
+    private final KnativeOidcClientOptions oidcClientOptions;
+
+    public KnativeOidcInterceptor(KnativeOidcClientOptions options) {
+        oidcClientOptions = options;
+    }
+
+    @Override
+    public void handle(HttpContext<?> context) {
+        switch (context.phase()) {
+            case CREATE_REQUEST:
+                addAuthorizationHeader(context);
+                break;
+            case DISPATCH_RESPONSE:
+                checkTokenRenew(context);
+                break;
+            default:
+                context.next();
+                break;
+        }
+    }
+
+    private void checkTokenRenew(HttpContext<?> context) {
+        if (context.response().statusCode() == 401) {
+            if (!oidcClientOptions.isRenewTokenOnForbidden() || 
dejaVu.contains(context)) {
+                // already seen, clear and continue without recovery
+                dejaVu.remove(context);
+                context.next();
+            } else {
+                // we need some stop condition, so we don't go into an 
infinite loop
+                dejaVu.add(context);
+                String old = oidcClientOptions.retrieveOidcToken();
+                String renewed = oidcClientOptions.renewOidcToken();
+                if (old.equals(renewed)) {
+                    // token has not been renewed continue with 401 response
+                    dejaVu.remove(context);
+                    context.next();
+                } else {
+                    // retry request with renewed token
+                    context.createRequest(context.requestOptions());
+                }
+            }
+        } else {// already seen, clear and continue without recovery
+            dejaVu.remove(context);
+            context.next();
+        }
+    }
+
+    private void addAuthorizationHeader(HttpContext<?> context) {
+        if (oidcClientOptions.getOidcTokenPath() == null) {
+            context.fail(new RuntimeCamelException("Missing OIDC access token 
path"));
+            return;
+        }
+
+        context.requestOptions().putHeader(HttpHeaders.AUTHORIZATION, "Bearer 
" + oidcClientOptions.retrieveOidcToken());
+        context.next();
+    }
+}
diff --git 
a/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpClientOptions.java
 
b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeSslClientOptions.java
similarity index 98%
rename from 
components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpClientOptions.java
rename to 
components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeSslClientOptions.java
index 9e0901766a6..65ec42fa3da 100644
--- 
a/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeHttpClientOptions.java
+++ 
b/components/camel-knative/camel-knative-http/src/main/java/org/apache/camel/component/knative/http/KnativeSslClientOptions.java
@@ -35,7 +35,7 @@ import org.apache.camel.spi.PropertiesComponent;
  * initialized via system property or environment variable settings. System 
property and environment variable settings
  * use a specific property name prefix. The properties get resolved via the 
given Camel context property component.
  */
-public class KnativeHttpClientOptions extends WebClientOptions implements 
CamelContextAware {
+public class KnativeSslClientOptions extends WebClientOptions implements 
CamelContextAware {
 
     private static final String PROPERTY_PREFIX = "camel.knative.client.ssl.";
 
@@ -54,10 +54,10 @@ public class KnativeHttpClientOptions extends 
WebClientOptions implements CamelC
     private KeyCertOptions keyCertOptions;
     private TrustOptions trustOptions;
 
-    public KnativeHttpClientOptions() {
+    public KnativeSslClientOptions() {
     }
 
-    public KnativeHttpClientOptions(CamelContext camelContext) {
+    public KnativeSslClientOptions(CamelContext camelContext) {
         this.camelContext = camelContext;
         configureOptions(camelContext);
     }
diff --git 
a/components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpServer.java
 
b/components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpServer.java
index df8782a054d..66d71b124b7 100644
--- 
a/components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpServer.java
+++ 
b/components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpServer.java
@@ -33,6 +33,7 @@ import io.vertx.ext.web.Router;
 import io.vertx.ext.web.RoutingContext;
 import io.vertx.ext.web.handler.BodyHandler;
 import org.apache.camel.CamelContext;
+import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.component.platform.http.PlatformHttpConstants;
 import org.apache.camel.support.service.ServiceSupport;
 import org.apache.camel.test.AvailablePortFinder;
@@ -124,8 +125,12 @@ public class KnativeHttpServer extends ServiceSupport {
                     BodyHandler.create().handle(event);
                 })
                 .handler(event -> {
-                    this.requests.offer(event.request());
-                    event.next();
+                    boolean success = this.requests.offer(event.request());
+                    if (success) {
+                        event.next();
+                    } else {
+                        event.fail(new RuntimeCamelException("Failed to save 
request to in-memory storage"));
+                    }
                 })
                 .handler(handler);
 
@@ -239,4 +244,8 @@ public class KnativeHttpServer extends ServiceSupport {
     protected HttpServerOptions getServerOptions() {
         return new HttpServerOptions();
     }
+
+    public int getNumberOfRequestsRemaining() {
+        return requests.size();
+    }
 }
diff --git 
a/components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpTest.java
 
b/components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpTest.java
index 40d6198ace0..e138f80c247 100644
--- 
a/components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpTest.java
+++ 
b/components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpTest.java
@@ -22,12 +22,15 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.UUID;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 import io.restassured.RestAssured;
 import io.restassured.mapper.ObjectMapperType;
+import io.vertx.core.http.HttpHeaders;
 import io.vertx.core.http.HttpServerRequest;
 import org.apache.camel.CamelContext;
 import org.apache.camel.CamelException;
+import org.apache.camel.CamelExecutionException;
 import org.apache.camel.Exchange;
 import org.apache.camel.FailedToStartRouteException;
 import org.apache.camel.ProducerTemplate;
@@ -46,6 +49,7 @@ import org.apache.camel.support.service.ServiceHelper;
 import org.apache.camel.test.AvailablePortFinder;
 import org.apache.camel.util.ObjectHelper;
 import org.apache.camel.util.StringHelper;
+import org.assertj.core.api.Assertions;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.params.ParameterizedTest;
@@ -1946,7 +1950,7 @@ public class KnativeHttpTest {
                         Map.of(
                                 Knative.CONTENT_TYPE, "text/plain")));
 
-        KnativeHttpClientOptions clientOptions = new 
KnativeHttpClientOptions(context);
+        KnativeSslClientOptions clientOptions = new 
KnativeSslClientOptions(context);
         clientOptions.setSslEnabled(true);
         clientOptions.setKeyPath("keystore/client.pem");
         clientOptions.setKeyCertPath("keystore/client.crt");
@@ -1994,7 +1998,7 @@ public class KnativeHttpTest {
                         Map.of(
                                 Knative.CONTENT_TYPE, "text/plain")));
 
-        KnativeHttpClientOptions clientOptions = new 
KnativeHttpClientOptions(context);
+        KnativeSslClientOptions clientOptions = new 
KnativeSslClientOptions(context);
         clientOptions.setSslEnabled(true);
         clientOptions.setKeyPath("keystore/client.p12");
         clientOptions.setVerifyHostName(false);
@@ -2041,7 +2045,7 @@ public class KnativeHttpTest {
                         Map.of(
                                 Knative.CONTENT_TYPE, "text/plain")));
 
-        KnativeHttpClientOptions clientOptions = new 
KnativeHttpClientOptions(context);
+        KnativeSslClientOptions clientOptions = new 
KnativeSslClientOptions(context);
         clientOptions.setSslEnabled(true);
         clientOptions.setKeystorePath("keystore/client.jks");
         clientOptions.setKeystorePassword("secr3t");
@@ -2090,7 +2094,7 @@ public class KnativeHttpTest {
                         Map.of(
                                 Knative.CONTENT_TYPE, "text/plain")));
 
-        KnativeHttpClientOptions sslClientOptions = new 
KnativeHttpClientOptions(context);
+        KnativeSslClientOptions sslClientOptions = new 
KnativeSslClientOptions(context);
         sslClientOptions.setSslEnabled(true);
         sslClientOptions.setKeyPath("keystore/client.pem");
         sslClientOptions.setKeyCertPath("keystore/client.crt");
@@ -2142,7 +2146,7 @@ public class KnativeHttpTest {
                                 Knative.CONTENT_TYPE, "text/plain")));
 
         PropertyBindingSupport.build().bind(context, component,
-                "camel.component.knative.producerFactory.clientOptions", 
"#class:" + KnativeHttpClientOptions.class.getName());
+                "camel.component.knative.producerFactory.clientOptions", 
"#class:" + KnativeSslClientOptions.class.getName());
 
         RouteBuilder.addRoutes(context, b -> {
             b.from("direct:start")
@@ -2165,4 +2169,311 @@ public class KnativeHttpTest {
             server.stop();
         }
     }
+
+    @ParameterizedTest
+    @EnumSource(CloudEvents.class)
+    void testOidcClientOptions(CloudEvent ce) throws Exception {
+        final KnativeHttpServer server = new KnativeHttpServer(context);
+
+        KnativeComponent component = configureKnativeComponent(
+                context,
+                ce,
+                event(
+                        Knative.EndpointKind.sink,
+                        "default",
+                        String.format("http://%s:%d";, server.getHost(), 
server.getPort()),
+                        Map.of(
+                                Knative.CONTENT_TYPE, "text/plain")));
+
+        KnativeOidcClientOptions clientOptions = new 
KnativeOidcClientOptions(context);
+        clientOptions.setOidcEnabled(true);
+        clientOptions.setOidcTokenPath("classpath:oidc/token.txt");
+
+        if (component.getProducerFactory() instanceof 
KnativeHttpProducerFactory httpProducerFactory) {
+            httpProducerFactory.setClientOptions(clientOptions);
+        }
+
+        RouteBuilder.addRoutes(context, b -> {
+            b.from("direct:start")
+                    .to("knative:event");
+        });
+
+        context.start();
+        try {
+            server.start();
+            template.sendBody("direct:start", "");
+
+            HttpServerRequest request = server.poll(30, TimeUnit.SECONDS);
+            
assertThat(request.getHeader(HttpHeaders.AUTHORIZATION.toString())).isEqualTo("Bearer
 whatever_the_token_is");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_VERSION))).isEqualTo(ce.version());
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_TYPE)))
+                    .isEqualTo("org.apache.camel.event");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_ID))).isNotNull();
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_SOURCE))).isNotNull();
+            
assertThat(request.getHeader(Exchange.CONTENT_TYPE)).isEqualTo("text/plain");
+        } finally {
+            server.stop();
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(CloudEvents.class)
+    void testOidcClientOptionsRenewTokenOnForbidden(CloudEvent ce) throws 
Exception {
+        KnativeOidcClientOptions clientOptions = new 
KnativeOidcClientOptions(context);
+        clientOptions.setOidcEnabled(true);
+        clientOptions.setOidcTokenPath("classpath:oidc/token.txt");
+
+        AtomicBoolean forbidden = new AtomicBoolean(true);
+        AtomicBoolean ok = new AtomicBoolean(false);
+        final KnativeHttpServer server = new KnativeHttpServer(context, event 
-> {
+            // respond with 401 FORBIDDEN only the 1st request to trigger 
token renewal
+            if (forbidden.getAndSet(false)) {
+                event.response().setStatusCode(401);
+                
clientOptions.setOidcTokenPath("classpath:oidc/renewed_token.txt");
+            } else {
+                event.response().setStatusCode(200);
+                ok.set(true);
+            }
+            event.response().end();
+        });
+
+        KnativeComponent component = configureKnativeComponent(
+                context,
+                ce,
+                event(
+                        Knative.EndpointKind.sink,
+                        "default",
+                        String.format("http://%s:%d";, server.getHost(), 
server.getPort()),
+                        Map.of(
+                                Knative.CONTENT_TYPE, "text/plain")));
+
+        if (component.getProducerFactory() instanceof 
KnativeHttpProducerFactory httpProducerFactory) {
+            httpProducerFactory.setClientOptions(clientOptions);
+        }
+
+        RouteBuilder.addRoutes(context, b -> {
+            b.from("direct:start")
+                    .to("knative:event");
+        });
+
+        context.start();
+        try {
+            server.start();
+            template.sendBody("direct:start", "");
+
+            // verify 1st request was handled with FORBIDDEN
+            assertThat(forbidden.get()).isFalse();
+
+            // 1st request that has been forbidden
+            HttpServerRequest request = server.poll(30, TimeUnit.SECONDS);
+            
assertThat(request.getHeader(HttpHeaders.AUTHORIZATION.toString())).isEqualTo("Bearer
 whatever_the_token_is");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_VERSION))).isEqualTo(ce.version());
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_TYPE)))
+                    .isEqualTo("org.apache.camel.event");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_ID))).isNotNull();
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_SOURCE))).isNotNull();
+            
assertThat(request.getHeader(Exchange.CONTENT_TYPE)).isEqualTo("text/plain");
+
+            // assert one more request
+            assertThat(server.getNumberOfRequestsRemaining()).isEqualTo(1);
+
+            // 2nd request handled with success
+            assertThat(ok.get()).isTrue();
+
+            // 2nd request after token renewal
+            request = server.poll(30, TimeUnit.SECONDS);
+            
assertThat(request.getHeader(HttpHeaders.AUTHORIZATION.toString())).isEqualTo("Bearer
 the_renewed_token");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_VERSION))).isEqualTo(ce.version());
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_TYPE)))
+                    .isEqualTo("org.apache.camel.event");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_ID))).isNotNull();
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_SOURCE))).isNotNull();
+            
assertThat(request.getHeader(Exchange.CONTENT_TYPE)).isEqualTo("text/plain");
+        } finally {
+            server.stop();
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(CloudEvents.class)
+    void testOidcClientOptionsCacheTokensDisabled(CloudEvent ce) throws 
Exception {
+        KnativeOidcClientOptions clientOptions = new 
KnativeOidcClientOptions(context);
+        clientOptions.setOidcEnabled(true);
+        clientOptions.setRenewTokenOnForbidden(false);
+        clientOptions.setCacheTokens(false);
+        clientOptions.setOidcTokenPath("classpath:oidc/token.txt");
+
+        AtomicBoolean refresh = new AtomicBoolean(true);
+        final KnativeHttpServer server = new KnativeHttpServer(context, event 
-> {
+            // respond with 401 FORBIDDEN only the 1st request to trigger 
token renewal
+            if (refresh.getAndSet(false)) {
+                
clientOptions.setOidcTokenPath("classpath:oidc/renewed_token.txt");
+            }
+
+            event.response().setStatusCode(200);
+            event.response().end();
+        });
+
+        KnativeComponent component = configureKnativeComponent(
+                context,
+                ce,
+                event(
+                        Knative.EndpointKind.sink,
+                        "default",
+                        String.format("http://%s:%d";, server.getHost(), 
server.getPort()),
+                        Map.of(
+                                Knative.CONTENT_TYPE, "text/plain")));
+
+        if (component.getProducerFactory() instanceof 
KnativeHttpProducerFactory httpProducerFactory) {
+            httpProducerFactory.setClientOptions(clientOptions);
+        }
+
+        RouteBuilder.addRoutes(context, b -> {
+            b.from("direct:start")
+                    .to("knative:event");
+        });
+
+        context.start();
+        try {
+            server.start();
+            template.sendBody("direct:start", "1st");
+
+            // 1st request
+            HttpServerRequest request = server.poll(30, TimeUnit.SECONDS);
+            
assertThat(request.getHeader(HttpHeaders.AUTHORIZATION.toString())).isEqualTo("Bearer
 whatever_the_token_is");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_VERSION))).isEqualTo(ce.version());
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_TYPE)))
+                    .isEqualTo("org.apache.camel.event");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_ID))).isNotNull();
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_SOURCE))).isNotNull();
+            
assertThat(request.getHeader(Exchange.CONTENT_TYPE)).isEqualTo("text/plain");
+
+            template.sendBody("direct:start", "2nd");
+
+            // assert one more request
+            assertThat(server.getNumberOfRequestsRemaining()).isEqualTo(1);
+
+            // 2nd request with new token
+            request = server.poll(30, TimeUnit.SECONDS);
+            
assertThat(request.getHeader(HttpHeaders.AUTHORIZATION.toString())).isEqualTo("Bearer
 the_renewed_token");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_VERSION))).isEqualTo(ce.version());
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_TYPE)))
+                    .isEqualTo("org.apache.camel.event");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_ID))).isNotNull();
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_SOURCE))).isNotNull();
+            
assertThat(request.getHeader(Exchange.CONTENT_TYPE)).isEqualTo("text/plain");
+        } finally {
+            server.stop();
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(CloudEvents.class)
+    void testOidcClientOptionsRenewTokenOnForbiddenButSameValue(CloudEvent ce) 
throws Exception {
+        AtomicBoolean forbidden = new AtomicBoolean(true);
+        final KnativeHttpServer server = new KnativeHttpServer(context, event 
-> {
+            // respond with 401 FORBIDDEN only the 1st request to trigger 
token renewal
+            if (forbidden.getAndSet(false)) {
+                event.response().setStatusCode(401);
+            } else {
+                event.response().setStatusCode(200);
+            }
+            event.response().end();
+        });
+
+        KnativeComponent component = configureKnativeComponent(
+                context,
+                ce,
+                event(
+                        Knative.EndpointKind.sink,
+                        "default",
+                        String.format("http://%s:%d";, server.getHost(), 
server.getPort()),
+                        Map.of(
+                                Knative.CONTENT_TYPE, "text/plain")));
+
+        KnativeOidcClientOptions clientOptions = new 
KnativeOidcClientOptions(context);
+        clientOptions.setOidcEnabled(true);
+        clientOptions.setOidcTokenPath("classpath:oidc/token.txt");
+
+        if (component.getProducerFactory() instanceof 
KnativeHttpProducerFactory httpProducerFactory) {
+            httpProducerFactory.setClientOptions(clientOptions);
+        }
+
+        RouteBuilder.addRoutes(context, b -> {
+            b.from("direct:start")
+                    .to("knative:event");
+        });
+
+        context.start();
+        try {
+            server.start();
+            Assertions.assertThatExceptionOfType(CamelExecutionException.class)
+                    .isThrownBy(() -> template.sendBody("direct:start", ""))
+                    .withCause(new CamelException(
+                            "HTTP operation failed invoking http://%s:%d with 
statusCode: 401, statusMessage: Unauthorized"
+                                    .formatted(server.getHost(), 
server.getPort())));
+
+            // verify 1st request was handled with FORBIDDEN
+            assertThat(forbidden.get()).isFalse();
+
+            // 1st request that has been forbidden
+            HttpServerRequest request = server.poll(30, TimeUnit.SECONDS);
+            
assertThat(request.getHeader(HttpHeaders.AUTHORIZATION.toString())).isEqualTo("Bearer
 whatever_the_token_is");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_VERSION))).isEqualTo(ce.version());
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_TYPE)))
+                    .isEqualTo("org.apache.camel.event");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_ID))).isNotNull();
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_SOURCE))).isNotNull();
+            
assertThat(request.getHeader(Exchange.CONTENT_TYPE)).isEqualTo("text/plain");
+
+            // assert no more requests
+            assertThat(server.getNumberOfRequestsRemaining()).isEqualTo(0);
+        } finally {
+            server.stop();
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(CloudEvents.class)
+    void testOidcClientOptionsPropertyConf(CloudEvent ce) throws Exception {
+        final KnativeHttpServer server = new KnativeHttpServer(context);
+
+        
context.getPropertiesComponent().addInitialProperty("camel.knative.client.oidc.enabled",
 "true");
+        
context.getPropertiesComponent().addInitialProperty("camel.knative.client.oidc.token.path",
 "classpath:oidc/token.txt");
+
+        KnativeComponent component = configureKnativeComponent(
+                context,
+                ce,
+                event(
+                        Knative.EndpointKind.sink,
+                        "default",
+                        String.format("http://%s:%d";, server.getHost(), 
server.getPort()),
+                        Map.of(
+                                Knative.CONTENT_TYPE, "text/plain")));
+
+        PropertyBindingSupport.build().bind(context, component,
+                "camel.component.knative.producerFactory.clientOptions", 
"#class:" + KnativeOidcClientOptions.class.getName());
+
+        RouteBuilder.addRoutes(context, b -> {
+            b.from("direct:start")
+                    .to("knative:event");
+        });
+
+        context.start();
+        try {
+            server.start();
+            template.sendBody("direct:start", "");
+
+            HttpServerRequest request = server.poll(30, TimeUnit.SECONDS);
+            
assertThat(request.getHeader(HttpHeaders.AUTHORIZATION.toString())).isEqualTo("Bearer
 whatever_the_token_is");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_VERSION))).isEqualTo(ce.version());
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_TYPE)))
+                    .isEqualTo("org.apache.camel.event");
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_ID))).isNotNull();
+            assertThat(request.getHeader(httpAttribute(ce, 
CloudEvent.CAMEL_CLOUD_EVENT_SOURCE))).isNotNull();
+            
assertThat(request.getHeader(Exchange.CONTENT_TYPE)).isEqualTo("text/plain");
+        } finally {
+            server.stop();
+        }
+    }
 }
diff --git 
a/components/camel-knative/camel-knative-http/src/test/resources/oidc/renewed_token.txt
 
b/components/camel-knative/camel-knative-http/src/test/resources/oidc/renewed_token.txt
new file mode 100644
index 00000000000..7c8d5bc4f55
--- /dev/null
+++ 
b/components/camel-knative/camel-knative-http/src/test/resources/oidc/renewed_token.txt
@@ -0,0 +1 @@
+the_renewed_token
diff --git 
a/components/camel-knative/camel-knative-http/src/test/resources/oidc/token.txt 
b/components/camel-knative/camel-knative-http/src/test/resources/oidc/token.txt
new file mode 100644
index 00000000000..8236532d0b8
--- /dev/null
+++ 
b/components/camel-knative/camel-knative-http/src/test/resources/oidc/token.txt
@@ -0,0 +1 @@
+whatever_the_token_is


Reply via email to