GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [fix][client] Fail creation on explicit TLS client certificate alerts… · apache/pulsar@18c9d01

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pulsar-broker/src/test/java/org/apache/pulsar/client/api
    • TlsProducerConsumerTest.java
  • pulsar-client/src
    • main/java/org/apache/pulsar/client/impl
      • ClientCnx.java
    • test/java/org/apache/pulsar/client/impl
      • ClientCnxTlsTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pulsar-broker/src/test/java/org/apache/pulsar/client/api/TlsProducerConsumerTest.java‎

Copy file name to clipboardExpand all lines: pulsar-broker/src/test/java/org/apache/pulsar/client/api/TlsProducerConsumerTest.java
+40Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
*/
1919
package org.apache.pulsar.client.api;
2020

21+
import static org.assertj.core.api.Assertions.assertThat;
2122
import static org.mockito.Mockito.mock;
2223
import static org.mockito.Mockito.never;
2324
import static org.mockito.Mockito.spy;
@@ -29,14 +30,18 @@
2930
import java.io.InputStream;
3031
import java.util.Arrays;
3132
import java.util.Map;
33+
import java.util.Set;
34+
import java.util.concurrent.CompletableFuture;
3235
import java.util.concurrent.TimeUnit;
3336
import java.util.concurrent.atomic.AtomicInteger;
3437
import java.util.function.Supplier;
38+
import javax.net.ssl.SSLException;
3539
import lombok.Cleanup;
3640
import org.apache.commons.compress.utils.IOUtils;
3741
import org.apache.pulsar.broker.service.persistent.PersistentTopic;
3842
import org.apache.pulsar.client.admin.PulsarAdmin;
3943
import org.apache.pulsar.client.impl.auth.AuthenticationTls;
44+
import org.apache.pulsar.common.util.FutureUtil;
4045
import org.slf4j.Logger;
4146
import org.slf4j.LoggerFactory;
4247
import org.testng.Assert;
@@ -47,6 +52,41 @@
4752
public class TlsProducerConsumerTest extends TlsProducerConsumerBase {
4853
private static final Logger log = LoggerFactory.getLogger(TlsProducerConsumerTest.class);
4954

55+
@DataProvider
56+
public Object[][] tlsAuthenticationFailures() {
57+
return new Object[][]{
58+
{"JDK", true},
59+
{"JDK", false},
60+
{"OPENSSL", true},
61+
{"OPENSSL", false}
62+
};
63+
}
64+
65+
@Test(dataProvider = "tlsAuthenticationFailures", timeOut = 30_000)
66+
public void testMissingTlsClientCertificateFailsWithoutRetry(String sslProvider, boolean producer)
67+
throws Exception {
68+
try (PulsarClient client = PulsarClient.builder()
69+
.serviceUrl(pulsar.getBrokerServiceUrlTls())
70+
.sslProvider(sslProvider)
71+
.tlsProtocols(Set.of("TLSv1.3"))
72+
.tlsTrustCertsFilePath(CA_CERT_FILE_PATH)
73+
.operationTimeout(30, TimeUnit.SECONDS)
74+
.build()) {
75+
CompletableFuture<?> creation = producer
76+
? client.newProducer().topic("persistent://my-property/my-ns/missing-cert").createAsync()
77+
: client.newConsumer().topic("persistent://my-property/my-ns/missing-cert")
78+
.subscriptionName("missing-cert").subscribeAsync();
79+
Throwable failure = creation.handle((result, error) -> error).get(10, TimeUnit.SECONDS);
80+
assertThat(failure).isNotNull();
81+
Throwable cause = FutureUtil.unwrapCompletionException(failure);
82+
assertThat(cause).isInstanceOf(PulsarClientException.class);
83+
assertThat(PulsarClientException.isRetriableError(cause))
84+
.as("a TLS certificate_required alert must fail creation without retrying")
85+
.isFalse();
86+
assertThat(cause.getCause()).isInstanceOf(SSLException.class);
87+
}
88+
}
89+
5090
/**
5191
* verifies that messages whose size is larger than 2^14 bytes (max size of single TLS chunk) can be
5292
* produced/consumed.
Collapse file

‎pulsar-client/src/main/java/org/apache/pulsar/client/impl/ClientCnx.java‎

Copy file name to clipboardExpand all lines: pulsar-client/src/main/java/org/apache/pulsar/client/impl/ClientCnx.java
+33Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import io.netty.channel.ChannelHandlerContext;
3030
import io.netty.channel.EventLoopGroup;
3131
import io.netty.channel.unix.Errors.NativeIoException;
32+
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
3233
import io.netty.util.concurrent.Promise;
3334
import io.opentelemetry.api.common.Attributes;
3435
import java.net.InetSocketAddress;
@@ -49,6 +50,8 @@
4950
import java.util.concurrent.TimeUnit;
5051
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
5152
import java.util.concurrent.atomic.AtomicLong;
53+
import java.util.regex.Pattern;
54+
import javax.net.ssl.SSLException;
5255
import lombok.AccessLevel;
5356
import lombok.Getter;
5457
import org.apache.commons.lang3.exception.ExceptionUtils;
@@ -120,6 +123,12 @@
120123
@SuppressWarnings("unchecked")
121124
public class ClientCnx extends PulsarHandler {
122125

126+
private static final Pattern TLS_CLIENT_AUTHENTICATION_ALERT = Pattern.compile(
127+
"\\b(?:Received fatal alert: |(?:SSLV3|TLSV1|TLSV13)_ALERT_)"
128+
+ "(?:certificate_required|bad_certificate|unsupported_certificate|certificate_revoked"
129+
+ "|certificate_expired|certificate_unknown|unknown_ca)\\b",
130+
Pattern.CASE_INSENSITIVE);
131+
123132
protected final Authentication authentication;
124133
protected State state;
125134

@@ -375,8 +384,19 @@ public void channelInactive(ChannelHandlerContext ctx) throws Exception {
375384

376385
// Command Handlers
377386

387+
@Override
388+
public void userEventTriggered(ChannelHandlerContext ctx, Object event) {
389+
if (event instanceof SslHandshakeCompletionEvent handshake && !handshake.isSuccess()) {
390+
failOnTlsAuthenticationError(handshake.cause());
391+
}
392+
super.userEventTriggered(ctx, event);
393+
}
394+
378395
@Override
379396
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
397+
// TLS 1.3 may report success locally before the peer rejects the client certificate, so also
398+
// handle alerts received after SslHandshakeCompletionEvent.SUCCESS.
399+
failOnTlsAuthenticationError(cause);
380400
if (state != State.Failed) {
381401
// No need to report stack trace for known exceptions that happen in disconnections
382402
log.warn("[{}] Got exception {}", remoteAddress,
@@ -393,6 +413,19 @@ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws E
393413
ctx.close();
394414
}
395415

416+
private void failOnTlsAuthenticationError(Throwable cause) {
417+
for (Throwable error = cause; error != null; error = error.getCause()) {
418+
if (error instanceof SSLException && error.getMessage() != null
419+
&& TLS_CLIENT_AUTHENTICATION_ALERT.matcher(error.getMessage()).find()) {
420+
// Only explicit peer certificate alerts are terminal. A generic handshake failure,
421+
// timeout or connection reset can be transient and must retain the normal retry policy.
422+
connectionFuture.completeExceptionally(new PulsarClientException.InvalidConfigurationException(
423+
"TLS client authentication failed: " + error.getMessage(), error));
424+
return;
425+
}
426+
}
427+
}
428+
396429
public static boolean isKnownException(Throwable t) {
397430
return t instanceof NativeIoException || t instanceof ClosedChannelException;
398431
}
Collapse file

‎pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientCnxTlsTest.java‎

Copy file name to clipboard
+116Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
package org.apache.pulsar.client.impl;
20+
21+
import static org.assertj.core.api.Assertions.assertThat;
22+
import io.netty.channel.EventLoopGroup;
23+
import io.netty.channel.embedded.EmbeddedChannel;
24+
import io.netty.handler.codec.DecoderException;
25+
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
26+
import io.netty.util.concurrent.DefaultThreadFactory;
27+
import java.io.IOException;
28+
import java.util.concurrent.TimeUnit;
29+
import javax.net.ssl.SSLException;
30+
import javax.net.ssl.SSLHandshakeException;
31+
import org.apache.pulsar.client.api.PulsarClientException;
32+
import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
33+
import org.apache.pulsar.client.impl.metrics.InstrumentProvider;
34+
import org.apache.pulsar.common.util.FutureUtil;
35+
import org.apache.pulsar.common.util.netty.EventLoopUtil;
36+
import org.testng.annotations.DataProvider;
37+
import org.testng.annotations.Test;
38+
39+
public class ClientCnxTlsTest {
40+
41+
@DataProvider
42+
public Object[][] tlsAuthenticationAlerts() {
43+
return new Object[][]{
44+
{"Received fatal alert: certificate_required"},
45+
{"Received fatal alert: bad_certificate"},
46+
{"Received fatal alert: unsupported_certificate"},
47+
{"Received fatal alert: certificate_revoked"},
48+
{"Received fatal alert: certificate_expired"},
49+
{"Received fatal alert: certificate_unknown"},
50+
{"Received fatal alert: unknown_ca"},
51+
{"error:1000045c:SSL routines:OPENSSL_internal:TLSV1_ALERT_CERTIFICATE_REQUIRED"},
52+
{"error:10000412:SSL routines:OPENSSL_internal:SSLV3_ALERT_BAD_CERTIFICATE"},
53+
{"error:10000418:SSL routines:OPENSSL_internal:TLSV1_ALERT_UNKNOWN_CA"}
54+
};
55+
}
56+
57+
@Test(dataProvider = "tlsAuthenticationAlerts")
58+
public void testTlsAuthenticationAlertIsNotRetriable(String message) throws Exception {
59+
SSLException alert = new SSLHandshakeException(message);
60+
assertTlsFailure(alert, true, false);
61+
// TLS 1.3 can finish the local handshake before the server rejects the client certificate.
62+
assertTlsFailure(alert, false, false);
63+
}
64+
65+
@DataProvider
66+
public Object[][] otherConnectionFailures() {
67+
return new Object[][]{
68+
{new IOException("Connection reset")},
69+
{new SSLHandshakeException("Remote host terminated the handshake")},
70+
{new SSLHandshakeException("Received fatal alert: handshake_failure")},
71+
{new SSLHandshakeException("Received fatal alert: protocol_version")},
72+
{new SSLHandshakeException("Received fatal alert: bad_certificate_status_response")},
73+
{new SSLHandshakeException("PKIX path building failed: unable to find valid certification path")},
74+
{new SSLException("TLS handshake timed out")},
75+
{new SSLException("certificate_expired")},
76+
{new SSLException((String) null)},
77+
{new IOException("Received fatal alert: certificate_required")}
78+
};
79+
}
80+
81+
@Test(dataProvider = "otherConnectionFailures")
82+
public void testOtherConnectionFailuresRemainRetriable(Throwable cause) throws Exception {
83+
assertTlsFailure(cause, true, true);
84+
assertTlsFailure(cause, false, true);
85+
}
86+
87+
private void assertTlsFailure(Throwable cause, boolean handshakeEvent, boolean retriable) throws Exception {
88+
EventLoopGroup eventLoop = EventLoopUtil.newEventLoopGroup(1, false,
89+
new DefaultThreadFactory("client-cnx-tls-test"));
90+
ClientConfigurationData conf = new ClientConfigurationData();
91+
conf.setKeepAliveIntervalSeconds(0);
92+
ClientCnx cnx = new ClientCnx(InstrumentProvider.NOOP, conf, eventLoop);
93+
EmbeddedChannel channel = new EmbeddedChannel(cnx);
94+
try {
95+
if (handshakeEvent) {
96+
channel.pipeline().fireUserEventTriggered(new SslHandshakeCompletionEvent(cause));
97+
} else {
98+
channel.pipeline().fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS);
99+
channel.pipeline().fireExceptionCaught(new DecoderException(cause));
100+
}
101+
channel.close().sync();
102+
Throwable failure = cnx.connectionFuture().handle((result, error) -> error).get(5, TimeUnit.SECONDS);
103+
assertThat(failure).isNotNull();
104+
Throwable connectionError = FutureUtil.unwrapCompletionException(failure);
105+
assertThat(connectionError).isInstanceOf(PulsarClientException.class);
106+
assertThat(PulsarClientException.isRetriableError(connectionError)).isEqualTo(retriable);
107+
if (!retriable) {
108+
assertThat(connectionError.getCause()).isSameAs(cause);
109+
assertThat(connectionError).hasMessageContaining(cause.getMessage());
110+
}
111+
} finally {
112+
channel.finishAndReleaseAll();
113+
eventLoop.shutdownGracefully(0, 5, TimeUnit.SECONDS).sync();
114+
}
115+
}
116+
}

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.