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:53 UTC

(pulsar) branch lh-pip-478-v5-native-auth-v2 created (now 3b7349f4befe)

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

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


      at 3b7349f4befe [fix][client] PIP-478: carry the v5 authentication through swap and close

This branch includes the following new commits:

     new f67d696c79fe [improve][client] PIP-478: give the v5 client a native "none" authentication
     new 721be36355ca [improve][client] PIP-478: drive the v5 authentication model natively in the client
     new 3ea0bdbe1a56 [fix][client] PIP-478: give a bridged v4 plugin an executor when no client owns it
     new 1a76f4f80e53 [fix][client] PIP-478: confine the fallback executor to the v4 bridge
     new 3b7349f4befe [fix][client] PIP-478: carry the v5 authentication through swap and close

The 5 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



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

Posted by lh...@apache.org.
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();
+        }
+    }
+}


(pulsar) 04/05: [fix][client] PIP-478: confine the fallback executor to the v4 bridge

Posted by lh...@apache.org.
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 1a76f4f80e536a06655ffb35afb530e27ec3d9b3
Author: Lari Hotari <lh...@apache.org>
AuthorDate: Wed Aug 12 21:37:06 2026 +0300

    [fix][client] PIP-478: confine the fallback executor to the v4 bridge
    
    The previous commit handed the shared blocking executor to every plugin through the init
    context, which changed the built-in bodies too: a token the client already holds in memory
    started resolving on a worker thread instead of inline, so the connect continuation
    stopped running synchronously (ClientCnxAsyncAuthTest.refreshRepublishesCredentialWithout
    Disconnect). Off-loading buys a native body nothing and costs a thread hop per connect.
    
    Hand it only to the component that must off-load. The init context reports no executor when
    no client services are bound, and LegacyV4AuthenticationAdapter borrows the shared pool at
    the point of use.
    
    That also restores a distinction the previous commit collapsed, which
    LegacyV4AuthenticationAdapterTest.capabilityMethodBeforeInitializationFailsFast pins: being
    used before initializeAsync() has run is not the same as being initialized without an
    executor. In the first case the wrapped plugin has not been configured or started, so there
    is nothing valid to call and it still fails fast; only the second falls back.
    
    Assisted-by: Claude Code (Opus 5)
---
 .../auth/v5/LegacyV4AuthenticationAdapter.java     | 22 +++++++++++++++-------
 .../pulsar/client/impl/auth/v5/V5AuthContexts.java | 21 +++++++++++++++++----
 2 files changed, 32 insertions(+), 11 deletions(-)

diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/LegacyV4AuthenticationAdapter.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/LegacyV4AuthenticationAdapter.java
index c45282b2cab4..7d477da3f672 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/LegacyV4AuthenticationAdapter.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/LegacyV4AuthenticationAdapter.java
@@ -230,9 +230,11 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
      * Offload a (potentially blocking) v4 call to the dedicated blocking executor captured at
      * initialization, translating v4 authentication exceptions into the matching v5 subtype.
      *
-     * <p>There is deliberately no inline fallback: if the adapter has not been initialized (no blocking
-     * executor available), the returned future fails with {@link IllegalStateException} rather than
-     * running the v4 call on the caller thread (PIP-478 offload discipline).
+     * <p>There is deliberately no <em>inline</em> fallback: the caller thread is a Netty event loop, and
+     * running a v4 plugin's credential I/O there is the stall PIP-478 exists to remove. When no
+     * client-owned executor is bound — a connection opened outside a {@code PulsarClient}, such as the
+     * proxy's broker connections — the work goes to {@link V5AuthContexts#sharedBlockingExecutor()}
+     * rather than failing, since refusing would reject connections the v4 client accepted.
      *
      * @param supplier the blocking work
      * @param <T> the result type
