You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by lh...@apache.org on 2026/08/12 21:04:58 UTC

(pulsar) 05/05: [fix][client] PIP-478: carry the v5 authentication through swap and close

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

lhotari pushed a commit to branch lh-pip-478-v5-native-auth-v2
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 3b7349f4befe85b05288ee0aab4b8caeac2803cd
Author: Lari Hotari <lh...@apache.org>
AuthorDate: Wed Aug 12 23:59:54 2026 +0300

    [fix][client] PIP-478: carry the v5 authentication through swap and close
    
    Two lifecycle paths still saw only the v4 slot, so the authentication the client actually
    drives was left behind. Both were found by review — the second independently by Codex.
    
    updateAuthentication(), which cluster failover uses, replaced the v4 plugin but left
    conf.v5Authentication and conf.v5AuthenticationDriver pointing at the previous credential
    body. Every new connection then kept presenting the OLD cluster's credential, served by a
    plugin the same method had just closed, so failing over to a cluster that requires the
    replacement credential would not authenticate. Re-resolve both after starting the new
    plugin.
    
    Client shutdown closed only conf.getAuthentication(). A v5-native plugin configured through
    the v5 builder lives only in the v5 slot — the v4 slot still holds AuthenticationDisabled —
    so whatever it holds open (HTTP clients, executors, credential handles) leaked on every
    close. Closing the v5 slot is safe for the other cases: a body handed over by a built-in
    shim owns nothing, and a bridged adapter built for an already-started plugin deliberately
    leaves that plugin to its owner, which is the v4 close that follows.
    
    Verified by mutation: reverting the first fails
    ClientAuthenticationLifecycleTest.swappingTheAuthenticationSwapsWhatTheClientDrives with
    the stale credential, reverting the second fails closingTheClientClosesAV5NativePlugin.
    
    Assisted-by: Claude Code (Opus 5)
---
 .../pulsar/client/impl/PulsarClientImpl.java       |  19 +++
 .../impl/ClientAuthenticationLifecycleTest.java    | 132 +++++++++++++++++++++
 2 files changed, 151 insertions(+)

diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PulsarClientImpl.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PulsarClientImpl.java
index 38ec29f987ec..1ed978f8f8f9 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PulsarClientImpl.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/PulsarClientImpl.java
@@ -1410,6 +1410,19 @@ public class PulsarClientImpl implements PulsarClient {
                 memoryLimitController.deregisterTrigger(memoryLimitTrigger);
             }
 
