lhotari commented on code in PR #25538:
URL: https://github.com/apache/pulsar/pull/25538#discussion_r3095283731
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/AuthenticationFactoryOAuth2.java:
##########
@@ -196,6 +236,18 @@ public ClientCredentialsBuilder
wellKnownMetadataPath(String wellKnownMetadataPa
return this;
}
+ /**
+ * Optional Certificate refresh interval in seconds
+ * This parameter can only be set when tls_client_auth.
Review Comment:
This feature would be useful also for ClientCredentialsFlow, I'll add some
other comments about unifying this.
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/AuthenticationOAuth2.java:
##########
@@ -158,7 +158,14 @@ public void configure(String encodedAuthParamString) {
Map<String, String> params =
parseAuthParameters(encodedAuthParamString);
String type = params.getOrDefault(CONFIG_PARAM_TYPE,
TYPE_CLIENT_CREDENTIALS);
if (TYPE_CLIENT_CREDENTIALS.equals(type)) {
- this.flow = ClientCredentialsFlow.fromParameters(params);
+ if (params.containsKey(TlsClientAuthFlow.CONFIG_PARAM_CERT_FILE)
+ && params.containsKey(TlsClientAuthFlow.CONFIG_PARAM_KEY_FILE)
+ &&
StringUtils.isNotBlank(params.get(TlsClientAuthFlow.CONFIG_PARAM_CERT_FILE))
+ &&
StringUtils.isNotBlank(params.get(TlsClientAuthFlow.CONFIG_PARAM_KEY_FILE))) {
Review Comment:
Would it make sense to add a separate parameter `auth_method` (or
`token_endpoint_auth_method`) which takes `tls_client_auth` or
`client_secret_basic` (default) for this purpose? It makes it possible to also
add validation if a required setting for `tls_client_auth` is missing.
Having a `auth_method` parameter would also make it easier to add more
methods later.
It looks like there's also `self_signed_tls_client_auth`.
Is it valid to provide a client certificate although `client_secret_basic`
is used?
That could be useful if there's a reverse proxy that validates that client's
identity, but the Authorization Server uses `client_secret_basic` for
authentication.
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/TlsClientAuthFlow.java:
##########
@@ -0,0 +1,244 @@
+/*
+ * 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.pulsar.client.impl.auth.oauth2;
+
+import java.io.IOException;
+import java.net.URL;
+import java.time.Duration;
+import java.util.Map;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import lombok.Builder;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.pulsar.PulsarVersion;
+import org.apache.pulsar.client.api.PulsarClientException;
+import
org.apache.pulsar.client.impl.auth.oauth2.protocol.ClientCredentialsExchangeRequest;
+import org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenClient;
+import
org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenExchangeException;
+import org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenResult;
+import org.apache.pulsar.client.util.ExecutorProvider;
+import org.apache.pulsar.client.util.PulsarHttpAsyncSslEngineFactory;
+import org.apache.pulsar.common.util.PulsarSslConfiguration;
+import org.apache.pulsar.common.util.PulsarSslFactory;
+import org.asynchttpclient.AsyncHttpClient;
+import org.asynchttpclient.DefaultAsyncHttpClient;
+import org.asynchttpclient.DefaultAsyncHttpClientConfig;
+import org.asynchttpclient.SslEngineFactory;
+
+/**
+ * Implementation of OAuth 2.0 Client TLS Authentication flow.
+ *
+ * @see <a href="https://datatracker.ietf.org/doc/html/rfc8705">RFC 8705 -
OAuth 2.0 Mutual-TLS Client Authentication</a>
+ */
+@Slf4j
+class TlsClientAuthFlow extends FlowBase {
+ public static final String CONFIG_PARAM_ISSUER_URL = "issuerUrl";
+ public static final String CONFIG_PARAM_CLIENT_ID = "clientId";
+ public static final String CONFIG_PARAM_CERT_FILE = "tlsCertFile";
+ public static final String CONFIG_PARAM_KEY_FILE = "tlsKeyFile";
+ public static final String CONFIG_PARAM_AUDIENCE = "audience";
+ public static final String CONFIG_PARAM_SCOPE = "scope";
+ public static final String CONFIG_PARAM_AUTO_CERT_REFRESH_DURATION =
"autoCertRefreshDuration";
+
+ private static final Duration DEFAULT_AUTO_CERT_REFRESH_DURATION =
Duration.ofSeconds(300);
+ private static final String DEFAULT_CLIENT_ID = "pulsar-client";
+
+ private static final long serialVersionUID = 1L;
+
+ private final String clientId;
+ private final String certFile;
+ private final String keyFile;
+ private final String audience;
+ private final String scope;
+ private final long autoCertRefreshSeconds; // Certificate refresh interval
in seconds
+ private final Duration connectTimeout;
+ private final Duration readTimeout;
+ private final String trustCertsFilePath;
+
+ private transient TokenClient exchanger;
+ private transient ScheduledExecutorService scheduler;
+ private transient PulsarSslFactory sslFactory;
+ private transient AsyncHttpClient tokenHttpClient;
+
+ private boolean initialized = false;
+
+ @Builder
+ public TlsClientAuthFlow(URL issuerUrl, String clientId, String certFile,
String keyFile, String audience,
+ String scope, Duration connectTimeout, Duration
readTimeout, String trustCertsFilePath,
+ String wellKnownMetadataPath, Duration
autoCertRefreshDuration) {
+ super(issuerUrl, connectTimeout, readTimeout, trustCertsFilePath,
wellKnownMetadataPath);
+ this.clientId = clientId == null ? DEFAULT_CLIENT_ID : clientId;
+ this.certFile = certFile;
+ this.keyFile = keyFile;
+ this.audience = audience;
+ this.scope = scope;
+ this.connectTimeout = connectTimeout;
+ this.readTimeout = readTimeout;
+ this.trustCertsFilePath = trustCertsFilePath;
+ this.autoCertRefreshSeconds =
getParameterDurationToSeconds(CONFIG_PARAM_AUTO_CERT_REFRESH_DURATION,
+ autoCertRefreshDuration, DEFAULT_AUTO_CERT_REFRESH_DURATION);
+ }
+
+ /**
+ * Constructs a {@link TlsClientAuthFlow} from configuration parameters.
+ *
+ * @param params Configuration parameters
+ * @return A new TlsClientAuthFlow instance
+ */
+ public static TlsClientAuthFlow fromParameters(Map<String, String> params)
{
+ URL issuerUrl = parseParameterUrl(params, CONFIG_PARAM_ISSUER_URL);
+ // In mTLS-based providers, caller input for client_id can be optional.
+ // Keep sending client_id in token request for RFC compatibility by
applying a default value.
+ String clientId = params.getOrDefault(CONFIG_PARAM_CLIENT_ID,
DEFAULT_CLIENT_ID);
+ String certFile = parseParameterString(params, CONFIG_PARAM_CERT_FILE);
+ String keyFile = parseParameterString(params, CONFIG_PARAM_KEY_FILE);
+ // These are optional parameters, so we allow null values
+ String scope = params.get(CONFIG_PARAM_SCOPE);
+ String audience = params.get(CONFIG_PARAM_AUDIENCE);
+ Duration connectTimeout = parseParameterDuration(params,
CONFIG_PARAM_CONNECT_TIMEOUT);
+ Duration readTimeout = parseParameterDuration(params,
CONFIG_PARAM_READ_TIMEOUT);
+ String trustCertsFilePath =
params.get(CONFIG_PARAM_TRUST_CERTS_FILE_PATH);
+ String wellKnownMetadataPath =
params.get(CONFIG_PARAM_WELL_KNOWN_METADATA_PATH);
+ Duration autoCertRefreshDuration = parseParameterDuration(params,
CONFIG_PARAM_AUTO_CERT_REFRESH_DURATION);
+
+ return TlsClientAuthFlow.builder()
+ .issuerUrl(issuerUrl)
+ .clientId(clientId)
+ .certFile(certFile)
+ .keyFile(keyFile)
+ .audience(audience)
+ .scope(scope)
+ .connectTimeout(connectTimeout)
+ .readTimeout(readTimeout)
+ .trustCertsFilePath(trustCertsFilePath)
+ .wellKnownMetadataPath(wellKnownMetadataPath)
+ .autoCertRefreshDuration(autoCertRefreshDuration)
+ .build();
+ }
+
+ @Override
+ public void initialize() throws PulsarClientException {
+ super.initialize();
+ assert this.metadata != null;
+
+ URL tokenUrl = this.metadata.getTokenEndpoint();
+ TlsHttpClientContext tlsHttpClientContext =
createTlsHttpClientContext(tokenUrl.getHost());
Review Comment:
It's not necessary to pass the hostname when creating
PulsarHttpAsyncSslEngineFactory. Therefore it should be possible to use the
httpclient as described in the comment about renaming defaultHttpClient to
createHttpClient in FlowBase and possibly overriding it in this class. (unless
providing a client certificate isn't desired when discovering the metadata,
that would be unexpected).
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/protocol/TokenClient.java:
##########
@@ -82,8 +85,31 @@ String
buildClientCredentialsBody(ClientCredentialsExchangeRequest req) {
*/
public TokenResult
exchangeClientCredentials(ClientCredentialsExchangeRequest req)
throws TokenExchangeException, IOException {
- String body = buildClientCredentialsBody(req);
+ String body = buildClientCredentialsBody(req, true);
+ return executeTokenRequest(body);
+ }
+ /**
+ * Performs a token exchange using TLS client authentication.
+ *
+ * @param req the client credentials request details for TLS client auth
+ * @return a token result
+ * @throws TokenExchangeException
+ */
+ public TokenResult exchangeTlsClientAuth(ClientCredentialsExchangeRequest
req)
+ throws TokenExchangeException, IOException {
+ String body = buildClientCredentialsBody(req, false);
+ return executeTokenRequest(body);
+ }
+
Review Comment:
No need to add this after adding `TokenEndpointAuthMethod authMethod` to
`ClientCredentialsExchangeRequest`
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/TlsClientAuthFlow.java:
##########
@@ -0,0 +1,244 @@
+/*
+ * 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.pulsar.client.impl.auth.oauth2;
+
+import java.io.IOException;
+import java.net.URL;
+import java.time.Duration;
+import java.util.Map;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import lombok.Builder;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.pulsar.PulsarVersion;
+import org.apache.pulsar.client.api.PulsarClientException;
+import
org.apache.pulsar.client.impl.auth.oauth2.protocol.ClientCredentialsExchangeRequest;
+import org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenClient;
+import
org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenExchangeException;
+import org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenResult;
+import org.apache.pulsar.client.util.ExecutorProvider;
+import org.apache.pulsar.client.util.PulsarHttpAsyncSslEngineFactory;
+import org.apache.pulsar.common.util.PulsarSslConfiguration;
+import org.apache.pulsar.common.util.PulsarSslFactory;
+import org.asynchttpclient.AsyncHttpClient;
+import org.asynchttpclient.DefaultAsyncHttpClient;
+import org.asynchttpclient.DefaultAsyncHttpClientConfig;
+import org.asynchttpclient.SslEngineFactory;
+
+/**
+ * Implementation of OAuth 2.0 Client TLS Authentication flow.
+ *
+ * @see <a href="https://datatracker.ietf.org/doc/html/rfc8705">RFC 8705 -
OAuth 2.0 Mutual-TLS Client Authentication</a>
+ */
+@Slf4j
+class TlsClientAuthFlow extends FlowBase {
+ public static final String CONFIG_PARAM_ISSUER_URL = "issuerUrl";
+ public static final String CONFIG_PARAM_CLIENT_ID = "clientId";
+ public static final String CONFIG_PARAM_CERT_FILE = "tlsCertFile";
+ public static final String CONFIG_PARAM_KEY_FILE = "tlsKeyFile";
+ public static final String CONFIG_PARAM_AUDIENCE = "audience";
+ public static final String CONFIG_PARAM_SCOPE = "scope";
+ public static final String CONFIG_PARAM_AUTO_CERT_REFRESH_DURATION =
"autoCertRefreshDuration";
+
+ private static final Duration DEFAULT_AUTO_CERT_REFRESH_DURATION =
Duration.ofSeconds(300);
+ private static final String DEFAULT_CLIENT_ID = "pulsar-client";
+
+ private static final long serialVersionUID = 1L;
+
+ private final String clientId;
+ private final String certFile;
+ private final String keyFile;
+ private final String audience;
+ private final String scope;
+ private final long autoCertRefreshSeconds; // Certificate refresh interval
in seconds
+ private final Duration connectTimeout;
+ private final Duration readTimeout;
+ private final String trustCertsFilePath;
+
+ private transient TokenClient exchanger;
+ private transient ScheduledExecutorService scheduler;
+ private transient PulsarSslFactory sslFactory;
+ private transient AsyncHttpClient tokenHttpClient;
+
+ private boolean initialized = false;
+
+ @Builder
+ public TlsClientAuthFlow(URL issuerUrl, String clientId, String certFile,
String keyFile, String audience,
+ String scope, Duration connectTimeout, Duration
readTimeout, String trustCertsFilePath,
+ String wellKnownMetadataPath, Duration
autoCertRefreshDuration) {
+ super(issuerUrl, connectTimeout, readTimeout, trustCertsFilePath,
wellKnownMetadataPath);
+ this.clientId = clientId == null ? DEFAULT_CLIENT_ID : clientId;
+ this.certFile = certFile;
+ this.keyFile = keyFile;
+ this.audience = audience;
+ this.scope = scope;
+ this.connectTimeout = connectTimeout;
+ this.readTimeout = readTimeout;
+ this.trustCertsFilePath = trustCertsFilePath;
+ this.autoCertRefreshSeconds =
getParameterDurationToSeconds(CONFIG_PARAM_AUTO_CERT_REFRESH_DURATION,
+ autoCertRefreshDuration, DEFAULT_AUTO_CERT_REFRESH_DURATION);
+ }
+
+ /**
+ * Constructs a {@link TlsClientAuthFlow} from configuration parameters.
+ *
+ * @param params Configuration parameters
+ * @return A new TlsClientAuthFlow instance
+ */
+ public static TlsClientAuthFlow fromParameters(Map<String, String> params)
{
+ URL issuerUrl = parseParameterUrl(params, CONFIG_PARAM_ISSUER_URL);
+ // In mTLS-based providers, caller input for client_id can be optional.
+ // Keep sending client_id in token request for RFC compatibility by
applying a default value.
+ String clientId = params.getOrDefault(CONFIG_PARAM_CLIENT_ID,
DEFAULT_CLIENT_ID);
+ String certFile = parseParameterString(params, CONFIG_PARAM_CERT_FILE);
+ String keyFile = parseParameterString(params, CONFIG_PARAM_KEY_FILE);
+ // These are optional parameters, so we allow null values
+ String scope = params.get(CONFIG_PARAM_SCOPE);
+ String audience = params.get(CONFIG_PARAM_AUDIENCE);
+ Duration connectTimeout = parseParameterDuration(params,
CONFIG_PARAM_CONNECT_TIMEOUT);
+ Duration readTimeout = parseParameterDuration(params,
CONFIG_PARAM_READ_TIMEOUT);
+ String trustCertsFilePath =
params.get(CONFIG_PARAM_TRUST_CERTS_FILE_PATH);
+ String wellKnownMetadataPath =
params.get(CONFIG_PARAM_WELL_KNOWN_METADATA_PATH);
+ Duration autoCertRefreshDuration = parseParameterDuration(params,
CONFIG_PARAM_AUTO_CERT_REFRESH_DURATION);
+
+ return TlsClientAuthFlow.builder()
+ .issuerUrl(issuerUrl)
+ .clientId(clientId)
+ .certFile(certFile)
+ .keyFile(keyFile)
+ .audience(audience)
+ .scope(scope)
+ .connectTimeout(connectTimeout)
+ .readTimeout(readTimeout)
+ .trustCertsFilePath(trustCertsFilePath)
+ .wellKnownMetadataPath(wellKnownMetadataPath)
+ .autoCertRefreshDuration(autoCertRefreshDuration)
+ .build();
+ }
+
+ @Override
+ public void initialize() throws PulsarClientException {
+ super.initialize();
+ assert this.metadata != null;
+
+ URL tokenUrl = this.metadata.getTokenEndpoint();
+ TlsHttpClientContext tlsHttpClientContext =
createTlsHttpClientContext(tokenUrl.getHost());
+ this.tokenHttpClient = tlsHttpClientContext.httpClient();
+ this.sslFactory = tlsHttpClientContext.sslFactory();
Review Comment:
Make the current defaultHttpClient in FlowBase protected and rename it to
createHttpClient. Override the method and create the http client there. This
avoids having 2 separate httpClient instances.
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/protocol/TokenClient.java:
##########
@@ -53,13 +53,16 @@ public void close() throws Exception {
* Constructing http request parameters.
*
* @param req object with relevant request parameters
+ * @param includeSecret whether to include client_secret in the request
body
* @return Generate the final request body from a map.
*/
- String buildClientCredentialsBody(ClientCredentialsExchangeRequest req) {
+ String buildClientCredentialsBody(ClientCredentialsExchangeRequest req,
boolean includeSecret) {
Map<String, String> bodyMap = new TreeMap<>();
bodyMap.put("grant_type", "client_credentials");
bodyMap.put("client_id", req.getClientId());
- bodyMap.put("client_secret", req.getClientSecret());
+ if (includeSecret) {
+ bodyMap.put("client_secret", req.getClientSecret());
+ }
// Only set audience and scope if they are non-empty.
Review Comment:
Instead of using `includeSecret`, Create an `enum` which is called
`TokenEndpointAuthMethod`. The `ClientCredentialsExchangeRequest` should have
a field `TokenEndpointAuthMethod authMethod` which carries the token endpoint
auth method.
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/TlsClientAuthFlow.java:
##########
@@ -0,0 +1,244 @@
+/*
+ * 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.pulsar.client.impl.auth.oauth2;
+
+import java.io.IOException;
+import java.net.URL;
+import java.time.Duration;
+import java.util.Map;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import lombok.Builder;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.pulsar.PulsarVersion;
+import org.apache.pulsar.client.api.PulsarClientException;
+import
org.apache.pulsar.client.impl.auth.oauth2.protocol.ClientCredentialsExchangeRequest;
+import org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenClient;
+import
org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenExchangeException;
+import org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenResult;
+import org.apache.pulsar.client.util.ExecutorProvider;
+import org.apache.pulsar.client.util.PulsarHttpAsyncSslEngineFactory;
+import org.apache.pulsar.common.util.PulsarSslConfiguration;
+import org.apache.pulsar.common.util.PulsarSslFactory;
+import org.asynchttpclient.AsyncHttpClient;
+import org.asynchttpclient.DefaultAsyncHttpClient;
+import org.asynchttpclient.DefaultAsyncHttpClientConfig;
+import org.asynchttpclient.SslEngineFactory;
+
+/**
+ * Implementation of OAuth 2.0 Client TLS Authentication flow.
+ *
+ * @see <a href="https://datatracker.ietf.org/doc/html/rfc8705">RFC 8705 -
OAuth 2.0 Mutual-TLS Client Authentication</a>
+ */
+@Slf4j
+class TlsClientAuthFlow extends FlowBase {
+ public static final String CONFIG_PARAM_ISSUER_URL = "issuerUrl";
+ public static final String CONFIG_PARAM_CLIENT_ID = "clientId";
+ public static final String CONFIG_PARAM_CERT_FILE = "tlsCertFile";
+ public static final String CONFIG_PARAM_KEY_FILE = "tlsKeyFile";
+ public static final String CONFIG_PARAM_AUDIENCE = "audience";
+ public static final String CONFIG_PARAM_SCOPE = "scope";
+ public static final String CONFIG_PARAM_AUTO_CERT_REFRESH_DURATION =
"autoCertRefreshDuration";
+
+ private static final Duration DEFAULT_AUTO_CERT_REFRESH_DURATION =
Duration.ofSeconds(300);
+ private static final String DEFAULT_CLIENT_ID = "pulsar-client";
+
+ private static final long serialVersionUID = 1L;
+
+ private final String clientId;
+ private final String certFile;
+ private final String keyFile;
+ private final String audience;
+ private final String scope;
+ private final long autoCertRefreshSeconds; // Certificate refresh interval
in seconds
+ private final Duration connectTimeout;
+ private final Duration readTimeout;
+ private final String trustCertsFilePath;
+
+ private transient TokenClient exchanger;
+ private transient ScheduledExecutorService scheduler;
+ private transient PulsarSslFactory sslFactory;
+ private transient AsyncHttpClient tokenHttpClient;
+
+ private boolean initialized = false;
+
+ @Builder
+ public TlsClientAuthFlow(URL issuerUrl, String clientId, String certFile,
String keyFile, String audience,
+ String scope, Duration connectTimeout, Duration
readTimeout, String trustCertsFilePath,
+ String wellKnownMetadataPath, Duration
autoCertRefreshDuration) {
+ super(issuerUrl, connectTimeout, readTimeout, trustCertsFilePath,
wellKnownMetadataPath);
+ this.clientId = clientId == null ? DEFAULT_CLIENT_ID : clientId;
+ this.certFile = certFile;
+ this.keyFile = keyFile;
+ this.audience = audience;
+ this.scope = scope;
+ this.connectTimeout = connectTimeout;
+ this.readTimeout = readTimeout;
+ this.trustCertsFilePath = trustCertsFilePath;
+ this.autoCertRefreshSeconds =
getParameterDurationToSeconds(CONFIG_PARAM_AUTO_CERT_REFRESH_DURATION,
+ autoCertRefreshDuration, DEFAULT_AUTO_CERT_REFRESH_DURATION);
+ }
+
+ /**
+ * Constructs a {@link TlsClientAuthFlow} from configuration parameters.
+ *
+ * @param params Configuration parameters
+ * @return A new TlsClientAuthFlow instance
+ */
+ public static TlsClientAuthFlow fromParameters(Map<String, String> params)
{
+ URL issuerUrl = parseParameterUrl(params, CONFIG_PARAM_ISSUER_URL);
+ // In mTLS-based providers, caller input for client_id can be optional.
+ // Keep sending client_id in token request for RFC compatibility by
applying a default value.
+ String clientId = params.getOrDefault(CONFIG_PARAM_CLIENT_ID,
DEFAULT_CLIENT_ID);
+ String certFile = parseParameterString(params, CONFIG_PARAM_CERT_FILE);
+ String keyFile = parseParameterString(params, CONFIG_PARAM_KEY_FILE);
+ // These are optional parameters, so we allow null values
+ String scope = params.get(CONFIG_PARAM_SCOPE);
+ String audience = params.get(CONFIG_PARAM_AUDIENCE);
+ Duration connectTimeout = parseParameterDuration(params,
CONFIG_PARAM_CONNECT_TIMEOUT);
+ Duration readTimeout = parseParameterDuration(params,
CONFIG_PARAM_READ_TIMEOUT);
+ String trustCertsFilePath =
params.get(CONFIG_PARAM_TRUST_CERTS_FILE_PATH);
+ String wellKnownMetadataPath =
params.get(CONFIG_PARAM_WELL_KNOWN_METADATA_PATH);
+ Duration autoCertRefreshDuration = parseParameterDuration(params,
CONFIG_PARAM_AUTO_CERT_REFRESH_DURATION);
+
+ return TlsClientAuthFlow.builder()
+ .issuerUrl(issuerUrl)
+ .clientId(clientId)
+ .certFile(certFile)
+ .keyFile(keyFile)
+ .audience(audience)
+ .scope(scope)
+ .connectTimeout(connectTimeout)
+ .readTimeout(readTimeout)
+ .trustCertsFilePath(trustCertsFilePath)
+ .wellKnownMetadataPath(wellKnownMetadataPath)
+ .autoCertRefreshDuration(autoCertRefreshDuration)
+ .build();
+ }
+
+ @Override
+ public void initialize() throws PulsarClientException {
+ super.initialize();
+ assert this.metadata != null;
+
+ URL tokenUrl = this.metadata.getTokenEndpoint();
+ TlsHttpClientContext tlsHttpClientContext =
createTlsHttpClientContext(tokenUrl.getHost());
+ this.tokenHttpClient = tlsHttpClientContext.httpClient();
+ this.sslFactory = tlsHttpClientContext.sslFactory();
+
+ this.exchanger = new TokenClient(tokenUrl, this.tokenHttpClient);
+
+ if (sslFactory != null && autoCertRefreshSeconds > 0) {
+ scheduler = Executors.newSingleThreadScheduledExecutor(new
ExecutorProvider
+ .ExtendedThreadFactory("tls-cert-refresher"));
+ scheduler.scheduleAtFixedRate(this::refreshSslContext,
+ autoCertRefreshSeconds, autoCertRefreshSeconds,
TimeUnit.SECONDS);
+
+ log.info("Scheduled TLS certificate refresh every {} seconds",
autoCertRefreshSeconds);
+ }
+
+ initialized = true;
+ }
+
+ private PulsarSslConfiguration buildSslConfiguration() {
+ return PulsarSslConfiguration.builder()
+ .tlsCertificateFilePath(certFile)
+ .tlsKeyFilePath(keyFile)
+ .tlsTrustCertsFilePath(trustCertsFilePath)
+ .allowInsecureConnection(false)
+ .serverMode(false)
+ .isHttps(true)
+ .build();
+ }
+
+ private TlsHttpClientContext createTlsHttpClientContext(String hostname)
throws PulsarClientException {
+ try {
+ PulsarSslConfiguration sslConfiguration = buildSslConfiguration();
+ PulsarSslFactory sslFactory = new
org.apache.pulsar.common.util.DefaultPulsarSslFactory();
+ sslFactory.initialize(sslConfiguration);
+ sslFactory.createInternalSslContext();
+
+ DefaultAsyncHttpClientConfig.Builder confBuilder = new
DefaultAsyncHttpClientConfig.Builder();
+ confBuilder.setCookieStore(null);
+ confBuilder.setUseProxyProperties(true);
+ confBuilder.setFollowRedirect(true);
+ confBuilder.setConnectTimeout(
+ getParameterDurationToMillis(
+ CONFIG_PARAM_CONNECT_TIMEOUT, connectTimeout,
DEFAULT_CONNECT_TIMEOUT));
+ confBuilder.setReadTimeout(
+ getParameterDurationToMillis(CONFIG_PARAM_READ_TIMEOUT,
readTimeout, DEFAULT_READ_TIMEOUT));
+ confBuilder.setUserAgent(String.format("Pulsar-Java-v%s",
PulsarVersion.getVersion()));
+ SslEngineFactory sslEngineFactory = new
PulsarHttpAsyncSslEngineFactory(sslFactory, hostname);
Review Comment:
In FlowBase, create another protected method which creates a
DefaultAsyncHttpClientConfig.Builder which could then be used in the overridden
createHttpClient where the HttpClient instance should be created.
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/TlsClientAuthFlow.java:
##########
@@ -0,0 +1,244 @@
+/*
+ * 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.pulsar.client.impl.auth.oauth2;
+
+import java.io.IOException;
+import java.net.URL;
+import java.time.Duration;
+import java.util.Map;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import lombok.Builder;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.pulsar.PulsarVersion;
+import org.apache.pulsar.client.api.PulsarClientException;
+import
org.apache.pulsar.client.impl.auth.oauth2.protocol.ClientCredentialsExchangeRequest;
+import org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenClient;
+import
org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenExchangeException;
+import org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenResult;
+import org.apache.pulsar.client.util.ExecutorProvider;
+import org.apache.pulsar.client.util.PulsarHttpAsyncSslEngineFactory;
+import org.apache.pulsar.common.util.PulsarSslConfiguration;
+import org.apache.pulsar.common.util.PulsarSslFactory;
+import org.asynchttpclient.AsyncHttpClient;
+import org.asynchttpclient.DefaultAsyncHttpClient;
+import org.asynchttpclient.DefaultAsyncHttpClientConfig;
+import org.asynchttpclient.SslEngineFactory;
+
+/**
+ * Implementation of OAuth 2.0 Client TLS Authentication flow.
+ *
+ * @see <a href="https://datatracker.ietf.org/doc/html/rfc8705">RFC 8705 -
OAuth 2.0 Mutual-TLS Client Authentication</a>
+ */
+@Slf4j
+class TlsClientAuthFlow extends FlowBase {
+ public static final String CONFIG_PARAM_ISSUER_URL = "issuerUrl";
+ public static final String CONFIG_PARAM_CLIENT_ID = "clientId";
+ public static final String CONFIG_PARAM_CERT_FILE = "tlsCertFile";
+ public static final String CONFIG_PARAM_KEY_FILE = "tlsKeyFile";
+ public static final String CONFIG_PARAM_AUDIENCE = "audience";
+ public static final String CONFIG_PARAM_SCOPE = "scope";
+ public static final String CONFIG_PARAM_AUTO_CERT_REFRESH_DURATION =
"autoCertRefreshDuration";
+
+ private static final Duration DEFAULT_AUTO_CERT_REFRESH_DURATION =
Duration.ofSeconds(300);
+ private static final String DEFAULT_CLIENT_ID = "pulsar-client";
+
+ private static final long serialVersionUID = 1L;
+
+ private final String clientId;
+ private final String certFile;
+ private final String keyFile;
+ private final String audience;
+ private final String scope;
+ private final long autoCertRefreshSeconds; // Certificate refresh interval
in seconds
+ private final Duration connectTimeout;
+ private final Duration readTimeout;
+ private final String trustCertsFilePath;
+
+ private transient TokenClient exchanger;
+ private transient ScheduledExecutorService scheduler;
+ private transient PulsarSslFactory sslFactory;
+ private transient AsyncHttpClient tokenHttpClient;
+
+ private boolean initialized = false;
+
+ @Builder
+ public TlsClientAuthFlow(URL issuerUrl, String clientId, String certFile,
String keyFile, String audience,
+ String scope, Duration connectTimeout, Duration
readTimeout, String trustCertsFilePath,
+ String wellKnownMetadataPath, Duration
autoCertRefreshDuration) {
+ super(issuerUrl, connectTimeout, readTimeout, trustCertsFilePath,
wellKnownMetadataPath);
+ this.clientId = clientId == null ? DEFAULT_CLIENT_ID : clientId;
+ this.certFile = certFile;
+ this.keyFile = keyFile;
+ this.audience = audience;
+ this.scope = scope;
+ this.connectTimeout = connectTimeout;
+ this.readTimeout = readTimeout;
+ this.trustCertsFilePath = trustCertsFilePath;
+ this.autoCertRefreshSeconds =
getParameterDurationToSeconds(CONFIG_PARAM_AUTO_CERT_REFRESH_DURATION,
+ autoCertRefreshDuration, DEFAULT_AUTO_CERT_REFRESH_DURATION);
+ }
+
+ /**
+ * Constructs a {@link TlsClientAuthFlow} from configuration parameters.
+ *
+ * @param params Configuration parameters
+ * @return A new TlsClientAuthFlow instance
+ */
+ public static TlsClientAuthFlow fromParameters(Map<String, String> params)
{
+ URL issuerUrl = parseParameterUrl(params, CONFIG_PARAM_ISSUER_URL);
+ // In mTLS-based providers, caller input for client_id can be optional.
+ // Keep sending client_id in token request for RFC compatibility by
applying a default value.
+ String clientId = params.getOrDefault(CONFIG_PARAM_CLIENT_ID,
DEFAULT_CLIENT_ID);
+ String certFile = parseParameterString(params, CONFIG_PARAM_CERT_FILE);
+ String keyFile = parseParameterString(params, CONFIG_PARAM_KEY_FILE);
+ // These are optional parameters, so we allow null values
+ String scope = params.get(CONFIG_PARAM_SCOPE);
+ String audience = params.get(CONFIG_PARAM_AUDIENCE);
+ Duration connectTimeout = parseParameterDuration(params,
CONFIG_PARAM_CONNECT_TIMEOUT);
+ Duration readTimeout = parseParameterDuration(params,
CONFIG_PARAM_READ_TIMEOUT);
+ String trustCertsFilePath =
params.get(CONFIG_PARAM_TRUST_CERTS_FILE_PATH);
+ String wellKnownMetadataPath =
params.get(CONFIG_PARAM_WELL_KNOWN_METADATA_PATH);
+ Duration autoCertRefreshDuration = parseParameterDuration(params,
CONFIG_PARAM_AUTO_CERT_REFRESH_DURATION);
+
+ return TlsClientAuthFlow.builder()
+ .issuerUrl(issuerUrl)
+ .clientId(clientId)
+ .certFile(certFile)
+ .keyFile(keyFile)
+ .audience(audience)
+ .scope(scope)
+ .connectTimeout(connectTimeout)
+ .readTimeout(readTimeout)
+ .trustCertsFilePath(trustCertsFilePath)
+ .wellKnownMetadataPath(wellKnownMetadataPath)
+ .autoCertRefreshDuration(autoCertRefreshDuration)
+ .build();
+ }
+
+ @Override
+ public void initialize() throws PulsarClientException {
+ super.initialize();
+ assert this.metadata != null;
+
+ URL tokenUrl = this.metadata.getTokenEndpoint();
+ TlsHttpClientContext tlsHttpClientContext =
createTlsHttpClientContext(tokenUrl.getHost());
+ this.tokenHttpClient = tlsHttpClientContext.httpClient();
+ this.sslFactory = tlsHttpClientContext.sslFactory();
+
+ this.exchanger = new TokenClient(tokenUrl, this.tokenHttpClient);
+
+ if (sslFactory != null && autoCertRefreshSeconds > 0) {
+ scheduler = Executors.newSingleThreadScheduledExecutor(new
ExecutorProvider
+ .ExtendedThreadFactory("tls-cert-refresher"));
+ scheduler.scheduleAtFixedRate(this::refreshSslContext,
+ autoCertRefreshSeconds, autoCertRefreshSeconds,
TimeUnit.SECONDS);
+
+ log.info("Scheduled TLS certificate refresh every {} seconds",
autoCertRefreshSeconds);
+ }
+
Review Comment:
This feature would be useful also at FlowBase level
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]