@@ -240,12 +242,18 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
      */
     protected <T> CompletableFuture<T> supplyOffloaded(ThrowingSupplier<T> supplier) {
         AuthenticationInitContext ctx = this.initContext;
-        Executor executor = ctx == null ? null : ctx.blockingExecutor();
-        if (executor == null) {
+        if (ctx == null) {
+            // Not initialized yet: the wrapped plugin has not been configured or started, so there is
+            // nothing valid to call. This is a different situation from "initialized, but the caller owns
+            // no executor" below, and it still fails fast.
             return CompletableFuture.failedFuture(new IllegalStateException(
                     "Legacy v4 authentication adapter " + getClass().getName() + " was used before "
-                            + "initializeAsync() completed (no blocking executor available); v4 plugin "
-                            + "calls must run on the blocking executor, never inline (PIP-478)"));
+                            + "initializeAsync() completed; v4 plugin calls must run on the blocking "
+                            + "executor, never inline (PIP-478)"));
+        }
+        Executor executor = ctx.blockingExecutor();
+        if (executor == null) {
+            executor = V5AuthContexts.sharedBlockingExecutor();
         }
         CompletableFuture<T> future = new CompletableFuture<>();
         executor.execute(() -> {
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5AuthContexts.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5AuthContexts.java
index 4653267af74d..0b385ab98c99 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5AuthContexts.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5AuthContexts.java
@@ -46,8 +46,8 @@ import org.apache.pulsar.http.PulsarHttpClientFactory;
  * — so a credential-fetching body (OAuth2, Athenz) can off-load its blocking fetch onto the blocking
  * executor instead of running it on the Netty event loop. When no services are bound (a connection opened
  * outside a {@code PulsarClient} — the proxy's broker connections, embedders, tests), the context reports
- * no HTTP client factory or scheduler, but still supplies a shared blocking executor: the offload
- * discipline holds on every path, since the caller thread there is a Netty event loop too.
+ * no services at all, and a body that holds its credential in memory simply resolves inline. The one
+ * component that cannot do that is the legacy v4 bridge, which borrows {@link #sharedBlockingExecutor()}.
  */
 public final class V5AuthContexts {
 
@@ -70,6 +70,16 @@ public final class V5AuthContexts {
                 : new BoundInitContext(services);
     }
 
+    /**
+     * The blocking executor of last resort, for work that must not run on the calling thread when no
+     * client-owned executor is available. See {@link SharedBlockingExecutor}.
+     *
+     * @return the shared blocking executor
+     */
+    static Executor sharedBlockingExecutor() {
+        return SharedBlockingExecutor.INSTANCE;
+    }
+
     /**
      * @param brokerHost the broker host
      * @return a new binary-protocol call context with a fresh state slot
@@ -117,10 +127,13 @@ public final class V5AuthContexts {
      * exactly the stall PIP-478 exists to remove, and refusing to run at all would break connections v4
      * made fine, so the library keeps one shared pool for them.
      *
+     * <p>Only the v4 bridge borrows it. A v5-native body is handed no executor at all when none is bound,
+     * so a credential it already holds in memory still resolves inline, without a thread hop per connect.
+     *
      * <p>It costs nothing when unused: no core threads, daemon threads that retire after a minute of idle.
      * Held in a holder class so it is created on first use rather than on class load.
      */
-    private static final class SharedBlockingExecutor {
+    static final class SharedBlockingExecutor {
         static final Executor INSTANCE = create();
 
         private static Executor create() {
@@ -153,7 +166,7 @@ public final class V5AuthContexts {
 
         @Override
         public Executor blockingExecutor() {
-            return SharedBlockingExecutor.INSTANCE;
+            return null;
         }
 
         @Override


(pulsar) 03/05: [fix][client] PIP-478: give a bridged v4 plugin an executor when no client owns it

Posted by lh...@apache.org.
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 3ea0bdbe1a56c8a121f07b2b3671571f93fac9be
Author: Lari Hotari <lh...@apache.org>
AuthorDate: Wed Aug 12 21:17:40 2026 +0300

    [fix][client] PIP-478: give a bridged v4 plugin an executor when no client owns it
    
    Driving the v5 model natively means every legacy v4 plugin now goes through
    LegacyV4AuthenticationAdapter, which by design refuses to run a v4 call inline — the
    caller thread is a Netty event loop, and running credential I/O there is the stall
    PIP-478 exists to remove. It off-loads to the executor its init context supplies.
    
    Not every connection is opened by a PulsarClient, though. The proxy builds broker
    connections straight from a ClientConfigurationData, and so do embedders and tests, so
    no client-owned executor is bound and the context supplied none: the adapter then failed
    every call with "used before initializeAsync() completed". That refuses connections v4
    made fine (ProxyAuthenticationTest, ProxySaslAuthenticationTest), and it only surfaced on
    the proxy because the built-in bodies never off-load.
    
    Supply a shared blocking executor for those callers instead. Running inline was the other
    option and is the wrong one: on that path the caller thread is an event loop too.
    The pool costs nothing when unused — no core threads, daemon threads retiring after a
    minute idle — and is created on first use.
    
    Verified by mutation: reverting this fails ProxySaslAuthenticationTest.testAuthentication
    with the same IllegalStateException CI reported.
    
    Assisted-by: Claude Code (Opus 5)
---
 .../pulsar/client/impl/auth/v5/V5AuthContexts.java | 39 +++++++++++++++++++---
 1 file changed, 35 insertions(+), 4 deletions(-)

diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5AuthContexts.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5AuthContexts.java
index 1e3088768332..4653267af74d 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5AuthContexts.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5AuthContexts.java
@@ -25,6 +25,9 @@ import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.Executor;
 import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
 import java.util.function.Supplier;
 import org.apache.pulsar.client.api.v5.auth.AuthenticationCallContext;
 import org.apache.pulsar.client.api.v5.auth.AuthenticationInitContext;
@@ -41,9 +44,10 @@ import org.apache.pulsar.http.PulsarHttpClientFactory;
  * HTTP client factory, client instance id) are late-bound into the init context via
  * {@link ClientAuthenticationServices}
  * — so a credential-fetching body (OAuth2, Athenz) can off-load its blocking fetch onto the blocking
- * executor instead of running it on the Netty event loop. When no services are bound (a plugin used
- * outside a client), the context degrades to {@code null} services and the body falls back to inline
- * computation.
+ * executor instead of running it on the Netty event loop. When no services are bound (a connection opened
+ * outside a {@code PulsarClient} — the proxy's broker connections, embedders, tests), the context reports
+ * no HTTP client factory or scheduler, but still supplies a shared blocking executor: the offload
+ * discipline holds on every path, since the caller thread there is a Netty event loop too.
  */
 public final class V5AuthContexts {
 
@@ -103,6 +107,33 @@ public final class V5AuthContexts {
         }
     }
 
+    /**
+     * The blocking executor used when no client services are bound.
+     *
+     * <p>Not every connection is opened by a {@code PulsarClient}: the proxy builds broker connections
+     * straight from a configuration, and so do embedders and tests. Those callers have no client-owned
+     * executor to lend, but a bridged v4 plugin still must not run its credential call on the caller
+     * thread — which on that path is a Netty event loop. Falling back to running inline would reintroduce
+     * exactly the stall PIP-478 exists to remove, and refusing to run at all would break connections v4
+     * made fine, so the library keeps one shared pool for them.
+     *
+     * <p>It costs nothing when unused: no core threads, daemon threads that retire after a minute of idle.
+     * Held in a holder class so it is created on first use rather than on class load.
+     */
+    private static final class SharedBlockingExecutor {
+        static final Executor INSTANCE = create();
+
+        private static Executor create() {
+            ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 8, 60L, TimeUnit.SECONDS,
+                    new SynchronousQueue<>(), runnable -> {
+                        Thread thread = new Thread(runnable, "pulsar-auth-blocking-shared");
+                        thread.setDaemon(true);
+                        return thread;
+                    });
+            return executor;
+        }
+    }
+
     private static final class InitContext implements AuthenticationInitContext {
         private final String clientInstanceId;
 
@@ -122,7 +153,7 @@ public final class V5AuthContexts {
 
         @Override
         public Executor blockingExecutor() {
-            return null;
+            return SharedBlockingExecutor.INSTANCE;
         }
 
         @Override


(pulsar) 01/05: [improve][client] PIP-478: give the v5 client a native "none" authentication

Posted by lh...@apache.org.
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 f67d696c79fe81b90d7154be99dfee1b93a5ae48
Author: Lari Hotari <lh...@apache.org>
AuthorDate: Wed Aug 12 20:12:39 2026 +0300

    [improve][client] PIP-478: give the v5 client a native "none" authentication
    
    The v5 SPI has no body for the unauthenticated case, and the generic v4->v5 bridge
    cannot stand in for one. LegacyV4CredentialAdapter advertises BinaryAuthDataProvider
    only when the wrapped plugin actually produced command data, and the v4
    AuthenticationDisabled produces none (AuthenticationDataNull is empty), so a bridged
    no-auth plugin exposes no binary capability at all — indistinguishable from a plugin
    that cannot authenticate a binary connection.
    
    That is currently masked by an explicit escape in PulsarClientBuilderV5, which drives
    AuthenticationDisabled raw on the v4 client. Once the client drives the v5 model
    natively that escape goes away, and the default unauthenticated deployment would stop
    connecting. Resolve the "none" method name to a new v5-native NoAuthentication instead,
    alongside the existing "tls" and "sasl" branches: side-effect-free selection, no v4
    probe, no executor hop on the unauthenticated hot path.
    
    Also return the v5-native token body from the v5 AuthenticationFactory rather than
    bridging AuthenticationToken backwards through the legacy adapter — the offload the
    bridge performs exists for plugins that do credential I/O, which an in-memory token
    does not.
    
    Verified by mutation: removing the "none" branch fails both
    V5AuthenticationLoaderTest.blankClassNameLoadsDisabledAuthentication and
    theUnauthenticatedCaseCanDriveABinaryConnection.
    
    Assisted-by: Claude Code (Opus 5)
---
 .../client/impl/v5/PulsarClientProviderV5.java     | 11 +--
 .../client/impl/v5/V5AuthenticationLoaderTest.java | 31 ++++++++-
 .../auth/v5/LegacyV4AuthenticationAdapter.java     | 14 +++-
 .../client/impl/auth/v5/NoAuthentication.java      | 78 ++++++++++++++++++++++
 4 files changed, 126 insertions(+), 8 deletions(-)

diff --git a/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/PulsarClientProviderV5.java b/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/PulsarClientProviderV5.java
index 96c8c3361c84..eb05fc8dea15 100644
--- a/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/PulsarClientProviderV5.java
+++ b/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/PulsarClientProviderV5.java
@@ -29,9 +29,8 @@ import org.apache.pulsar.client.api.v5.auth.Authentication;
 import org.apache.pulsar.client.api.v5.internal.PulsarClientProvider;
 import org.apache.pulsar.client.api.v5.schema.GenericRecord;
 import org.apache.pulsar.client.api.v5.schema.Schema;
-import org.apache.pulsar.client.impl.auth.AuthenticationToken;
-import org.apache.pulsar.client.impl.auth.v5.LegacyV4AuthenticationAdapter;
 import org.apache.pulsar.client.impl.auth.v5.TlsAuthentication;
+import org.apache.pulsar.client.impl.auth.v5.TokenAuthenticationV5;
 import org.apache.pulsar.client.impl.auth.v5.V5AuthenticationLoader;
 
 /**
@@ -170,14 +169,18 @@ public final class PulsarClientProviderV5 implements PulsarClientProvider {
 
     // --- Authentication ---
 
+    // The v5 factory returns the v5-native token body directly rather than bridging the v4
+    // AuthenticationToken back through LegacyV4AuthenticationAdapter (PIP-478). Both serve the same
+    // credential, but the bridge would route a purely in-memory token through the blocking executor on
+    // every connect — the offload exists for plugins that perform credential I/O, which this one does not.
     @Override
     public Authentication authenticationToken(String token) {
-        return LegacyV4AuthenticationAdapter.wrap(new AuthenticationToken(token));
+        return new TokenAuthenticationV5(new TokenAuthenticationV5.LiteralTokenSupplier(token));
     }
 
     @Override
     public Authentication authenticationToken(Supplier<String> tokenSupplier) {
-        return LegacyV4AuthenticationAdapter.wrap(new AuthenticationToken(tokenSupplier));
+        return new TokenAuthenticationV5(tokenSupplier);
     }
 
     @Override
diff --git a/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/V5AuthenticationLoaderTest.java b/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/V5AuthenticationLoaderTest.java
index d9eb73e9b01b..bbcd75af1276 100644
--- a/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/V5AuthenticationLoaderTest.java
+++ b/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/V5AuthenticationLoaderTest.java
@@ -27,10 +27,12 @@ import org.apache.pulsar.client.api.v5.auth.Authentication;
 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.BinaryAuthDataProvider;
 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.v5.LegacyV4AuthenticationAdapter;
+import org.apache.pulsar.client.impl.auth.v5.NoAuthentication;
 import org.apache.pulsar.client.impl.auth.v5.V5AuthenticationLoader;
 import org.apache.pulsar.client.impl.v5.auth.V5ToV4AuthenticationAdapter;
 import org.testng.annotations.Test;
@@ -163,9 +165,32 @@ public class V5AuthenticationLoaderTest {
     @Test
     public void blankClassNameLoadsDisabledAuthentication() throws Exception {
         Authentication auth = V5AuthenticationLoader.create("", "");
-        // Blank routes to the v4 path, which yields AuthenticationDisabled bridged through the adapter.
+        // Blank routes to the v4 path, which yields AuthenticationDisabled — and the "none" method name
+        // resolves to the v5-native NoAuthentication rather than a bridged v4 plugin (PIP-478).
+        assertThat(auth).isInstanceOf(NoAuthentication.class);
         assertThat(LegacyV4AuthenticationAdapter.unwrapV4(auth))
-                .get()
-                .isInstanceOf(org.apache.pulsar.client.impl.auth.AuthenticationDisabled.class);
+                .as("the v5-native no-auth body wraps nothing; there is no v4 plugin left to recover")
+                .isEmpty();
+    }
+
+    /**
+     * The unauthenticated case must be able to authenticate a binary connection. It is the only built-in
+     * whose v4 form carries neither command data nor HTTP data, so the generic bridge — which advertises
+     * {@link BinaryAuthDataProvider} only for a plugin that actually produced command data — resolves it to
+     * a plugin with no binary capability at all. Driving that plugin natively fails the connection outright,
+     * so "none" is routed to the v5-native body instead.
+     */
+    @Test
+    public void theUnauthenticatedCaseCanDriveABinaryConnection() throws Exception {
+        Authentication auth = V5AuthenticationLoader.create("", "");
+
+        assertThat(auth.capability(BinaryAuthDataProvider.class))
+                .as("a natively-driven client with no auth configured must still be able to connect")
+                .isPresent();
+        BinaryAuthDataProvider binary = auth.capability(BinaryAuthDataProvider.class).orElseThrow();
+        assertThat(binary.authMethodName()).isEqualTo("none");
+        assertThat(binary.getAuthDataAsync(null).get().bytes())
+                .as("and it carries an empty credential")
+                .isEmpty();
     }
 }
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/LegacyV4AuthenticationAdapter.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/LegacyV4AuthenticationAdapter.java
index 15a9a4086c42..c849f1fbfff4 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/LegacyV4AuthenticationAdapter.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/LegacyV4AuthenticationAdapter.java
@@ -93,14 +93,26 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
      * {@code hasDataForTls()} plugin's material into the client TLS configuration is a builder-time
      * concern handled by the client (PIP-478).
      *
+     * <p>The method name {@code "none"} is resolved to the built-in {@link NoAuthentication} rather than
+     * to a bridging adapter, because "no credential" is the one case the generic bridge cannot represent:
+     * {@link LegacyV4CredentialAdapter} advertises {@link BinaryAuthDataProvider} only for a plugin that
+     * actually produced command data, and the v4 {@code AuthenticationDisabled} produces none — so a
+     * bridged no-auth plugin is indistinguishable from one that cannot authenticate a binary connection at
+     * all. Declaring {@code auth_method_name=none} is itself the statement that no credential is carried,
+     * so nothing is lost by not consulting the wrapped plugin.
+     *
      * @param v4 the v4 authentication plugin to wrap
-     * @return a v5 {@link Authentication} that delegates to the v4 plugin
+     * @return a v5 {@link Authentication} that delegates to the v4 plugin, or a built-in v5-native body
+     *         for the method names that have one
      */
     public static Authentication wrap(org.apache.pulsar.client.api.Authentication v4) {
         if (v4 == null) {
             throw new IllegalArgumentException("v4 authentication must not be null");
         }
         String methodName = v4.getAuthMethodName();
+        if (NoAuthentication.DEFAULT_AUTH_METHOD_NAME.equalsIgnoreCase(methodName)) {
+            return NoAuthentication.INSTANCE;
+        }
         if (TlsAuthentication.DEFAULT_AUTH_METHOD_NAME.equalsIgnoreCase(methodName)) {
             return new LegacyV4TlsAdapter(v4);
         }
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/NoAuthentication.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/NoAuthentication.java
new file mode 100644
index 000000000000..00326831e54e
--- /dev/null
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/NoAuthentication.java
@@ -0,0 +1,78 @@
+/*
+ * 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.v5;
+
+import java.util.concurrent.CompletableFuture;
+import org.apache.pulsar.client.api.v5.auth.Authentication;
+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.BinaryAuthDataProvider;
+
+/**
+ * Built-in "no authentication" plugin for the v5 client (PIP-478) — the v5-native counterpart of the v4
+ * {@code AuthenticationDisabled}. It declares the {@code "none"} authentication method name and carries an
+ * empty binary payload.
+ *
+ * <p>This is the v5 body for the default, unauthenticated deployment, and it exists because the generic
+ * v4&rarr;v5 bridge cannot serve that case. {@link LegacyV4AuthenticationAdapter}'s credential subtype
+ * advertises the binary capability only when the wrapped plugin actually produces command data, and
+ * {@code AuthenticationDisabled.getAuthData()} returns an empty {@code AuthenticationDataNull}. A bridged
+ * no-auth plugin therefore exposes no {@link BinaryAuthDataProvider} at all, which is indistinguishable
+ * from a plugin that cannot authenticate a binary connection. Routing {@code "none"} here keeps the
+ * unauthenticated hot path both drivable and allocation-free: no executor hop, no v4 probe, no credential
+ * I/O — matching PIP-478's requirement that the default no-auth path not be routed through the blocking
+ * executor machinery.
+ *
+ * <p>Only the binary capability is declared. On the HTTP transport "no credential" is expressed by sending
+ * no authentication headers at all, which is what omitting {@code HttpAuthHeadersProvider} means.
+ */
+public class NoAuthentication implements Authentication, BinaryAuthDataProvider {
+
+    /**
+     * The authentication method name for a connection that carries no credential.
+     */
+    public static final String DEFAULT_AUTH_METHOD_NAME = "none";
+
+    /** The shared instance; this plugin is stateless. */
+    public static final NoAuthentication INSTANCE = new NoAuthentication();
+
+    private static final BinaryAuthData EMPTY = new BinaryAuthData(new byte[0]);
+
+    /**
+     * Create a no-op authentication plugin advertising the {@code "none"} method name.
+     */
+    public NoAuthentication() {
+    }
+
+    @Override
+    public CompletableFuture<Void> initializeAsync(AuthenticationInitContext initContext) {
+        return CompletableFuture.completedFuture(null);
+    }
+
+    @Override
+    public String authMethodName() {
+        return DEFAULT_AUTH_METHOD_NAME;
+    }
+
+    @Override
+    public CompletableFuture<BinaryAuthData> getAuthDataAsync(AuthenticationCallContext callContext) {
+        return CompletableFuture.completedFuture(EMPTY);
+    }
+}


(pulsar) 02/05: [improve][client] PIP-478: drive the v5 authentication model natively in the client

Posted by lh...@apache.org.
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 721be36355ca5daa79d9940fd6210bec91509340
Author: Lari Hotari <lh...@apache.org>
AuthorDate: Wed Aug 12 20:54:12 2026 +0300

    [improve][client] PIP-478: drive the v5 authentication model natively in the client
    
    The client held a v4 Authentication and wrapped a v5 plugin backwards into it. Invert
    that: the client resolves exactly one v5 Authentication and drives every binary
    connection from it, and the only remaining bridge is v4 -> v5. There is no synchronous
    plugin path left on the connect/challenge routes, so credential I/O can no longer land
    on a Netty event loop by accident.
    
    The built-in shims (token, basic, OAuth2) hand over the v5-native body they already own
    through a new V5AuthenticationProvider seam, instead of implementing
    AsyncAuthenticationDriver; anything else is wrapped by LegacyV4AuthenticationAdapter.
    V5ToV4AuthenticationAdapter, SimpleAuthInitContext and SimpleAuthCallContext are deleted
    — the inversion removes more than it adds.
    
    conf.authentication deliberately stays v4-typed and populated with the raw plugin: every
    auth-provided TLS-material fold keys off the concrete v4 type, and the v5 SPI has no TLS
    carrier. Emptying it would silently drop the client certificate and surface only as a 401.
    The v5 body goes in a new transient slot beside it.
    
    Three defects had to be fixed for the inversion to be behaviour-preserving, each found by
    an existing test rather than by inspection:
    
    - The bridge selected its adapter by auth-method name, so only a plugin literally called
      "sasl" got a challenge handler. Every custom challenge/response plugin lost multi-round
      auth (MutualAuthenticationTest). Any v4 plugin that can serve the binary transport can
      answer a challenge on it, so the credential adapter now advertises both.
    - The bridge served the initial credential from getCommandData(), while v4's ClientCnx
      used authenticate(INIT_AUTH_DATA) — whose default implementation returns getCommandData(),
      so it is correct for single-pass plugins and also correct for challenge plugins that
      only produce their first frame that way.
    - The binary capability was gated on a probe, so a plugin reporting no command data could
      not connect at all — but v4 connected it fine, sending whatever authenticate() returned,
      empty included (TlsProducerConsumerTest.testTlsWithFakeAuthentication). The probe now
      decides only the HTTP capability, which has no universal fallback.
    
    Plugin lifecycle now has exactly one owner. The client starts and closes the v4 instance
    in conf, so the adapter that drives it is created in an already-started form and does not
    re-run configure/start/close — AuthenticationOAuth2.start() initializes the token flow,
    so a second start() is not a harmless no-op.
    
    Verified: :pulsar-client-original:test, :pulsar-client-v5:test, :pulsar-proxy ProxyTest +
    AutoCloseUselessClientConProxyTest, :pulsar-broker TlsProducerConsumerTest +
    V5TlsProducerConsumerTest + MutualAuthenticationTest, sanityCheck and quickCheck.
    
    Assisted-by: Claude Code (Opus 5)
---
 .../service/OneWayReplicatorDeduplicationTest.java |   2 +-
 .../api/v5/internal/V5AuthenticationProvider.java  |  56 ++++
 .../api/internal/AsyncAuthenticationDriver.java    |  12 +
 .../client/impl/v5/PulsarClientBuilderV5.java      |  16 +-
 .../client/impl/v5/auth/SimpleAuthCallContext.java |  57 ----
 .../client/impl/v5/auth/SimpleAuthInitContext.java |  80 -----
 .../impl/v5/auth/V5ToV4AuthenticationAdapter.java  | 351 ---------------------
 .../pulsar/client/impl/v5/auth/package-info.java   |  29 --
 .../v5/CredentialOffloadThroughV5BuilderTest.java  |  17 +-
 .../client/impl/v5/V5AuthenticationLoaderTest.java |  18 +-
 .../v5/auth/V5ToV4AuthenticationAdapterTest.java   | 251 ---------------
 .../org/apache/pulsar/client/impl/ClientCnx.java   |  88 ++++--
 .../pulsar/client/impl/PulsarClientImpl.java       |  33 +-
 .../client/impl/auth/AuthenticationBasic.java      |  29 +-
 .../client/impl/auth/AuthenticationToken.java      |  30 +-
 .../impl/auth/oauth2/AuthenticationOAuth2.java     |  21 +-
 .../client/impl/auth/v5/BasicAuthenticationV5.java |  21 +-
 .../impl/auth/v5/BinaryAuthenticationExchange.java |  13 +
 .../auth/v5/LegacyV4AuthenticationAdapter.java     | 130 ++++++--
 .../impl/auth/v5/V5AuthenticationLoader.java       |  18 ++
 .../impl/auth/v5/V5BinaryAuthenticationDriver.java |   5 +
 .../client/impl/conf/ClientConfigurationData.java  |  21 ++
 .../pulsar/client/impl/ClientCnxAsyncAuthTest.java |  25 +-
 .../apache/pulsar/proxy/server/ProxyClientCnx.java |   2 +-
 .../org/apache/pulsar/proxy/server/ProxyTest.java  |   2 +-
 25 files changed, 413 insertions(+), 914 deletions(-)

diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorDeduplicationTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorDeduplicationTest.java
index 854bedb9392b..04dc4e5ceacd 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorDeduplicationTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorDeduplicationTest.java
@@ -325,7 +325,7 @@ public class OneWayReplicatorDeduplicationTest extends OneWayReplicatorTestBase
                     if (supportsReplDedupByLidAndEid) {
                         return super.buildConnectCommand(authData);
                     }
-                    BaseCommand cmd = Commands.newConnectWithoutSerialize(authentication.getAuthMethodName(), authData,
+                    BaseCommand cmd = Commands.newConnectWithoutSerialize(authMethodName(), authData,
                             this.protocolVersion, clientVersion, proxyToTargetBrokerAddress,
                             null, null, null, null, null);
                     cmd.getConnect().getFeatureFlags().setSupportsReplDedupByLidAndEid(false);
diff --git a/pulsar-client-api-v5/src/main/java/org/apache/pulsar/client/api/v5/internal/V5AuthenticationProvider.java b/pulsar-client-api-v5/src/main/java/org/apache/pulsar/client/api/v5/internal/V5AuthenticationProvider.java
new file mode 100644
index 000000000000..997a42745fd0
--- /dev/null
+++ b/pulsar-client-api-v5/src/main/java/org/apache/pulsar/client/api/v5/internal/V5AuthenticationProvider.java
@@ -0,0 +1,56 @@
+/*
+ * 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.api.v5.internal;
+
+import org.apache.pulsar.client.api.v5.auth.Authentication;
+
+/**
+ * Implemented by a legacy v4 {@code org.apache.pulsar.client.api.Authentication} that owns a v5-native
+ * body, so the client can drive the v5 body directly instead of bridging the v4 plugin (PIP-478).
+ *
+ * <p>The client drives the v5 authentication model natively: it resolves exactly one v5
+ * {@link Authentication} per client and drives every transport from it. A v4 plugin therefore has to be
+ * turned into a v5 one, and there are two ways to do that. The built-in credential shims (token, basic,
+ * OAuth2, Athenz, SASL) already <em>have</em> a v5-native body — the v4 class is a thin compatibility
+ * surface over it — so they hand that body over through this interface. Everything else is wrapped by
+ * {@code LegacyV4AuthenticationAdapter}, which re-expresses the v4 surface as v5 capabilities and
+ * off-loads every v4 call to the client's blocking executor.
+ *
+ * <p>Handing over the native body is not merely tidier: the generic bridge exists to make an
+ * <em>unknown</em> plugin safe, and it pays for that with an executor hop per call and a start-time probe
+ * of the v4 plugin's capabilities. A built-in whose body is already asynchronous and non-blocking needs
+ * neither.
+ *
+ * <p>The body is requested once per client, during client construction, and must be cheap to produce —
+ * credential acquisition belongs in the body's own asynchronous methods, not here. Implementations must
+ * return a body that reads any mutable configuration (a rotated token, for instance) at call time rather
+ * than capturing it, since the same body serves the whole client lifetime.
+ *
+ * <p>The {@code .internal.} subpackage signals "stable internal" — application code should not implement
+ * this interface; it is observed by the framework.
+ */
+public interface V5AuthenticationProvider {
+
+    /**
+     * The v5-native authentication body this v4 plugin delegates to.
+     *
+     * @return the v5 authentication to drive; never {@code null}
+     */
+    Authentication v5Authentication();
+}
diff --git a/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/internal/AsyncAuthenticationDriver.java b/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/internal/AsyncAuthenticationDriver.java
index f903546fe64a..6038a46d0850 100644
--- a/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/internal/AsyncAuthenticationDriver.java
+++ b/pulsar-client-api/src/main/java/org/apache/pulsar/client/api/internal/AsyncAuthenticationDriver.java
@@ -79,6 +79,18 @@ public interface AsyncAuthenticationDriver {
          */
         CompletableFuture<AuthData> getAuthDataAsync();
 
+        /**
+         * The authentication method name to declare on the wire for this exchange's rounds.
+         *
+         * <p>Valid only once a round of this exchange has completed: the name is a property of the
+         * credential the plugin actually served, and a bridged legacy plugin does not know which
+         * capabilities it can serve until its initialization has run. Callers read it when building the
+         * frame that carries the auth data they just resolved, never before.
+         *
+         * @return the auth method name (for example {@code token}, {@code tls}, {@code none})
+         */
+        String authMethodName();
+
         /**
          * Asynchronously compute the response to a broker {@code CommandAuthChallenge} — an ordinary
          * challenge round (SASL multi-round or custom challenge/response), answered from this exchange's
diff --git a/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/PulsarClientBuilderV5.java b/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/PulsarClientBuilderV5.java
index 9117ea2b11c4..b9e3e4e02f4e 100644
--- a/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/PulsarClientBuilderV5.java
+++ b/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/PulsarClientBuilderV5.java
@@ -38,7 +38,6 @@ import org.apache.pulsar.client.impl.auth.AuthenticationTls;
 import org.apache.pulsar.client.impl.auth.v5.LegacyV4AuthenticationAdapter;
 import org.apache.pulsar.client.impl.auth.v5.V5AuthenticationLoader;
 import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
-import org.apache.pulsar.client.impl.v5.auth.V5ToV4AuthenticationAdapter;
 import org.apache.pulsar.tls.PulsarTlsFactory;
 import org.apache.pulsar.tls.TlsPolicy;
 import org.apache.pulsar.tls.TlsPurpose;
@@ -133,10 +132,17 @@ final class PulsarClientBuilderV5 implements PulsarClientBuilder {
         }
         org.apache.pulsar.client.api.Authentication bridgedV4 =
                 LegacyV4AuthenticationAdapter.unwrapV4(v5Authentication).orElse(null);
-        boolean runRaw = bridgedV4 != null && resolveBridgedV4(bridgedV4);
-        conf.setAuthentication(runRaw
-                ? bridgedV4
-                : new V5ToV4AuthenticationAdapter(v5Authentication));
+        if (bridgedV4 != null) {
+            // A legacy v4 plugin configured through the v5 builder. Fold any TLS material it carries into
+            // the client's policy map, then hand the raw plugin to the v4 slot: that slot stays the one the
+            // client starts, closes, and reads for TLS material and the OAuth2 IdP trust. The v5 body the
+            // client drives is resolved from it during client construction, so the plugin's lifecycle has
+            // exactly one owner.
+            resolveBridgedV4(bridgedV4);
+            conf.setAuthentication(bridgedV4);
+            return;
+        }
+        conf.setV5Authentication(v5Authentication);
     }
 
     /**
diff --git a/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/auth/SimpleAuthCallContext.java b/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/auth/SimpleAuthCallContext.java
deleted file mode 100644
index d94975ea3b92..000000000000
--- a/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/auth/SimpleAuthCallContext.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * 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.v5.auth;
-
-import java.util.Map;
-import java.util.Optional;
-import java.util.concurrent.ConcurrentHashMap;
-import org.apache.pulsar.client.api.v5.auth.AuthenticationCallContext;
-
-/**
- * Simple {@link AuthenticationCallContext} implementation backed by a concurrent map of typed
- * per-exchange state objects. Used by the v5&harr;v4 bridges to drive challenge/response exchanges.
- */
-class SimpleAuthCallContext implements AuthenticationCallContext {
-
-    private final String brokerHost;
-    private final Map<Class<?>, Object> state = new ConcurrentHashMap<>();
-
-    SimpleAuthCallContext(String brokerHost) {
-        this.brokerHost = brokerHost;
-    }
-
-    @Override
-    public String brokerHost() {
-        return brokerHost;
-    }
-
-    @Override
-    public <T> Optional<T> getStateObject(Class<T> clazz) {
-        return Optional.ofNullable(clazz.cast(state.get(clazz)));
-    }
-
-    @Override
-    public <T> void setStateObject(Class<T> clazz, T value) {
-        if (value == null) {
-            state.remove(clazz);
-        } else {
-            state.put(clazz, value);
-        }
-    }
-}
diff --git a/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/auth/SimpleAuthInitContext.java b/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/auth/SimpleAuthInitContext.java
deleted file mode 100644
index 55456c8257d5..000000000000
--- a/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/auth/SimpleAuthInitContext.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * 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.v5.auth;
-
-import io.opentelemetry.api.OpenTelemetry;
-import java.time.Clock;
-import java.util.concurrent.Executor;
-import java.util.concurrent.ScheduledExecutorService;
-import org.apache.pulsar.client.api.v5.auth.AuthenticationInitContext;
-import org.apache.pulsar.http.PulsarHttpClientFactory;
-
-/**
- * Simple immutable {@link AuthenticationInitContext} implementation used by the v5/v4 bridges to
- * initialize a v5 {@link org.apache.pulsar.client.api.v5.auth.Authentication} plugin.
- */
-class SimpleAuthInitContext implements AuthenticationInitContext {
-
-    private final PulsarHttpClientFactory httpClientFactory;
-    private final ScheduledExecutorService scheduler;
-    private final Executor blockingExecutor;
-    private final Clock clock;
-    private final OpenTelemetry openTelemetry;
-    private final String clientInstanceId;
-
-    SimpleAuthInitContext(PulsarHttpClientFactory httpClientFactory, ScheduledExecutorService scheduler,
-            Executor blockingExecutor, Clock clock, OpenTelemetry openTelemetry, String clientInstanceId) {
-        this.httpClientFactory = httpClientFactory;
-        this.scheduler = scheduler;
-        this.blockingExecutor = blockingExecutor;
-        this.clock = clock;
-        this.openTelemetry = openTelemetry;
-        this.clientInstanceId = clientInstanceId;
-    }
-
-    @Override
-    public PulsarHttpClientFactory httpClientFactory() {
-        return httpClientFactory;
-    }
-
-    @Override
-    public ScheduledExecutorService scheduler() {
-        return scheduler;
-    }
-
-    @Override
-    public Executor blockingExecutor() {
-        return blockingExecutor;
-    }
-
-    @Override
-    public Clock clock() {
-        return clock;
-    }
-
-    @Override
-    public OpenTelemetry openTelemetry() {
-        return openTelemetry;
-    }
-
-    @Override
-    public String clientInstanceId() {
-        return clientInstanceId;
-    }
-}
diff --git a/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/auth/V5ToV4AuthenticationAdapter.java b/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/auth/V5ToV4AuthenticationAdapter.java
deleted file mode 100644
index 8d1a6cc8e102..000000000000
--- a/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/auth/V5ToV4AuthenticationAdapter.java
+++ /dev/null
@@ -1,351 +0,0 @@
-/*
- * 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.v5.auth;
-
-import static java.nio.charset.StandardCharsets.UTF_8;
-import io.opentelemetry.api.OpenTelemetry;
-import java.io.IOException;
-import java.io.NotSerializableException;
-import java.io.ObjectOutputStream;
-import java.net.URI;
-import java.time.Clock;
-import java.util.Arrays;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ExecutionException;
-import org.apache.pulsar.client.api.AuthenticationDataProvider;
-import org.apache.pulsar.client.api.PulsarClientException;
-import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver;
-import org.apache.pulsar.client.api.v5.auth.Authentication;
-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.BinaryAuthDataProvider;
-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.HttpAuthHeadersProvider;
-import org.apache.pulsar.client.api.v5.internal.ClientAuthenticationServices;
-import org.apache.pulsar.client.api.v5.internal.ClientAuthenticationServicesAware;
-import org.apache.pulsar.client.impl.auth.v5.AuthMetrics;
-import org.apache.pulsar.client.impl.auth.v5.BinaryAuthenticationExchange;
-import org.apache.pulsar.common.api.AuthData;
-
-/**
- * Exposes a new-SPI v5 {@link Authentication} plugin through the legacy v4
- * {@link org.apache.pulsar.client.api.Authentication} interface that {@code ClientCnx} drives
- * (PIP-478).
- *
- * <p>It also implements {@link AsyncAuthenticationDriver} so that the {@code ClientCnx} carve-out
- * (PIP-478) can authenticate via the asynchronous (non event-loop-blocking) path. Both the
- * async driver and the synchronous v4 {@link #getAuthData(String)} path are exchange-scoped: one
- * {@link AsyncAuthenticationDriver.AuthenticationExchange} — and one {@link AuthenticationCallContext}
- * with its state slot — backs a single connection attempt, so a plugin's challenge/response
- * conversation state survives across all of that connection's rounds (initial data, refresh, and every
- * {@code CommandAuthChallenge}).
- *
- * <p>The per-connection routing (initial connect / refresh sentinel / challenge) and the v5→v4 exception
- * mapping are the shared {@link BinaryAuthenticationExchange} — the same implementation the built-in
- * shims' {@code V5BinaryAuthenticationDriver} uses — so the two adapters cannot drift on the normative
- * binary rules. Binary transport requires the {@link BinaryAuthDataProvider} capability (PIP-478 binary
- * routing rule 1); a wrapped v5 plugin that does not expose it fails loudly — {@link #start()} throws a
- * v4-mapped {@link PulsarClientException.UnsupportedAuthenticationException} — rather than synthesizing
- * an empty {@code "none"} credential.
- */
-// Implements the deprecated v4 Authentication SPI by design (configure(Map)).
-@SuppressWarnings("deprecation")
-public class V5ToV4AuthenticationAdapter
-        implements org.apache.pulsar.client.api.Authentication, AsyncAuthenticationDriver,
-        ClientAuthenticationServicesAware {
-
-    private static final long serialVersionUID = 1L;
-
-    private final transient Authentication v5;
-    // Late-bound by the client via bindClientAuthenticationServices(...) before start() (PIP-478);
-    // null until then (e.g. when the adapter is exercised outside a client), yielding an init context with
-    // no framework services.
-    private transient volatile ClientAuthenticationServices services;
-    // Built from the bound services' OpenTelemetry in start(); NOOP until then.
-    private transient volatile AuthMetrics authMetrics = AuthMetrics.NOOP;
-
-    /**
-     * Create an adapter that exposes a v5 authentication plugin through the v4 interface. The framework
-     * services the plugin's init context reports are late-bound by the client through
-     * {@link #bindClientAuthenticationServices} before {@link #start()}.
-     *
-     * @param v5 the v5 authentication plugin to expose
-     */
-    public V5ToV4AuthenticationAdapter(Authentication v5) {
-        this.v5 = v5;
-    }
-
-    @Override
-    public void bindClientAuthenticationServices(ClientAuthenticationServices services) {
-        this.services = services;
-    }
-
-    @Override
-    public String getAuthMethodName() {
-        return requireBinaryProvider().authMethodName();
-    }
-
-    @Override
-    public void configure(Map<String, String> authParams) {
-        v5.configure(authParams);
-    }
-
-    @Override
-    public void start() throws PulsarClientException {
-        ClientAuthenticationServices bound = this.services;
-        this.authMetrics = AuthMetrics.create(bound == null ? null : bound.openTelemetry());
-        AuthenticationInitContext initContext = bound == null
-                ? new SimpleAuthInitContext(null, null, null, Clock.systemUTC(), OpenTelemetry.noop(), null)
-                : new SimpleAuthInitContext(bound.httpClientFactory(), bound.scheduler(), bound.blockingExecutor(),
-                        bound.clock() == null ? Clock.systemUTC() : bound.clock(),
-                        bound.openTelemetry() == null ? OpenTelemetry.noop() : bound.openTelemetry(),
-                        bound.clientInstanceId());
-        try {
-            v5.initializeAsync(initContext).get();
-        } catch (InterruptedException e) {
-            Thread.currentThread().interrupt();
-            throw new PulsarClientException(e);
-        } catch (Exception e) {
-            throw BinaryAuthenticationExchange.toV4Exception(BinaryAuthenticationExchange.unwrap(e));
-        }
-        // Binary transport requires the BinaryAuthDataProvider capability (PIP-478 binary routing
-        // rule 1). Fail loudly here rather than synthesizing a "none"/empty credential.
-        if (v5.capability(BinaryAuthDataProvider.class).isEmpty()) {
-            throw new PulsarClientException.UnsupportedAuthenticationException(
-                    "v5 authentication plugin " + v5.getClass().getName() + " does not expose "
-                            + "BinaryAuthDataProvider; the Pulsar binary transport requires it (PIP-478)");
-        }
-    }
-
-    @Override
-    public AuthenticationDataProvider getAuthData(String brokerHostName) throws PulsarClientException {
-        AuthenticationExchange exchange = newAuthenticationExchange(brokerHostName);
-        try {
-            AuthData initial = exchange.getAuthDataAsync().get();
-            return new SynthesizedV4DataProvider(exchange, initial, v5, brokerHostName);
-        } catch (InterruptedException e) {
-            Thread.currentThread().interrupt();
-            throw new PulsarClientException(e);
-        } catch (Exception e) {
-            throw BinaryAuthenticationExchange.toV4Exception(BinaryAuthenticationExchange.unwrap(e));
-        }
-    }
-
-    @Override
-    public AuthenticationExchange newAuthenticationExchange(String brokerHostName) {
-        return new BinaryAuthenticationExchange(v5, new SimpleAuthCallContext(brokerHostName), authMetrics);
-    }
-
-    /**
-     * The v5 {@link BinaryAuthDataProvider} the wrapped plugin exposes for the binary transport.
-     *
-     * @return the capability
-     * @throws IllegalStateException if the plugin does not support the binary transport; normally
-     *         {@link #start()} has already failed loudly before this can be reached
-     */
-    private BinaryAuthDataProvider requireBinaryProvider() {
-        return v5.capability(BinaryAuthDataProvider.class)
-                .orElseThrow(() -> new IllegalStateException(
-                        "v5 authentication plugin " + v5.getClass().getName() + " does not expose "
-                                + "BinaryAuthDataProvider; it cannot authenticate a Pulsar binary-protocol "
-                                + "connection (PIP-478)"));
-    }
-
-    @Override
-    public void close() throws IOException {
-        try {
-            v5.close();
-        } catch (IOException e) {
-            throw e;
-        } catch (Exception e) {
-            throw new IOException(e);
-        }
-    }
-
-    /**
-     * v5 {@link Authentication} plugins are not serializable. Serialization of this adapter is therefore
-     * unsupported. Configure authentication on a remote/forked context via the
-     * {@code authPluginClassName} + {@code authParams} string form instead.
-     *
-     * @param out the object output stream
-     * @throws NotSerializableException always
-     */
-    private void writeObject(ObjectOutputStream out) throws NotSerializableException {
-        throw new NotSerializableException("V5 authentication plugins are not serializable. "
-                + "Configure authentication using authPluginClassName + authParams instead of a "
-                + "pre-built Authentication instance.");
-    }
-
-    private static boolean isInitSentinel(AuthData challenge) {
-        return challenge != null && Arrays.equals(challenge.getBytes(), AuthData.INIT_AUTH_DATA_BYTES);
-    }
-
-    /**
-     * A v4 {@link AuthenticationDataProvider} synthesized from a single
-     * {@link AsyncAuthenticationDriver.AuthenticationExchange}, so that the synchronous v4 {@code ClientCnx}
-     * code path keeps working — including multi-round challenge/response, which rides
-     * {@link #authenticate(AuthData)} through the same exchange (and thus the same
-     * {@link AuthenticationCallContext} state slot).
-     *
-     * <p>It also bridges the single-pass HTTP transport: the v4 HTTP lookup path (which drives
-     * {@link #hasDataForHttp()} / {@link #getHttpHeaders()}) is served from the wrapped plugin's v5
-     * {@link HttpAuthHeadersProvider} capability, so a bearer/role credential (for example
-     * {@code Authorization: Bearer <jwt>}) is attached to the lookup {@code GET}. Multi-round
-     * SASL-over-HTTP challenge/response is out of scope here — it rides the framework HTTP challenge
-     * driver, not this bridge — so a plugin that exposes only an
-     * {@link org.apache.pulsar.client.api.v5.auth.HttpAuthChallengeHandler} contributes no static header
-     * and {@link #hasDataForHttp()} stays {@code false}.
-     */
-    private static final class SynthesizedV4DataProvider implements AuthenticationDataProvider {
-
-        private static final long serialVersionUID = 1L;
-
-        private final transient AuthenticationExchange exchange;
-        private final transient byte[] initialData;
-        private final transient Authentication v5;
-        private final transient String brokerHostName;
-
-        SynthesizedV4DataProvider(AuthenticationExchange exchange, AuthData initial, Authentication v5,
-                                  String brokerHostName) {
-            this.exchange = exchange;
-            this.initialData = initial == null || initial.getBytes() == null ? null : initial.getBytes();
-            this.v5 = v5;
-            this.brokerHostName = brokerHostName;
-        }
-
-        @Override
-        public boolean hasDataFromCommand() {
-            return initialData != null;
-        }
-
-        @Override
-        public String getCommandData() {
-            return initialData == null ? null : new String(initialData, UTF_8);
-        }
-
-        @Override
-        public boolean hasDataForHttp() {
-            return v5.capability(HttpAuthHeadersProvider.class).isPresent();
-        }
-
-        @Override
-        public Set<Map.Entry<String, String>> getHttpHeaders() throws Exception {
-            Optional<HttpAuthHeadersProvider> provider = v5.capability(HttpAuthHeadersProvider.class);
-            if (provider.isEmpty()) {
-                return null;
-            }
-            // Blocking .get() is intentional: this v4 hook runs on the client's blockingAuthExecutor
-            // (HttpClient.computeAuthHeaders offloads the whole v4 branch), never the event loop.
-            HttpAuthCallContext ctx = new SynthesizedHttpAuthCallContext(brokerHostName);
-            try {
-                HttpAuthHeaders headers = provider.get().getHttpHeadersAsync(ctx).get();
-                return headers == null || headers.isEmpty() ? null : headers.asMap().entrySet();
-            } catch (InterruptedException e) {
-                Thread.currentThread().interrupt();
-                throw e;
-            } catch (ExecutionException e) {
-                Throwable cause = BinaryAuthenticationExchange.unwrap(e);
-                if (cause instanceof Exception ex) {
-                    throw ex;
-                }
-                throw new PulsarClientException(cause);
-            }
-        }
-
-        /**
-         * Route a challenge (or the connect/refresh sentinel) through the bound exchange so that v5
-         * challenge handlers work through the plain synchronous v4 path, sharing the exchange's state
-         * slot across rounds. The init sentinel reuses the already-computed initial credential to avoid
-         * re-running the initial round (which, for challenge/response plugins, would re-seed the
-         * conversation).
-         *
-         * @param data the challenge payload, or the {@code INIT}/{@code REFRESH} sentinel
-         * @return the response auth data
-         * @throws javax.naming.AuthenticationException if the exchange fails
-         */
-        @Override
-        public AuthData authenticate(AuthData data) throws javax.naming.AuthenticationException {
-            if (isInitSentinel(data)) {
-                return AuthData.of(initialData == null ? new byte[0] : initialData);
-            }
-            try {
-                AuthData result = exchange.authenticateAsync(data).get();
-                return AuthData.of(result == null ? new byte[0] : result.getBytes());
-            } catch (InterruptedException e) {
-                Thread.currentThread().interrupt();
-                throw namingAuthException(e);
-            } catch (ExecutionException e) {
-                throw namingAuthException(BinaryAuthenticationExchange.unwrap(e));
-            }
-        }
-
-        private static javax.naming.AuthenticationException namingAuthException(Throwable cause) {
-            javax.naming.AuthenticationException e = new javax.naming.AuthenticationException(
-                    cause == null ? null : cause.getMessage());
-            e.initCause(cause);
-            return e;
-        }
-    }
-
-    /**
-     * A single-pass {@link HttpAuthCallContext} for the v4 HTTP lookup path, which surfaces only the
-     * request host (from {@link org.apache.pulsar.client.api.Authentication#getAuthData(String)}) rather
-     * than a full request URI. The host is presented as an {@code https://<host>} URI; single-pass
-     * {@link HttpAuthHeadersProvider}s (token/Athenz/OAuth2) do not consult it. There is no prior server
-     * challenge on this path, so {@link #serverChallengeHeaders()} is always empty; the state slot exists
-     * to satisfy the contract but is not shared across requests.
-     */
-    private static final class SynthesizedHttpAuthCallContext implements HttpAuthCallContext {
-
-        private final URI requestUri;
-        private final Map<Class<?>, Object> state = new ConcurrentHashMap<>();
-
-        SynthesizedHttpAuthCallContext(String brokerHostName) {
-            this.requestUri = URI.create("https://" + (brokerHostName == null ? "" : brokerHostName));
-        }
-
-        @Override
-        public URI requestUri() {
-            return requestUri;
-        }
-
-        @Override
-        public Optional<HttpAuthHeaders> serverChallengeHeaders() {
-            return Optional.empty();
-        }
-
-        @Override
-        public <T> Optional<T> getStateObject(Class<T> clazz) {
-            return Optional.ofNullable(clazz.cast(state.get(clazz)));
-        }
-
-        @Override
-        public <T> void setStateObject(Class<T> clazz, T value) {
-            if (value == null) {
-                state.remove(clazz);
-            } else {
-                state.put(clazz, value);
-            }
-        }
-    }
-}
diff --git a/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/auth/package-info.java b/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/auth/package-info.java
deleted file mode 100644
index 16d2a0e3b7db..000000000000
--- a/pulsar-client-v5/src/main/java/org/apache/pulsar/client/impl/v5/auth/package-info.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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.
- */
-
-/**
- * v5 client authentication bridges and the built-in mTLS plugin (PIP-478).
- *
- * <p>Contains the built-in {@link org.apache.pulsar.client.impl.auth.v5.TlsAuthentication} plugin and
- * the compatibility adapters between the v4 and v5 authentication SPIs:
- * {@link org.apache.pulsar.client.impl.auth.v5.LegacyV4AuthenticationAdapter} (v4 plugin exposed as v5)
- * and {@link org.apache.pulsar.client.impl.v5.auth.V5ToV4AuthenticationAdapter} (v5 plugin exposed
- * through the v4 interface that {@code ClientCnx} drives).
- */
-package org.apache.pulsar.client.impl.v5.auth;
diff --git a/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/CredentialOffloadThroughV5BuilderTest.java b/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/CredentialOffloadThroughV5BuilderTest.java
index a8665c48d740..cf613b2ed8e4 100644
--- a/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/CredentialOffloadThroughV5BuilderTest.java
+++ b/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/CredentialOffloadThroughV5BuilderTest.java
@@ -35,7 +35,7 @@ import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver.Authentic
 import org.apache.pulsar.client.api.v5.internal.ClientAuthenticationServices;
 import org.apache.pulsar.client.impl.auth.v5.DefaultClientAuthenticationServices;
 import org.apache.pulsar.client.impl.auth.v5.LegacyV4AuthenticationAdapter;
-import org.apache.pulsar.client.impl.v5.auth.V5ToV4AuthenticationAdapter;
+import org.apache.pulsar.client.impl.auth.v5.V5BinaryAuthenticationDriver;
 import org.apache.pulsar.common.api.AuthData;
 import org.testng.annotations.Test;
 
@@ -55,10 +55,11 @@ public class CredentialOffloadThroughV5BuilderTest {
         PulsarClientBuilderV5 builder = new PulsarClientBuilderV5();
         builder.authentication(LegacyV4AuthenticationAdapter.wrap(v4));
 
-        // Decision: the credential plugin is NOT unwrapped to the raw v4 engine; it stays wrapped so that
-        // its (blocking) getAuthData off-loads instead of running on the Netty event loop.
+        // The builder hands the raw v4 plugin to the v4 slot — that slot is what the client starts, closes
+        // and reads TLS material from. What the client *drives* is the v5 body it resolves from it, which is
+        // where the off-loading lives.
         org.apache.pulsar.client.api.Authentication resolved = builder.resolveAuthenticationForTest();
-        assertThat(resolved).isInstanceOf(V5ToV4AuthenticationAdapter.class);
+        assertThat(resolved).isSameAs(v4);
 
         ExecutorService blocking = Executors.newSingleThreadExecutor(r -> {
             Thread t = new Thread(r, BLOCKING_THREAD);
@@ -67,12 +68,12 @@ public class CredentialOffloadThroughV5BuilderTest {
         });
         ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
         try {
-            V5ToV4AuthenticationAdapter adapter = (V5ToV4AuthenticationAdapter) resolved;
-            adapter.bindClientAuthenticationServices(services(blocking, scheduler));
-            adapter.start();
+            V5BinaryAuthenticationDriver driver = new V5BinaryAuthenticationDriver(
+                    LegacyV4AuthenticationAdapter.wrapAlreadyStarted(resolved),
+                    services(blocking, scheduler));
 
             String callerThread = Thread.currentThread().getName();
-            AuthenticationExchange exchange = adapter.newAuthenticationExchange("broker.example.com");
+            AuthenticationExchange exchange = driver.newAuthenticationExchange("broker.example.com");
             CompletableFuture<AuthData> future = exchange.getAuthDataAsync();
 
             // The fetch is off-loaded: it started on the blocking executor while the caller proceeds.
diff --git a/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/V5AuthenticationLoaderTest.java b/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/V5AuthenticationLoaderTest.java
index bbcd75af1276..83953f88242c 100644
--- a/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/V5AuthenticationLoaderTest.java
+++ b/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/V5AuthenticationLoaderTest.java
@@ -23,6 +23,7 @@ import static org.assertj.core.api.Assertions.assertThat;
 import java.util.Map;
 import java.util.concurrent.CompletableFuture;
 import org.apache.pulsar.client.api.AuthenticationDataProvider;
+import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver.AuthenticationExchange;
 import org.apache.pulsar.client.api.v5.auth.Authentication;
 import org.apache.pulsar.client.api.v5.auth.AuthenticationCallContext;
 import org.apache.pulsar.client.api.v5.auth.AuthenticationInitContext;
@@ -34,14 +35,15 @@ import org.apache.pulsar.client.api.v5.auth.SinglePassAuthentication;
 import org.apache.pulsar.client.impl.auth.v5.LegacyV4AuthenticationAdapter;
 import org.apache.pulsar.client.impl.auth.v5.NoAuthentication;
 import org.apache.pulsar.client.impl.auth.v5.V5AuthenticationLoader;
-import org.apache.pulsar.client.impl.v5.auth.V5ToV4AuthenticationAdapter;
+import org.apache.pulsar.client.impl.auth.v5.V5BinaryAuthenticationDriver;
+import org.apache.pulsar.common.api.AuthData;
 import org.testng.annotations.Test;
 
 /**
  * Verifies the string-config reflective load path (PIP-478 In-Scope #2): a v5-native
  * {@link Authentication} deployed by class name is instantiated, configured with the parsed
  * {@code authParams}, and drives the Pulsar binary transport through the
- * {@link V5ToV4AuthenticationAdapter} — where before it was blind-cast to the v4 SPI and threw
+ * {@link V5BinaryAuthenticationDriver} — where before it was blind-cast to the v4 SPI and threw
  * {@link ClassCastException}. A legacy v4 class still loads through the {@link LegacyV4AuthenticationAdapter}.
  */
 public class V5AuthenticationLoaderTest {
@@ -125,13 +127,13 @@ public class V5AuthenticationLoaderTest {
                 .containsEntry("user", "alice")
                 .containsEntry("realm", "test");
 
-        // It drives the binary transport through the v5->v4 adapter that ClientCnx consumes.
-        V5ToV4AuthenticationAdapter adapter = new V5ToV4AuthenticationAdapter(auth);
-        adapter.start();
+        // It drives the binary transport through the driver ClientCnx consumes — no v5->v4 wrapping.
+        AuthenticationExchange exchange =
+                new V5BinaryAuthenticationDriver(auth).newAuthenticationExchange("broker-1.example.com");
+        AuthData credential = exchange.getAuthDataAsync().get();
         assertThat(((FakeV5SinglePass) auth).initialized).isTrue();
-        assertThat(adapter.getAuthMethodName()).isEqualTo("fake-v5");
-        AuthenticationDataProvider data = adapter.getAuthData("broker-1.example.com");
-        assertThat(data.getCommandData()).isEqualTo("token:alice");
+        assertThat(exchange.authMethodName()).isEqualTo("fake-v5");
+        assertThat(new String(credential.getBytes(), UTF_8)).isEqualTo("token:alice");
     }
 
     @Test
diff --git a/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/auth/V5ToV4AuthenticationAdapterTest.java b/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/auth/V5ToV4AuthenticationAdapterTest.java
deleted file mode 100644
index 9d0aa7bb43cd..000000000000
--- a/pulsar-client-v5/src/test/java/org/apache/pulsar/client/impl/v5/auth/V5ToV4AuthenticationAdapterTest.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * 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.v5.auth;
-
-import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import java.io.ByteArrayOutputStream;
-import java.io.NotSerializableException;
-import java.io.ObjectOutputStream;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.concurrent.CompletableFuture;
-import org.apache.pulsar.client.api.AuthenticationDataProvider;
-import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver.AuthenticationExchange;
-import org.apache.pulsar.client.api.v5.auth.AuthChallenge;
-import org.apache.pulsar.client.api.v5.auth.Authentication;
-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.BinaryAuthChallengeHandler;
-import org.apache.pulsar.client.api.v5.auth.BinaryAuthData;
-import org.apache.pulsar.client.api.v5.auth.BinaryAuthDataProvider;
-import org.apache.pulsar.client.api.v5.auth.ChallengeResponse;
-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.HttpAuthHeadersProvider;
-import org.apache.pulsar.client.impl.auth.v5.TlsAuthentication;
-import org.apache.pulsar.common.api.AuthData;
-import org.testng.annotations.Test;
-
-/**
- * Verifies that {@link V5ToV4AuthenticationAdapter} exposes a v5 plugin through the v4
- * {@code Authentication} interface that {@code ClientCnx} drives, drives one exchange-scoped call
- * context across all challenge rounds, routes the refresh sentinel to the credential provider (never
- * the challenge handler), fails loudly when the wrapped plugin cannot serve the binary transport, and
- * refuses serialization with an actionable message (v5 plugins are deliberately not {@code Serializable}).
- */
-public class V5ToV4AuthenticationAdapterTest {
-
-    private static V5ToV4AuthenticationAdapter wrap(Authentication v5) {
-        return new V5ToV4AuthenticationAdapter(v5);
-    }
-
-    private static V5ToV4AuthenticationAdapter wrap() {
-        return wrap(new TlsAuthentication());
-    }
-
-    @Test
-    public void exposesV5MethodNameAndEmptyCredentialThroughV4Interface() throws Exception {
-        V5ToV4AuthenticationAdapter adapter = wrap();
-        assertThat(adapter.getAuthMethodName()).isEqualTo("tls");
-        // start() drives the v5 initializeAsync(...) — a no-op for the mTLS plugin — and must not throw.
-        adapter.start();
-
-        AuthenticationDataProvider data = adapter.getAuthData("broker-1.example.com");
-        // mTLS carries an empty binary payload; the certificate is presented at the TLS handshake.
-        assertThat(data.getCommandData()).isEmpty();
-    }
-
-    @Test
-    public void challengeStatePersistsAcrossRoundsThroughOneExchange() throws Exception {
-        CountingChallengePlugin plugin = new CountingChallengePlugin();
-        V5ToV4AuthenticationAdapter adapter = wrap(plugin);
-        adapter.start();
-
-        AuthenticationExchange exchange = adapter.newAuthenticationExchange("broker-1.example.com");
-        // Initial round seeds the conversation state in the call-context state slot.
-        exchange.getAuthDataAsync().get();
-        AuthData round1 = exchange.authenticateAsync(AuthData.of("challenge-1".getBytes(UTF_8))).get();
-        AuthData round2 = exchange.authenticateAsync(AuthData.of("challenge-2".getBytes(UTF_8))).get();
-
-        // The counter advances 1 -> 2 only because both challenge rounds see the SAME state slot; a
-        // per-call context (the bug this fix addresses) would reset it to 1 each round.
-        assertThat(new String(round1.getBytes(), UTF_8)).isEqualTo("round-1");
-        assertThat(new String(round2.getBytes(), UTF_8)).isEqualTo("round-2");
-        assertThat(plugin.challengeCalls).isEqualTo(2);
-    }
-
-    @Test
-    public void refreshSentinelRoutesToDataProviderNotChallengeHandler() throws Exception {
-        CountingChallengePlugin plugin = new CountingChallengePlugin();
-        V5ToV4AuthenticationAdapter adapter = wrap(plugin);
-        adapter.start();
-
-        AuthenticationExchange exchange = adapter.newAuthenticationExchange("broker-1.example.com");
-        exchange.getAuthDataAsync().get();
-        int challengeCallsBefore = plugin.challengeCalls;
-
-        AuthData refreshed = exchange.authenticateAsync(AuthData.REFRESH_AUTH_DATA).get();
-
-        // Refresh means "produce the current credential again": the challenge handler must NOT be called,
-        // and BinaryAuthDataProvider is re-invoked instead.
-        assertThat(plugin.challengeCalls).isEqualTo(challengeCallsBefore);
-        assertThat(plugin.dataCalls).isEqualTo(2);
-        assertThat(new String(refreshed.getBytes(), UTF_8)).isEqualTo("init");
-    }
-
-    @Test
-    public void emptyChallengeRoutesToChallengeHandlerNotDataProvider() throws Exception {
-        CountingChallengePlugin plugin = new CountingChallengePlugin();
-        V5ToV4AuthenticationAdapter adapter = wrap(plugin);
-        adapter.start();
-
-        AuthenticationExchange exchange = adapter.newAuthenticationExchange("broker-1.example.com");
-        // Seed the conversation state, then present an empty challenge payload.
-        exchange.getAuthDataAsync().get();
-        int dataCallsBefore = plugin.dataCalls;
-
-        AuthData response = exchange.authenticateAsync(AuthData.of(new byte[0])).get();
-
-        // An empty payload is a legitimate challenge round (PIP-478 rule 3), not the refresh sentinel: the
-        // challenge handler answers it and BinaryAuthDataProvider is NOT re-invoked.
-        assertThat(plugin.challengeCalls).isEqualTo(1);
-        assertThat(plugin.dataCalls).isEqualTo(dataCallsBefore);
-        assertThat(new String(response.getBytes(), UTF_8)).isEqualTo("round-1");
-    }
-
-    @Test
-    public void startFailsLoudlyWhenBinaryCapabilityIsMissing() {
-        // A v5 plugin exposing no capabilities cannot serve the binary transport; using it there is an
-        // error (PIP-478 binary routing rule 1) — never a silent "none"/empty credential.
-        Authentication noBinary = ctx -> CompletableFuture.completedFuture(null);
-        V5ToV4AuthenticationAdapter adapter = wrap(noBinary);
-
-        assertThatThrownBy(adapter::start).isInstanceOf(
-                org.apache.pulsar.client.api.PulsarClientException.UnsupportedAuthenticationException.class);
-    }
-
-    @Test
-    public void bridgesSinglePassHttpHeadersFromV5Capability() throws Exception {
-        V5ToV4AuthenticationAdapter adapter = wrap(new HttpHeaderPlugin());
-        adapter.start();
-
-        AuthenticationDataProvider data = adapter.getAuthData("broker-1.example.com");
-
-        // Without this bridge the v4 HTTP lookup path attaches no Authorization header and an
-        // authenticated http:// lookup GET returns 401 (the PIP-478 regression this fix closes).
-        assertThat(data.hasDataForHttp()).isTrue();
-        Map<String, String> headers = new LinkedHashMap<>();
-        data.getHttpHeaders().forEach(entry -> headers.put(entry.getKey(), entry.getValue()));
-        // HttpAuthHeaders canonicalises header names to lower case.
-        assertThat(headers).containsEntry("authorization", "Bearer jwt-token");
-    }
-
-    @Test
-    public void reportsNoHttpDataWhenPluginHasNoHttpHeaderCapability() throws Exception {
-        // The mTLS plugin exposes only BinaryAuthDataProvider; it contributes no single-pass HTTP header,
-        // so the v4 HTTP path must report none rather than attaching an empty/absent credential.
-        V5ToV4AuthenticationAdapter adapter = wrap();
-        adapter.start();
-
-        AuthenticationDataProvider data = adapter.getAuthData("broker-1.example.com");
-
-        assertThat(data.hasDataForHttp()).isFalse();
-        assertThat(data.getHttpHeaders()).isNull();
-    }
-
-    @Test
-    public void refusesSerializationWithActionableMessage() {
-        assertThatThrownBy(() -> new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(wrap()))
-                .isInstanceOf(NotSerializableException.class)
-                .hasMessageContaining("authPluginClassName");
-    }
-
-    /**
-     * A fake v5 challenge/response plugin that keeps a per-exchange round counter in the call-context
-     * state slot, so a test can prove the same context (and slot) is reused across rounds.
-     */
-    private static final class CountingChallengePlugin
-            implements Authentication, BinaryAuthDataProvider, BinaryAuthChallengeHandler {
-
-        private static final class Counter {
-            private int rounds;
-        }
-
-        private int dataCalls;
-        private int challengeCalls;
-
-        @Override
-        public CompletableFuture<Void> initializeAsync(AuthenticationInitContext ctx) {
-            return CompletableFuture.completedFuture(null);
-        }
-
-        @Override
-        public String authMethodName() {
-            return "counting";
-        }
-
-        @Override
-        public CompletableFuture<BinaryAuthData> getAuthDataAsync(AuthenticationCallContext ctx) {
-            dataCalls++;
-            ctx.setStateObject(Counter.class, new Counter());
-            return CompletableFuture.completedFuture(new BinaryAuthData("init".getBytes(UTF_8)));
-        }
-
-        @Override
-        public CompletableFuture<ChallengeResponse> respondToChallengeAsync(AuthenticationCallContext ctx,
-                AuthChallenge authChallenge) {
-            challengeCalls++;
-            Counter counter = ctx.getStateObject(Counter.class).orElseThrow(
-                    () -> new IllegalStateException("conversation state did not persist across rounds"));
-            counter.rounds++;
-            return CompletableFuture.completedFuture(
-                    new ChallengeResponse(("round-" + counter.rounds).getBytes(UTF_8)));
-        }
-    }
-
-    /**
-     * A fake v5 token-style plugin that serves the binary transport and a single-pass HTTP
-     * {@code Authorization: Bearer <jwt>} header through the {@link HttpAuthHeadersProvider} capability.
-     */
-    private static final class HttpHeaderPlugin
-            implements Authentication, BinaryAuthDataProvider, HttpAuthHeadersProvider {
-
-        @Override
-        public CompletableFuture<Void> initializeAsync(AuthenticationInitContext ctx) {
-            return CompletableFuture.completedFuture(null);
-        }
-
-        @Override
-        public String authMethodName() {
-            return "token";
-        }
-
-        @Override
-        public CompletableFuture<BinaryAuthData> getAuthDataAsync(AuthenticationCallContext ctx) {
-            return CompletableFuture.completedFuture(new BinaryAuthData("jwt-token".getBytes(UTF_8)));
-        }
-
-        @Override
-        public CompletableFuture<HttpAuthHeaders> getHttpHeadersAsync(HttpAuthCallContext ctx) {
-            return CompletableFuture.completedFuture(HttpAuthHeaders.of("Authorization", "Bearer jwt-token"));
-        }
-    }
-}
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ClientCnx.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ClientCnx.java
index 1be537e4bae0..291c4e26283f 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ClientCnx.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ClientCnx.java
@@ -57,7 +57,6 @@ import lombok.AccessLevel;
 import lombok.Getter;
 import org.apache.commons.lang3.tuple.Pair;
 import org.apache.pulsar.PulsarVersion;
-import org.apache.pulsar.client.api.Authentication;
 import org.apache.pulsar.client.api.AuthenticationDataProvider;
 import org.apache.pulsar.client.api.PulsarClientException;
 import org.apache.pulsar.client.api.PulsarClientException.ConnectException;
@@ -65,6 +64,8 @@ import org.apache.pulsar.client.api.PulsarClientException.TimeoutException;
 import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver;
 import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver.AuthenticationExchange;
 import org.apache.pulsar.client.impl.BinaryProtoLookupService.LookupDataResult;
+import org.apache.pulsar.client.impl.auth.v5.V5AuthenticationLoader;
+import org.apache.pulsar.client.impl.auth.v5.V5BinaryAuthenticationDriver;
 import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
 import org.apache.pulsar.client.impl.metrics.Counter;
 import org.apache.pulsar.client.impl.metrics.InstrumentProvider;
@@ -128,7 +129,10 @@ public class ClientCnx extends PulsarHandler {
     // Derived instance logger with channel context, set in channelActive().
     private Logger log = LOG;
 
-    protected final Authentication authentication;
+    // PIP-478: the authentication the client drives. The client resolves exactly one v5 Authentication and
+    // wraps it in this per-client driver, from which every connection attempt opens its own exchange; there
+    // is no synchronous plugin path left on the connect/challenge routes.
+    protected final AsyncAuthenticationDriver authDriver;
     protected State state;
 
     @VisibleForTesting
@@ -345,7 +349,7 @@ public class ClientCnx extends PulsarHandler {
         this.maxLookupRequestSemaphore =
                 new Semaphore(conf.getMaxLookupRequest() - conf.getConcurrentLookupRequest(), false);
         this.waitingLookupRequests = Queues.newConcurrentLinkedQueue();
-        this.authentication = conf.getAuthentication();
+        this.authDriver = resolveAuthDriver(conf);
         this.eventLoopGroup = eventLoopGroup;
         this.maxNumberOfRejectedRequestPerConnection = conf.getMaxNumberOfRejectedRequestPerConnection();
         this.operationTimeoutMs = conf.getOperationTimeoutMs();
@@ -408,17 +412,9 @@ public class ClientCnx extends PulsarHandler {
         // funnelled into a failed future so the continuation always handles it — never a synchronous throw
         // on the event loop.
         try {
-            if (authentication instanceof AsyncAuthenticationDriver asyncAuth) {
-                authenticationExchange = asyncAuth.newAuthenticationExchange(remoteHostName);
-                return authenticationExchange.getAuthDataAsync()
-                        .thenApply(authData -> new ResolvedAuthData(commandDataProvider(authData), authData));
-            }
-            // mutual authentication is to auth between `remoteHostName` and this client for this channel.
-            // each channel will have a mutual client/server pair, mutual client evaluateChallenge with init
-            // data, and return authData to server.
-            AuthenticationDataProvider provider = authentication.getAuthData(remoteHostName);
-            AuthData authData = provider.authenticate(AuthData.INIT_AUTH_DATA);
-            return CompletableFuture.completedFuture(new ResolvedAuthData(provider, authData));
+            authenticationExchange = authDriver.newAuthenticationExchange(remoteHostName);
+            return authenticationExchange.getAuthDataAsync()
+                    .thenApply(authData -> new ResolvedAuthData(commandDataProvider(authData), authData));
         } catch (Throwable t) {
             return CompletableFuture.failedFuture(t);
         }
@@ -471,8 +467,46 @@ public class ClientCnx extends PulsarHandler {
      * (e.g. the proxy's broker client) can customise the frame — the resolved {@link AuthData} is passed in
      * rather than re-fetched, so the override composes with both the sync and async credential paths.
      */
+    /**
+     * The authentication driver for this connection's configuration.
+     *
+     * <p>{@code PulsarClientImpl} resolves one per client, so that its initialization runs once and every
+     * connection shares it. Not every {@code ClientCnx} comes from a {@code PulsarClient} though — the proxy
+     * builds broker connections straight from a configuration — so resolve and memoize one here for those,
+     * keyed on the configuration so connections sharing it still share a driver.
+     *
+     * @param conf the client configuration this connection is built from
+     * @return the driver to open authentication exchanges against
+     */
+    private static AsyncAuthenticationDriver resolveAuthDriver(ClientConfigurationData conf) {
+        AsyncAuthenticationDriver resolved = conf.getV5AuthenticationDriver();
+        if (resolved != null) {
+            return resolved;
+        }
+        synchronized (conf) {
+            resolved = conf.getV5AuthenticationDriver();
+            if (resolved == null) {
+                resolved = new V5BinaryAuthenticationDriver(
+                        V5AuthenticationLoader.forStartedV4Plugin(conf.getAuthentication()));
+                conf.setV5AuthenticationDriver(resolved);
+            }
+            return resolved;
+        }
+    }
+
+    /**
+     * The auth method name to declare on the wire, taken from the exchange that produced the credential
+     * being sent. It is not resolved at construction: a bridged legacy plugin only learns which capabilities
+     * it can serve once its initialization has run, which happens on the first connection attempt.
+     *
+     * @return the auth method name for the current exchange
+     */
+    protected String authMethodName() {
+        return authenticationExchange.authMethodName();
+    }
+
     protected ByteBuf buildConnectCommand(AuthData authData) throws Exception {
-        return Commands.newConnect(authentication.getAuthMethodName(), authData, this.protocolVersion,
+        return Commands.newConnect(authMethodName(), authData, this.protocolVersion,
                 clientVersion, proxyToTargetBrokerAddress, originalPrincipal, null, null);
     }
 
@@ -633,23 +667,13 @@ public class ClientCnx extends PulsarHandler {
         // As in resolveConnectAuthData, one try/catch guarantees a failed future rather than a synchronous
         // throw on the event loop, for both the sync and the async plugin paths.
         try {
-            if (authentication instanceof AsyncAuthenticationDriver asyncAuth) {
-                if (refresh) {
-                    authenticationExchange = asyncAuth.newAuthenticationExchange(remoteHostName);
-                    return authenticationExchange.getAuthDataAsync()
-                            .thenApply(authData -> new ResolvedAuthData(commandDataProvider(authData), authData));
-                }
-                return authenticationExchange.authenticateAsync(challenge)
-                        .thenApply(authData -> new ResolvedAuthData(null, authData));
-            }
-            AuthenticationDataProvider provider = authenticationDataProvider;
-            AuthenticationDataProvider providerToPublish = null;
             if (refresh) {
-                provider = authentication.getAuthData(remoteHostName);
-                providerToPublish = provider;
+                authenticationExchange = authDriver.newAuthenticationExchange(remoteHostName);
+                return authenticationExchange.getAuthDataAsync()
+                        .thenApply(authData -> new ResolvedAuthData(commandDataProvider(authData), authData));
             }
-            AuthData authData = provider.authenticate(challenge);
-            return CompletableFuture.completedFuture(new ResolvedAuthData(providerToPublish, authData));
+            return authenticationExchange.authenticateAsync(challenge)
+                    .thenApply(authData -> new ResolvedAuthData(null, authData));
         } catch (Throwable t) {
             return CompletableFuture.failedFuture(t);
         }
@@ -674,12 +698,12 @@ public class ClientCnx extends PulsarHandler {
 
             checkState(!authData.isComplete());
 
-            ByteBuf request = Commands.newAuthResponse(authentication.getAuthMethodName(),
+            ByteBuf request = Commands.newAuthResponse(authMethodName(),
                     authData,
                     this.protocolVersion,
                     clientVersion);
                 log.debug()
-                        .attr("auth", authentication.getAuthMethodName())
+                        .attr("auth", authMethodName())
                         .log("Mutual auth");
 
             ctx.writeAndFlush(request).addListener(writeFuture -> {
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 f0eeeebbbe33..38ec29f987ec 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
@@ -82,6 +82,8 @@ import org.apache.pulsar.client.api.v5.internal.ClientAuthenticationServicesAwar
 import org.apache.pulsar.client.impl.auth.oauth2.AuthenticationOAuth2;
 import org.apache.pulsar.client.impl.auth.v5.DefaultClientAuthenticationServices;
 import org.apache.pulsar.client.impl.auth.v5.FrameworkHttpClientFactory;
+import org.apache.pulsar.client.impl.auth.v5.V5AuthenticationLoader;
+import org.apache.pulsar.client.impl.auth.v5.V5BinaryAuthenticationDriver;
 import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
 import org.apache.pulsar.client.impl.conf.ConsumerConfigurationData;
 import org.apache.pulsar.client.impl.conf.ProducerConfigurationData;
@@ -165,6 +167,9 @@ public class PulsarClientImpl implements PulsarClient {
     // PIP-478: the framework HTTP client factory handed to an auth driver that wants one; null when
     // no ClientAuthenticationServicesAware plugin is configured. Closed with the client.
     private volatile FrameworkHttpClientFactory authHttpClientFactory;
+    // PIP-478: the framework services handed to the authentication the client drives, rebuilt alongside
+    // authHttpClientFactory on every updateAuthentication rebind.
+    private volatile ClientAuthenticationServices authServices;
 
     private final boolean createdEventLoopGroup;
     private final boolean createdCnxPool;
@@ -320,6 +325,7 @@ public class PulsarClientImpl implements PulsarClient {
             // its first call. Nothing between the config above and here consumes started authentication.
             bindAuthenticationServices(conf.getAuthentication());
             conf.getAuthentication().start();
+            resolveV5Authentication();
             lookup = createLookup(conf.getServiceUrl());
 
             if (conf.getServiceUrlProvider() != null) {
@@ -373,7 +379,7 @@ public class PulsarClientImpl implements PulsarClient {
      *        {@code AuthenticationDisabled} when unset)
      */
     private void bindAuthenticationServices(Authentication authentication) {
-        if (authentication instanceof ClientAuthenticationServicesAware aware) {
+        {
             // Do not (re)bind into a client that is shutting down: a rebind racing close() would install a
             // FrameworkHttpClientFactory that close() has already passed, leaking it. state is null during
             // construction (the first bind), which must proceed.
@@ -404,8 +410,31 @@ public class PulsarClientImpl implements PulsarClient {
                     clientClock,
                     conf.getOpenTelemetry() != null ? conf.getOpenTelemetry() : OpenTelemetry.noop(),
                     clientInstanceId);
-            aware.bindClientAuthenticationServices(services);
+            this.authServices = services;
+            if (authentication instanceof ClientAuthenticationServicesAware aware) {
+                aware.bindClientAuthenticationServices(services);
+            }
+        }
+    }
+
+    /**
+     * Resolve the authentication the client drives (PIP-478). The client drives the v5 model natively, so
+     * exactly one v5 {@code Authentication} is resolved per client and every connection opens an exchange
+     * against it.
+     *
+     * <p>The v5 builder may already have configured a v5 plugin; otherwise the v4 slot is translated. A
+     * built-in shim hands over its v5-native body (no bridge, no executor hop for a credential it holds in
+     * memory); anything else is wrapped by {@link LegacyV4AuthenticationAdapter}. The wrap is the
+     * already-started variant because the v4 instance stays in {@code conf} and this client both started it
+     * above and closes it in {@link #shutdown()} — the adapter must not run that lifecycle a second time.
+     */
+    private void resolveV5Authentication() {
+        org.apache.pulsar.client.api.v5.auth.Authentication v5 = conf.getV5Authentication();
+        if (v5 == null) {
+            v5 = V5AuthenticationLoader.forStartedV4Plugin(conf.getAuthentication());
+            conf.setV5Authentication(v5);
         }
+        conf.setV5AuthenticationDriver(new V5BinaryAuthenticationDriver(v5, authServices));
     }
 
     /**
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/AuthenticationBasic.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/AuthenticationBasic.java
index f285102351f6..6f146dc0ed54 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/AuthenticationBasic.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/AuthenticationBasic.java
@@ -26,28 +26,23 @@ import org.apache.pulsar.client.api.Authentication;
 import org.apache.pulsar.client.api.AuthenticationDataProvider;
 import org.apache.pulsar.client.api.EncodedAuthenticationParameterSupport;
 import org.apache.pulsar.client.api.PulsarClientException;
-import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver;
-import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver.AuthenticationExchange;
-import org.apache.pulsar.client.api.v5.internal.ClientAuthenticationServices;
-import org.apache.pulsar.client.api.v5.internal.ClientAuthenticationServicesAware;
+import org.apache.pulsar.client.api.v5.internal.V5AuthenticationProvider;
 import org.apache.pulsar.client.impl.auth.v5.BasicAuthenticationV5;
-import org.apache.pulsar.client.impl.auth.v5.V5BinaryAuthenticationDriver;
 
 /**
  * HTTP-basic authentication provider.
  *
  * <p>The verbatim v4 synchronous surface ({@link #getAuthData()} / {@link AuthenticationDataBasic}) is
- * preserved; PIP-478 additionally exposes {@link AsyncAuthenticationDriver} so {@code ClientCnx} can drive
- * the credential over the non-blocking binary path via the v5-native {@link BasicAuthenticationV5}.
+ * preserved for callers of the v4 API; PIP-478 additionally exposes the v5-native
+ * {@link BasicAuthenticationV5} through {@link V5AuthenticationProvider}, which is what the client itself
+ * drives — over the non-blocking binary path, without bridging this class.
  */
 public class AuthenticationBasic
-        implements Authentication, EncodedAuthenticationParameterSupport, AsyncAuthenticationDriver,
-        ClientAuthenticationServicesAware {
+        implements Authentication, EncodedAuthenticationParameterSupport, V5AuthenticationProvider {
     static final String AUTH_METHOD_NAME = "basic";
     private String userId;
     private String password;
     // PIP-478: the client's framework services, late-bound before start(); null until then.
-    private transient volatile ClientAuthenticationServices authServices;
 
     @Override
     public void close() throws IOException {
@@ -88,15 +83,11 @@ public class AuthenticationBasic
     }
 
     @Override
-    public void bindClientAuthenticationServices(ClientAuthenticationServices services) {
-        this.authServices = services;
-    }
-
-    @Override
-    public AuthenticationExchange newAuthenticationExchange(String brokerHostName) {
-        // PIP-478: drive the v5-native basic body on the async binary path.
-        return new V5BinaryAuthenticationDriver(new BasicAuthenticationV5(userId, password), authServices)
-                .newAuthenticationExchange(brokerHostName);
+    public org.apache.pulsar.client.api.v5.auth.Authentication v5Authentication() {
+        // PIP-478: the client drives this v5-native basic body; the v4 methods above remain for callers of
+        // the v4 API. The fields are read live, so a credential changed by a later configure(...) on this
+        // same instance is picked up on the next connection attempt.
+        return new BasicAuthenticationV5(() -> userId, () -> password);
     }
 
 }
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/AuthenticationToken.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/AuthenticationToken.java
index 7e649fb07583..5f1e75da6d36 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/AuthenticationToken.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/AuthenticationToken.java
@@ -27,29 +27,24 @@ import org.apache.pulsar.client.api.Authentication;
 import org.apache.pulsar.client.api.AuthenticationDataProvider;
 import org.apache.pulsar.client.api.EncodedAuthenticationParameterSupport;
 import org.apache.pulsar.client.api.PulsarClientException;
-import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver;
-import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver.AuthenticationExchange;
-import org.apache.pulsar.client.api.v5.internal.ClientAuthenticationServices;
-import org.apache.pulsar.client.api.v5.internal.ClientAuthenticationServicesAware;
+import org.apache.pulsar.client.api.v5.internal.V5AuthenticationProvider;
 import org.apache.pulsar.client.impl.auth.v5.TokenAuthenticationV5;
-import org.apache.pulsar.client.impl.auth.v5.V5BinaryAuthenticationDriver;
 
 /**
  * Token based authentication provider.
  *
  * <p>The verbatim v4 synchronous surface ({@link #getAuthData()} / {@link AuthenticationDataToken}) is
- * preserved; PIP-478 additionally exposes {@link AsyncAuthenticationDriver} so {@code ClientCnx} can drive
- * the token credential over the non-blocking binary path via the v5-native {@link TokenAuthenticationV5}.
+ * preserved for callers of the v4 API; PIP-478 additionally exposes the v5-native
+ * {@link TokenAuthenticationV5} through {@link V5AuthenticationProvider}, which is what the client itself
+ * drives — over the non-blocking binary path, without bridging this class.
  */
 public class AuthenticationToken
-        implements Authentication, EncodedAuthenticationParameterSupport, AsyncAuthenticationDriver,
-        ClientAuthenticationServicesAware {
+        implements Authentication, EncodedAuthenticationParameterSupport, V5AuthenticationProvider {
     static final String AUTH_METHOD_NAME = "token";
 
     private static final long serialVersionUID = 1L;
     private Supplier<String> tokenSupplier = null;
     // PIP-478: the client's framework services, late-bound before start(); null until then.
-    private transient volatile ClientAuthenticationServices authServices;
 
     public AuthenticationToken() {
     }
@@ -97,16 +92,11 @@ public class AuthenticationToken
     }
 
     @Override
-    public void bindClientAuthenticationServices(ClientAuthenticationServices services) {
-        this.authServices = services;
-    }
-
-    @Override
-    public AuthenticationExchange newAuthenticationExchange(String brokerHostName) {
-        // PIP-478: drive the v5-native token body on the async binary path. The supplier is read live so a
-        // token rotated via configure(...) is picked up on the next connection attempt.
-        return new V5BinaryAuthenticationDriver(new TokenAuthenticationV5(() -> tokenSupplier.get()), authServices)
-                .newAuthenticationExchange(brokerHostName);
+    public org.apache.pulsar.client.api.v5.auth.Authentication v5Authentication() {
+        // PIP-478: the client drives this v5-native token body; the v4 methods above remain for callers of
+        // the v4 API. The supplier is read live so a token rotated via configure(...) is picked up on the
+        // next connection attempt.
+        return new TokenAuthenticationV5(() -> tokenSupplier.get());
     }
 
     /**
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/AuthenticationOAuth2.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/AuthenticationOAuth2.java
index d32c1ac8b411..2d4b9586c90d 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/AuthenticationOAuth2.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/oauth2/AuthenticationOAuth2.java
@@ -39,14 +39,12 @@ import org.apache.pulsar.client.api.Authentication;
 import org.apache.pulsar.client.api.AuthenticationDataProvider;
 import org.apache.pulsar.client.api.EncodedAuthenticationParameterSupport;
 import org.apache.pulsar.client.api.PulsarClientException;
-import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver;
-import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver.AuthenticationExchange;
 import org.apache.pulsar.client.api.v5.internal.ClientAuthenticationServices;
 import org.apache.pulsar.client.api.v5.internal.ClientAuthenticationServicesAware;
+import org.apache.pulsar.client.api.v5.internal.V5AuthenticationProvider;
 import org.apache.pulsar.client.impl.AuthenticationUtil;
 import org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenEndpointAuthMethod;
 import org.apache.pulsar.client.impl.auth.oauth2.protocol.TokenResult;
-import org.apache.pulsar.client.impl.auth.v5.V5BinaryAuthenticationDriver;
 import org.apache.pulsar.common.util.Backoff;
 import org.apache.pulsar.tls.TlsPolicy;
 import org.apache.pulsar.tls.TlsPurpose;
@@ -80,7 +78,7 @@ import org.apache.pulsar.tls.TlsPurpose;
  */
 @CustomLog
 public class AuthenticationOAuth2
-        implements Authentication, EncodedAuthenticationParameterSupport, AsyncAuthenticationDriver,
+        implements Authentication, EncodedAuthenticationParameterSupport, V5AuthenticationProvider,
         ClientAuthenticationServicesAware {
 
     public static final String CONFIG_PARAM_TYPE = "type";
@@ -298,14 +296,13 @@ public class AuthenticationOAuth2
     }
 
     @Override
-    public AuthenticationExchange newAuthenticationExchange(String brokerHostName) {
-        // PIP-478: drive the v5-native OAuth2 body on the async binary path. The heavy flow — token
-        // acquisition, caching and early refresh — stays on this shim; the body reads the current access
-        // token through getAuthData(), so a broker-pushed REFRESH re-fetches an expired token here exactly
-        // as the synchronous path does. The bound blocking executor off-loads that (network-blocking)
-        // fetch so it never runs on the Netty event loop.
-        return new V5BinaryAuthenticationDriver(new OAuth2AuthenticationV5(this::currentAccessToken), authServices)
-                .newAuthenticationExchange(brokerHostName);
+    public org.apache.pulsar.client.api.v5.auth.Authentication v5Authentication() {
+        // PIP-478: the client drives this v5-native OAuth2 body. The heavy flow — token acquisition,
+        // caching and early refresh — stays on this shim; the body reads the current access token through
+        // getAuthData(), so a broker-pushed REFRESH re-fetches an expired token here exactly as the
+        // synchronous path does. The blocking executor the body is initialized with off-loads that
+        // (network-blocking) fetch so it never runs on the Netty event loop.
+        return new OAuth2AuthenticationV5(this::currentAccessToken);
     }
 
     private String currentAccessToken() {
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/BasicAuthenticationV5.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/BasicAuthenticationV5.java
index 6c5f61d3bf40..dece64071cb7 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/BasicAuthenticationV5.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/BasicAuthenticationV5.java
@@ -24,6 +24,7 @@ import java.util.Base64;
 import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.concurrent.CompletableFuture;
+import java.util.function.Supplier;
 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;
@@ -52,14 +53,28 @@ public class BasicAuthenticationV5 implements SinglePassAuthentication, Serializ
     /** The Pulsar HTTP header that names the auth method. */
     public static final String PULSAR_AUTH_METHOD_NAME = "X-Pulsar-Auth-Method-Name";
 
-    private final String userId;
-    private final String password;
+    private final Supplier<String> userId;
+    private final Supplier<String> password;
 
     /**
      * @param userId   the user id
      * @param password the password
      */
     public BasicAuthenticationV5(String userId, String password) {
+        this(new TokenAuthenticationV5.LiteralTokenSupplier(userId),
+                new TokenAuthenticationV5.LiteralTokenSupplier(password));
+    }
+
+    /**
+     * Serve credentials that the caller may change after this body is constructed. The client resolves one
+     * body per plugin and keeps it for the client's lifetime, so the v4 {@code AuthenticationBasic} shim —
+     * whose {@code configure(...)} may run again on the same instance — supplies its fields through
+     * suppliers rather than by value.
+     *
+     * @param userId   supplies the current user id
+     * @param password supplies the current password
+     */
+    public BasicAuthenticationV5(Supplier<String> userId, Supplier<String> password) {
         this.userId = userId;
         this.password = password;
     }
@@ -94,6 +109,6 @@ public class BasicAuthenticationV5 implements SinglePassAuthentication, Serializ
     }
 
     private String userInfo() {
-        return userId + ":" + password;
+        return userId.get() + ":" + password.get();
     }
 }
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/BinaryAuthenticationExchange.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/BinaryAuthenticationExchange.java
index 933309dfb64f..8fdb47b50d70 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/BinaryAuthenticationExchange.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/BinaryAuthenticationExchange.java
@@ -90,6 +90,19 @@ public final class BinaryAuthenticationExchange implements AuthenticationExchang
         this.metrics = metrics == null ? AuthMetrics.NOOP : metrics;
     }
 
+    @Override
+    public String authMethodName() {
+        // Unreachable before a round has run: every route into this method follows a completed
+        // getAuthDataAsync()/authenticateAsync(), which fails the connection when the capability is absent.
+        // Failing loudly beats defaulting to "none", which would silently downgrade the connection to
+        // anonymous.
+        return v5.capability(BinaryAuthDataProvider.class)
+                .map(BinaryAuthDataProvider::authMethodName)
+                .orElseThrow(() -> new IllegalStateException(
+                        "v5 authentication body " + v5.getClass().getName() + " does not expose "
+                                + "BinaryAuthDataProvider, so it has no binary auth method name (PIP-478)"));
+    }
+
     @Override
     public CompletableFuture<AuthData> getAuthDataAsync() {
         // Never throw synchronously (PIP-478 error model): a body that throws while producing its future is
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/LegacyV4AuthenticationAdapter.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/LegacyV4AuthenticationAdapter.java
index c849f1fbfff4..c45282b2cab4 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/LegacyV4AuthenticationAdapter.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/LegacyV4AuthenticationAdapter.java
@@ -18,7 +18,6 @@
  */
 package org.apache.pulsar.client.impl.auth.v5;
 
-import static java.nio.charset.StandardCharsets.UTF_8;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Optional;
@@ -75,11 +74,23 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
      */
     protected final org.apache.pulsar.client.api.Authentication v4;
 
+    /**
+     * Whether this adapter is responsible for the wrapped plugin's {@code configure}/{@code start}/
+     * {@code close} lifecycle. False when the client that resolved this adapter already owns the v4
+     * instance and drives that lifecycle itself; see {@link #wrapAlreadyStarted}.
+     */
+    private final boolean ownsV4Lifecycle;
+
     private volatile AuthenticationInitContext initContext;
     private volatile Map<String, String> configuredParams;
 
     LegacyV4AuthenticationAdapter(org.apache.pulsar.client.api.Authentication v4) {
+        this(v4, true);
+    }
+
+    LegacyV4AuthenticationAdapter(org.apache.pulsar.client.api.Authentication v4, boolean ownsV4Lifecycle) {
         this.v4 = v4;
+        this.ownsV4Lifecycle = ownsV4Lifecycle;
     }
 
     /**
@@ -106,6 +117,28 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
      *         for the method names that have one
      */
     public static Authentication wrap(org.apache.pulsar.client.api.Authentication v4) {
+        return wrap(v4, true);
+    }
+
+    /**
+     * Wrap a v4 plugin whose {@code configure}/{@code start} the caller has already performed and whose
+     * {@code close} the caller will perform.
+     *
+     * <p>This is the client's own path. The client keeps the configured v4 plugin in its configuration and
+     * starts it during construction — the v4 instance remains observable, and several client-side features
+     * (notably folding an auth plugin's TLS material into the client's TLS policy) read it directly. The
+     * adapter that lets the client <em>drive</em> that plugin through the v5 model must therefore not run
+     * the lifecycle a second time: {@code AuthenticationOAuth2.start()} initializes the token flow, so a
+     * second {@code start()} is not a harmless no-op.
+     *
+     * @param v4 the already-configured, already-started v4 authentication plugin
+     * @return a v5 {@link Authentication} that delegates to the v4 plugin without re-running its lifecycle
+     */
+    public static Authentication wrapAlreadyStarted(org.apache.pulsar.client.api.Authentication v4) {
+        return wrap(v4, false);
+    }
+
+    private static Authentication wrap(org.apache.pulsar.client.api.Authentication v4, boolean ownsLifecycle) {
         if (v4 == null) {
             throw new IllegalArgumentException("v4 authentication must not be null");
         }
@@ -114,12 +147,12 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
             return NoAuthentication.INSTANCE;
         }
         if (TlsAuthentication.DEFAULT_AUTH_METHOD_NAME.equalsIgnoreCase(methodName)) {
-            return new LegacyV4TlsAdapter(v4);
+            return new LegacyV4TlsAdapter(v4, ownsLifecycle);
         }
         if ("sasl".equalsIgnoreCase(methodName)) {
-            return new LegacyV4ChallengeResponseAdapter(v4);
+            return new LegacyV4ChallengeResponseAdapter(v4, ownsLifecycle);
         }
-        return new LegacyV4CredentialAdapter(v4);
+        return new LegacyV4CredentialAdapter(v4, ownsLifecycle);
     }
 
     /**
@@ -153,11 +186,13 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
     public CompletableFuture<Void> initializeAsync(AuthenticationInitContext initContext) {
         this.initContext = initContext;
         return supplyOffloaded(() -> {
-            Map<String, String> cfg = configuredParams;
-            if (cfg != null) {
-                v4.configure(cfg);
+            if (ownsV4Lifecycle) {
+                Map<String, String> cfg = configuredParams;
+                if (cfg != null) {
+                    v4.configure(cfg);
+                }
+                v4.start();
             }
-            v4.start();
             onStarted();
             return null;
         });
@@ -165,7 +200,11 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
 
     @Override
     public void close() throws Exception {
-        v4.close();
+        // Closing a plugin this adapter did not start would close it twice: its owner closes it too, and a
+        // v4 plugin is not required to be idempotent.
+        if (ownsV4Lifecycle) {
+            v4.close();
+        }
     }
 
     /**
@@ -270,13 +309,12 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
      * {@link PulsarClientException.UnsupportedAuthenticationException}.
      */
     static final class LegacyV4CredentialAdapter extends LegacyV4AuthenticationAdapter
-            implements BinaryAuthDataProvider, HttpAuthHeadersProvider {
+            implements BinaryAuthDataProvider, BinaryAuthChallengeHandler, HttpAuthHeadersProvider {
 
-        private volatile boolean supportsCommand;
         private volatile boolean supportsHttp;
 
-        LegacyV4CredentialAdapter(org.apache.pulsar.client.api.Authentication v4) {
-            super(v4);
+        LegacyV4CredentialAdapter(org.apache.pulsar.client.api.Authentication v4, boolean ownsV4Lifecycle) {
+            super(v4, ownsV4Lifecycle);
         }
 
         @Override
@@ -287,13 +325,10 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
             // unverifiable HTTP path.
             try {
                 AuthenticationDataProvider probe = v4.getAuthData(null);
-                supportsCommand = probe != null && probe.hasDataFromCommand();
                 supportsHttp = probe != null && probe.hasDataForHttp();
             } catch (Exception e) {
                 log.debug().attr("plugin", v4.getClass().getName()).exception(e)
-                        .log("Could not probe v4 auth plugin for supported capabilities; assuming binary "
-                                + "command only");
-                supportsCommand = true;
+                        .log("Could not probe v4 auth plugin for HTTP support; assuming binary only");
                 supportsHttp = false;
             }
         }
@@ -302,8 +337,14 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
         public <T> Optional<T> capability(Class<T> kind) {
             // This adapter can serve only the two single-pass capabilities, and only those the probe
             // confirmed the v4 plugin actually supports. Anything else is unsupported.
-            if (kind == BinaryAuthDataProvider.class) {
-                return supportsCommand ? Optional.of(kind.cast(this)) : Optional.empty();
+            if (kind == BinaryAuthDataProvider.class || kind == BinaryAuthChallengeHandler.class) {
+                // Both are always advertised, because in v4 every plugin could authenticate a binary
+                // connection: the client called authenticate(INIT_AUTH_DATA) and sent whatever came back,
+                // empty included, and answered any challenge through the same provider. Gating either on a
+                // probe would refuse connections v4 accepted — a plugin whose credential is presented at
+                // the TLS layer reports no command data yet still has to connect. The probe below therefore
+                // decides only the HTTP capability, which has no such universal fallback.
+                return Optional.of(kind.cast(this));
             }
             if (kind == HttpAuthHeadersProvider.class) {
                 return supportsHttp ? Optional.of(kind.cast(this)) : Optional.empty();
@@ -320,12 +361,33 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
         public CompletableFuture<BinaryAuthData> getAuthDataAsync(AuthenticationCallContext callContext) {
             return supplyOffloaded(() -> {
                 AuthenticationDataProvider d = v4.getAuthData(callContext.brokerHost());
-                if (d == null || !d.hasDataFromCommand() || d.getCommandData() == null) {
+                if (d == null) {
                     throw new PulsarClientException.UnsupportedAuthenticationException(
-                            "v4 plugin " + v4.getClass().getName() + " provided no binary-protocol command "
-                                    + "credential (hasDataFromCommand()/getCommandData() returned nothing)");
+                            "v4 plugin " + v4.getClass().getName() + " returned no AuthenticationDataProvider");
+                }
+                // The provider is retained for this exchange so a following challenge round continues the
+                // same conversation, and the initial credential comes from authenticate(INIT_AUTH_DATA) —
+                // verbatim what the v4 client did. Its default implementation returns getCommandData(), so a
+                // single-pass plugin is unaffected, while a challenge/response plugin (which serves its
+                // first frame only through authenticate) keeps working.
+                callContext.setStateObject(AuthenticationDataProvider.class, d);
+                AuthData initial = d.authenticate(AuthData.INIT_AUTH_DATA);
+                return new BinaryAuthData(initial == null ? new byte[0] : initial.getBytes());
+            });
+        }
+
+        @Override
+        public CompletableFuture<ChallengeResponse> respondToChallengeAsync(AuthenticationCallContext callContext,
+                AuthChallenge challenge) {
+            return supplyOffloaded(() -> {
+                AuthenticationDataProvider d = callContext.getStateObject(AuthenticationDataProvider.class)
+                        .orElse(null);
+                if (d == null) {
+                    d = v4.getAuthData(callContext.brokerHost());
+                    callContext.setStateObject(AuthenticationDataProvider.class, d);
                 }
-                return new BinaryAuthData(d.getCommandData().getBytes(UTF_8));
+                AuthData response = d.authenticate(AuthData.of(challenge.bytes()));
+                return new ChallengeResponse(response == null ? null : response.getBytes());
             });
         }
 
@@ -357,8 +419,9 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
     static final class LegacyV4ChallengeResponseAdapter extends LegacyV4AuthenticationAdapter
             implements BinaryAuthDataProvider, BinaryAuthChallengeHandler {
 
-        LegacyV4ChallengeResponseAdapter(org.apache.pulsar.client.api.Authentication v4) {
-            super(v4);
+        LegacyV4ChallengeResponseAdapter(org.apache.pulsar.client.api.Authentication v4,
+                boolean ownsV4Lifecycle) {
+            super(v4, ownsV4Lifecycle);
         }
 
         @Override
@@ -401,9 +464,11 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
     static final class LegacyV4TlsAdapter extends TlsAuthentication {
 
         private final org.apache.pulsar.client.api.Authentication v4;
+        private final boolean ownsV4Lifecycle;
 
-        LegacyV4TlsAdapter(org.apache.pulsar.client.api.Authentication v4) {
+        LegacyV4TlsAdapter(org.apache.pulsar.client.api.Authentication v4, boolean ownsV4Lifecycle) {
             this.v4 = v4;
+            this.ownsV4Lifecycle = ownsV4Lifecycle;
         }
 
         @Override
@@ -422,10 +487,12 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
          */
         @Override
         public CompletableFuture<Void> initializeAsync(AuthenticationInitContext initContext) {
-            try {
-                v4.start();
-            } catch (Exception e) {
-                return CompletableFuture.failedFuture(e);
+            if (ownsV4Lifecycle) {
+                try {
+                    v4.start();
+                } catch (Exception e) {
+                    return CompletableFuture.failedFuture(e);
+                }
             }
             return super.initializeAsync(initContext);
         }
@@ -438,6 +505,9 @@ public abstract class LegacyV4AuthenticationAdapter implements Authentication {
          */
         @Override
         public void close() throws Exception {
+            if (!ownsV4Lifecycle) {
+                return;
+            }
             try {
                 v4.close();
             } finally {
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5AuthenticationLoader.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5AuthenticationLoader.java
index 509944053de0..3c7d09dfae7d 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5AuthenticationLoader.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5AuthenticationLoader.java
@@ -22,6 +22,7 @@ import java.io.IOException;
 import java.util.Map;
 import org.apache.pulsar.client.api.PulsarClientException;
 import org.apache.pulsar.client.api.v5.auth.Authentication;
+import org.apache.pulsar.client.api.v5.internal.V5AuthenticationProvider;
 import org.apache.pulsar.client.impl.AuthenticationUtil;
 
 /**
@@ -78,6 +79,23 @@ public final class V5AuthenticationLoader {
         return LegacyV4AuthenticationAdapter.wrap(AuthenticationUtil.create(authPluginClassName, authParams));
     }
 
+    /**
+     * The v5 {@link Authentication} to drive for an already-configured, already-started v4 plugin.
+     *
+     * <p>This is the client's translation rule, in one place because both the client and its tests must
+     * apply it identically. A built-in shim hands over its v5-native body — no bridge, and no executor hop
+     * for a credential it already holds. Anything else is wrapped by {@link LegacyV4AuthenticationAdapter}
+     * in its already-started form, since the caller owns the v4 plugin's lifecycle.
+     *
+     * @param v4 the already-configured, already-started v4 authentication plugin
+     * @return the v5 authentication to drive
+     */
+    public static Authentication forStartedV4Plugin(org.apache.pulsar.client.api.Authentication v4) {
+        return v4 instanceof V5AuthenticationProvider provider
+                ? provider.v5Authentication()
+                : LegacyV4AuthenticationAdapter.wrapAlreadyStarted(v4);
+    }
+
     /**
      * The class named by {@code authPluginClassName} when it is a v5-native {@link Authentication}, else
      * {@code null}. A blank name, a class that cannot be loaded, or a legacy v4 class all return
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5BinaryAuthenticationDriver.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5BinaryAuthenticationDriver.java
index 578d9dd7718c..7421926f2398 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5BinaryAuthenticationDriver.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/auth/v5/V5BinaryAuthenticationDriver.java
@@ -137,6 +137,11 @@ public final class V5BinaryAuthenticationDriver implements AsyncAuthenticationDr
     private record InitGatedExchange(CompletableFuture<Void> initialization, AuthenticationExchange delegate)
             implements AuthenticationExchange {
 
+        @Override
+        public String authMethodName() {
+            return delegate.authMethodName();
+        }
+
         @Override
         public CompletableFuture<AuthData> getAuthDataAsync() {
             return initialization.thenCompose(ignored -> delegate.getAuthDataAsync());
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/conf/ClientConfigurationData.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/conf/ClientConfigurationData.java
index 6753f6ef8d97..bbe9999045a5 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/conf/ClientConfigurationData.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/conf/ClientConfigurationData.java
@@ -43,6 +43,7 @@ import org.apache.pulsar.client.api.Authentication;
 import org.apache.pulsar.client.api.ProxyProtocol;
 import org.apache.pulsar.client.api.ServiceUrlProvider;
 import org.apache.pulsar.client.api.Socks5ProxyScope;
+import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver;
 import org.apache.pulsar.client.impl.auth.AuthenticationDisabled;
 import org.apache.pulsar.client.util.Secret;
 import org.apache.pulsar.tls.PulsarTlsFactory;
@@ -248,6 +249,26 @@ public class ClientConfigurationData implements Serializable, Cloneable {
     @JsonIgnore
     private transient Map<String, String> tlsFactoryParams;
 
+    // PIP-478: the authentication the client actually drives. The client drives the v5 model natively, so
+    // this is resolved once at client construction — from the v5 builder when it configured a v5 plugin,
+    // otherwise from the v4 `authentication` slot above (a built-in shim hands over its v5-native body; any
+    // other v4 plugin is wrapped by LegacyV4AuthenticationAdapter).
+    //
+    // The v4 slot deliberately stays populated and authoritative for everything that is not the credential
+    // exchange: folding an auth plugin's TLS material into the client's TLS policy keys off the concrete v4
+    // type (AuthenticationTls / AuthenticationKeyStoreTls / AuthenticationOAuth2), which the v5 SPI has no
+    // carrier for. Emptying it would silently drop the client certificate and surface only as a 401.
+    //
+    // Transient, like the TLS seam above: a v5 plugin is not Serializable, and a shallow clone() keeps the
+    // reference so a cloned configuration drives the same authentication.
+    @JsonIgnore
+    private transient org.apache.pulsar.client.api.v5.auth.Authentication v5Authentication;
+    // The per-client authentication session: the resolved body plus its memoized one-shot initialization,
+    // from which ClientCnx opens one exchange per connection attempt. Resolved by PulsarClientImpl; null
+    // until then (and for a configuration that never builds a client).
+    @JsonIgnore
+    private transient AsyncAuthenticationDriver v5AuthenticationDriver;
+
     @Schema(
             name = "concurrentLookupRequest",
             description = "The number of concurrent lookup requests that can be sent on each broker connection. "
diff --git a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientCnxAsyncAuthTest.java b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientCnxAsyncAuthTest.java
index da7a1174f13a..22ec39ab39ab 100644
--- a/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientCnxAsyncAuthTest.java
+++ b/pulsar-client/src/test/java/org/apache/pulsar/client/impl/ClientCnxAsyncAuthTest.java
@@ -49,7 +49,10 @@ import org.apache.pulsar.client.api.Authentication;
 import org.apache.pulsar.client.api.PulsarClientException;
 import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver;
 import org.apache.pulsar.client.api.internal.AsyncAuthenticationDriver.AuthenticationExchange;
+import org.apache.pulsar.client.api.v5.internal.V5AuthenticationProvider;
 import org.apache.pulsar.client.impl.auth.AuthenticationToken;
+import org.apache.pulsar.client.impl.auth.v5.V5AuthenticationLoader;
+import org.apache.pulsar.client.impl.auth.v5.V5BinaryAuthenticationDriver;
 import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
 import org.apache.pulsar.client.impl.metrics.InstrumentProvider;
 import org.apache.pulsar.common.api.AuthData;
@@ -118,17 +121,21 @@ public class ClientCnxAsyncAuthTest {
         conf.setKeepAliveIntervalSeconds(0);
         conf.setOperationTimeoutMs(operationTimeoutMs);
         conf.setAuthentication(auth);
+        // PIP-478: the client drives the v5 model, so ClientCnx takes its exchanges from the resolved
+        // authentication driver rather than from the v4 plugin in conf.
+        conf.setV5AuthenticationDriver(auth instanceof AsyncAuthenticationDriver driver ? driver
+                : new V5BinaryAuthenticationDriver(V5AuthenticationLoader.forStartedV4Plugin(auth)));
         ClientCnx cnx = new ClientCnx(InstrumentProvider.NOOP, conf, eventLoop);
         cnx.setRemoteHostName("localhost");
         return cnx;
     }
 
     private ClientCnx connectedCnx(Supplier<String> tokenSupplier) throws Exception {
-        // A real async-capable built-in plugin (AuthenticationToken implements AsyncAuthenticationDriver via
-        // its v5-native body). With no bound framework services its credential resolves inline, so the
-        // connect continuation runs synchronously on the calling thread.
+        // A real built-in plugin: AuthenticationToken hands over its v5-native body, which the client drives
+        // directly. With no bound framework services its credential resolves inline, so the connect
+        // continuation runs synchronously on the calling thread.
         AuthenticationToken auth = new AuthenticationToken(tokenSupplier);
-        assertThat(auth).isInstanceOf(AsyncAuthenticationDriver.class);
+        assertThat(auth).isInstanceOf(V5AuthenticationProvider.class);
         ClientCnx cnx = newCnx(auth);
         cnx.channelActive(ctx);
         return cnx;
@@ -485,6 +492,11 @@ public class ClientCnxAsyncAuthTest {
 
     private static final class ControllableExchange implements AuthenticationExchange {
 
+        @Override
+        public String authMethodName() {
+            return "controllable";
+        }
+
         private final CompletableFuture<AuthData> authData = new CompletableFuture<>();
         private final CompletableFuture<AuthData> challengeResponse = new CompletableFuture<>();
 
@@ -530,6 +542,11 @@ public class ClientCnxAsyncAuthTest {
         @Override
         public AuthenticationExchange newAuthenticationExchange(String brokerHostName) {
             return new AuthenticationExchange() {
+                @Override
+                public String authMethodName() {
+                    return "always-responding";
+                }
+
                 @Override
                 public CompletableFuture<AuthData> getAuthDataAsync() {
                     return CompletableFuture.completedFuture(AuthData.of("init".getBytes(UTF_8)));
diff --git a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ProxyClientCnx.java b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ProxyClientCnx.java
index 86e14e5c259f..e7572737f27b 100644
--- a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ProxyClientCnx.java
+++ b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/ProxyClientCnx.java
@@ -71,7 +71,7 @@ public class ProxyClientCnx extends ClientCnx {
             // authentication data.
             clientAuthData = proxyConnection.getClientAuthData();
         }
-        return Commands.newConnect(authentication.getAuthMethodName(), authData, protocolVersion,
+        return Commands.newConnect(authMethodName(), authData, protocolVersion,
                 proxyConnection.clientVersion, proxyToTargetBrokerAddress, clientAuthRole, clientAuthData,
                 clientAuthMethod, PulsarVersion.getVersion(), null);
     }
diff --git a/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyTest.java b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyTest.java
index cf450dfc0c95..e9df49acd944 100644
--- a/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyTest.java
+++ b/pulsar-proxy/src/test/java/org/apache/pulsar/proxy/server/ProxyTest.java
@@ -529,7 +529,7 @@ public class ProxyTest extends MockedPulsarServiceBaseTest {
                     @Override
                     protected ByteBuf buildConnectCommand(AuthData authData) throws Exception {
                         BaseCommand cmd =
-                                Commands.newConnectWithoutSerialize(authentication.getAuthMethodName(), authData,
+                                Commands.newConnectWithoutSerialize(authMethodName(), authData,
                                         this.protocolVersion, clientVersion, proxyToTargetBrokerAddress,
                                         null, null, null, null, null);
                         FeatureFlags featureFlags = cmd.getConnect().getFeatureFlags();