+            if (conf != null && conf.getV5Authentication() != null) {
+                // PIP-478: a v5-native plugin configured through the v5 builder lives only in this slot —
+                // the v4 slot still holds AuthenticationDisabled — so closing the v4 slot alone would leak
+                // whatever it holds open. Closing is safe for the other cases too: a body handed over by a
+                // built-in shim owns nothing, and a bridged adapter created for an already-started plugin
+                // deliberately leaves that plugin to its owner, which is the v4 close below.
+                try {
+                    conf.getV5Authentication().close();
+                } catch (Throwable t) {
+                    log.warn().exception(t).log("Failed to close v5 authentication");
+                    throwable = t;
+                }
+            }
             if (conf != null && conf.getAuthentication() != null) {
                 try {
                     conf.getAuthentication().close();
@@ -1547,6 +1560,12 @@ public class PulsarClientImpl implements PulsarClient {
         // authentication and does not depend on the auth being started.
         rebuildClientTlsFactory();
         conf.getAuthentication().start();
+        // PIP-478: the client drives the v5 model, so the swap is not complete until what it drives has been
+        // re-resolved. Without this the previous body and driver survive in the configuration and every new
+        // connection keeps presenting the OLD credential — from a plugin this method has just closed.
+        conf.setV5Authentication(null);
+        conf.setV5AuthenticationDriver(null);
+        resolveV5Authentication();
     }
 
     public void updateTlsTrustCertsFilePath(String tlsTrustCertsFilePath) {
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientAuthenticationLifecycleTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientAuthenticationLifecycleTest.java
new file mode 100644
index 000000000000..29e948e10413
--- /dev/null
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientAuthenticationLifecycleTest.java
@@ -0,0 +1,132 @@
+/*
+ * 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;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.assertj.core.api.Assertions.assertThat;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.pulsar.client.api.PulsarClient;
+import org.apache.pulsar.client.api.v5.auth.AuthenticationCallContext;
+import org.apache.pulsar.client.api.v5.auth.AuthenticationInitContext;
+import org.apache.pulsar.client.api.v5.auth.BinaryAuthData;
+import org.apache.pulsar.client.api.v5.auth.HttpAuthCallContext;
+import org.apache.pulsar.client.api.v5.auth.HttpAuthHeaders;
+import org.apache.pulsar.client.api.v5.auth.SinglePassAuthentication;
+import org.apache.pulsar.client.impl.auth.AuthenticationToken;
+import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
+import org.testng.annotations.Test;
+
+/**
+ * PIP-478: the client drives a v5 {@code Authentication}, so the v5 slot — not only the v4 one — has to
+ * follow the client's lifecycle.
+ *
+ * <p>Both invariants below are invisible from the v4 slot, which is why they need their own coverage: the
+ * v4 slot is updated and closed correctly in each case while the authentication the client actually drives
+ * is not.
+ */
+public class ClientAuthenticationLifecycleTest {
+
+    /**
+     * A cluster failover swaps the client's authentication at runtime ({@code AutoClusterFailover} /
+     * {@code ControlledClusterFailover}). The credential the client presents must follow the swap.
+     */
+    @Test
+    public void swappingTheAuthenticationSwapsWhatTheClientDrives() throws Exception {
+        PulsarClient client = PulsarClient.builder()
+                .serviceUrl("pulsar://localhost:6650")
+                .authentication(new AuthenticationToken("first-cluster-token"))
+                .build();
+        try {
+            ClientConfigurationData conf = ((PulsarClientImpl) client).conf;
+            assertThat(credentialOf(conf)).isEqualTo("first-cluster-token");
+
+            ((PulsarClientImpl) client).updateAuthentication(new AuthenticationToken("second-cluster-token"));
+
+            assertThat(credentialOf(conf))
+                    .as("a stale v5 body would keep presenting the old cluster's credential — from a plugin "
+                            + "updateAuthentication has already closed")
+                    .isEqualTo("second-cluster-token");
+            assertThat(conf.getV5AuthenticationDriver())
+                    .as("and the driver must be re-resolved with it, since ClientCnx memoizes it")
+                    .isNotNull();
+        } finally {
+            client.close();
+        }
+    }
+
+    /**
+     * A v5-native plugin configured through the v5 builder lives only in the v5 slot — the v4 slot still
+     * holds {@code AuthenticationDisabled} — so closing the client must reach it there.
+     */
+    @Test
+    public void closingTheClientClosesAV5NativePlugin() throws Exception {
+        CountingV5Authentication plugin = new CountingV5Authentication();
+        PulsarClient client = PulsarClient.builder()
+                .serviceUrl("pulsar://localhost:6650")
+                .build();
+        ((PulsarClientImpl) client).conf.setV5Authentication(plugin);
+
+        client.close();
+
+        assertThat(plugin.closed)
+                .as("a plugin the client drove but never closed leaks whatever it holds open")
+                .hasValue(1);
+    }
+
+    private static String credentialOf(ClientConfigurationData conf) throws Exception {
+        BinaryAuthData data = conf.getV5AuthenticationDriver()
+                .newAuthenticationExchange("broker.example.com")
+                .getAuthDataAsync()
+                .thenApply(authData -> new BinaryAuthData(authData.getBytes()))
+                .get();
+        return new String(data.bytes(), UTF_8);
+    }
+
+    /** Counts its own closing. */
+    private static final class CountingV5Authentication implements SinglePassAuthentication {
+
+        private final AtomicInteger closed = new AtomicInteger();
+
+        @Override
+        public String authMethodName() {
+            return "counting";
+        }
+
+        @Override
+        public CompletableFuture<Void> initializeAsync(AuthenticationInitContext ctx) {
+            return CompletableFuture.completedFuture(null);
+        }
+
+        @Override
+        public CompletableFuture<BinaryAuthData> getAuthDataAsync(AuthenticationCallContext ctx) {
+            return CompletableFuture.completedFuture(new BinaryAuthData(new byte[0]));
+        }
+
+        @Override
+        public CompletableFuture<HttpAuthHeaders> getHttpHeadersAsync(HttpAuthCallContext ctx) {
+            return CompletableFuture.completedFuture(HttpAuthHeaders.of(java.util.Map.of()));
+        }
+
+        @Override
+        public void close() {
+            closed.incrementAndGet();
+        }
+    }
+}