GV

GeezerVison

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

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

On this site

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

This view

  • Original page
  • New address

GeezerVison is showing github.com — [fix][proxy] PIP-478: resolve the proxy's broker-client credential of… · apache/pulsar@7e9edb8

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pip
    • pip-478.md
  • pulsar-proxy/src
    • main/java/org/apache/pulsar/proxy/server
      • DirectProxyHandler.java
      • ProxyService.java
    • test/java/org/apache/pulsar/proxy/server
      • DirectProxyHandlerAuthTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pip/pip-478.md‎

Copy file name to clipboardExpand all lines: pip/pip-478.md
+1-1Lines changed: 1 addition & 1 deletion
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ This PIP introduces new API and implementation across the existing `pulsar-clien
142142

143143
- **Non-Java client SDKs.** Each non-Java SDK (Python, Go, C++, Node.js) follows its own auth model and will be addressed by per-SDK PIPs.
144144

145-
- **Off-loading the proxy's own broker-client credential I/O (known gap).** Motivation #1's event-loop-safety guarantee is delivered for `PulsarClient` / `PulsarAdmin` (and the broker's outbound clients, which are genuine clients that bind the framework's `ClientAuthenticationServices`). The **proxy's** connection to the broker is not a `PulsarClientImpl`: its lookup path uses a bare `ConnectionPool` and its data path a hand-rolled Netty `DirectProxyHandler`, and neither binds the client auth services (bounded blocking executor, framework HTTP client factory). On the proxy's **lookup** path the credential no longer runs on that loop: `ClientCnx` resolves and memoizes a binary authentication driver for a configuration that no `PulsarClient` owns, and with no services bound the credential call falls back to the framework's process-wide shared blocking pool. What remains is the **data** path: `DirectProxyHandler` resolves the credential inline on the proxy's Netty loop, on connect and on the broker's refresh sentinel — **the same behavior as v4, not a regression introduced by this PIP**. Closing it requires an async rework of that inline `getAuthData()`; the lookup leg additionally still runs without the framework HTTP client factory and on a shared library-owned pool rather than a client-owned bounded executor, which is why reordering proxy startup (the broker-client `Authentication` is created and started before the proxy's event loop, DNS resolver, and TLS factory exist) is still part of the follow-up. Both are deferred rather than bundled into this change.
145+
- **Binding the proxy's broker-client legs to client-owned services (known gap).** Motivation #1's event-loop-safety guarantee is delivered for `PulsarClient` / `PulsarAdmin` (and the broker's outbound clients, which are genuine clients that bind the framework's `ClientAuthenticationServices`). The **proxy's** connection to the broker is not a `PulsarClientImpl`: its lookup path uses a bare `ConnectionPool` and its data path a hand-rolled Netty `DirectProxyHandler`, and neither binds the client auth services (bounded blocking executor, framework HTTP client factory). On the proxy's **lookup** path the credential no longer runs on that loop: `ClientCnx` resolves and memoizes a binary authentication driver for a configuration that no `PulsarClient` owns, and with no services bound the credential call falls back to the framework's process-wide shared blocking pool. The **data** path is off-loaded too: `DirectProxyHandler` opens a per-connection exchange on a `ProxyService`-owned `V5BinaryAuthenticationDriver` and resolves the credential through it — on connect and on the broker's refresh sentinel alike — dispatching the continuation back to the channel's event loop, with challenge rounds strictly serialized (a non-refresh challenge arriving while a round is in flight is dropped) and bounded by the same round cap `ClientCnx` uses. What remains deferred: neither proxy leg binds the framework HTTP client factory, both run credential work on the shared library-owned pool rather than a client-owned bounded executor, and reordering proxy startup (the broker-client `Authentication` is created and started before the proxy's event loop, DNS resolver, and TLS factory exist) is still follow-up work.
146146

147147
- **The broader FIPS-compliance mode.** This PIP covers the **TLS-transport** requirements for FIPS: a configurable TLS engine (JDK, not native BoringSSL) wired through every component plus the two configurable provider axes (Motivation #4, Goal #5). It does **not** define a full FIPS-mode profile: FIPS-approved algorithms in message encryption (key-wrap) and authentication (password hashing, token signing), a FIPS distribution/packaging variant (shipping `bc-fips` and excluding non-validated `bcprov` / `netty-tcnative-boringssl` / Conscrypt), and a fail-fast `fipsMode` validation switch are a **separate effort** — Pulsar-wide in scope and independent of this SPI. Concretely, the shipped `pulsar-server` distribution today bundles the **non-FIPS** BouncyCastle provider (`bcprov-jdk18on` / `bcpkix-jdk18on`) and explicitly excludes `bc-fips`, and it ships no `bctls-fips` (the jar registering `BCJSSE`) at all; because the two BouncyCastle families declare the same `org.bouncycastle.*` classes under different signers they cannot coexist on one classpath, so until that packaging effort lands a FIPS deployment assembles the provider classpath itself. The in-tree `pulsar-client-test-bcfips` module assembles a classpath that way — excluding the non-FIPS BouncyCastle jars in favour of `bc-fips` — but it covers the crypto side only: it ships no `bctls-fips` and sets neither provider key, so it is not an end-to-end FIPS TLS test. This PIP deliberately provides only the TLS-transport configurability those deployments require, so the two efforts compose without one blocking the other.
148148

Collapse file

‎pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/DirectProxyHandler.java‎

Copy file name to clipboardExpand all lines: pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/DirectProxyHandler.java
+145-35Lines changed: 145 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,15 @@
4242
import io.netty.util.CharsetUtil;
4343
import java.net.InetSocketAddress;
4444
import java.util.Arrays;
45+
import java.util.concurrent.CompletableFuture;
4546
import java.util.concurrent.TimeUnit;
47+
import java.util.function.Function;
4648
import lombok.CustomLog;
4749
import lombok.Getter;
4850
import lombok.SneakyThrows;
4951
import org.apache.pulsar.PulsarVersion;
5052
import org.apache.pulsar.client.api.Authentication;
51-
import org.apache.pulsar.client.api.AuthenticationDataProvider;
52-
import org.apache.pulsar.client.api.PulsarClientException;
53+
import org.apache.pulsar.client.impl.auth.v5.BinaryAuthenticationDriver.AuthenticationExchange;
5354
import org.apache.pulsar.common.allocator.PulsarByteBufAllocator;
5455
import org.apache.pulsar.common.api.AuthData;
5556
import org.apache.pulsar.common.api.proto.BaseCommand;
@@ -61,6 +62,7 @@
6162
import org.apache.pulsar.common.protocol.PulsarDecoder;
6263
import org.apache.pulsar.common.stats.Rate;
6364
import org.apache.pulsar.common.tls.impl.TlsContextAcquisition;
65+
import org.apache.pulsar.common.util.FutureUtil;
6466
import org.apache.pulsar.common.util.netty.NettyChannelUtil;
6567

6668
@CustomLog
@@ -79,8 +81,13 @@ public class DirectProxyHandler {
7981
private final String clientAuthMethod;
8082
public static final String TLS_HANDLER = "tls";
8183

84+
// PIP-478: hard cap on broker challenge rounds within a single binary authentication exchange, mirroring
85+
// ClientCnx.MAX_AUTH_CHALLENGE_ROUNDS (both in turn mirror HttpAuthenticationDriver.MAX_CHALLENGE_ROUNDS).
86+
// A broker that answers every CommandAuthResponse with another challenge would otherwise loop against the
87+
// proxy forever, and each round now also schedules credential work onto a blocking pool.
88+
static final int MAX_AUTH_CHALLENGE_ROUNDS = 10;
89+
8290
private final Authentication authentication;
83-
private AuthenticationDataProvider authenticationDataProvider;
8491
private final ProxyService service;
8592
private final Runnable onHandshakeCompleteAction;
8693
final boolean tlsEnabledWithBroker;
@@ -259,6 +266,18 @@ public class ProxyBackendHandler extends PulsarDecoder {
259266
private final ProxyConfiguration config;
260267
private final int protocolVersion;
261268
private final FeatureFlags featureFlags;
269+
// PIP-478: the v5 exchange this backend connection authenticates through. Replaced on a broker-pushed
270+
// REFRESH, which starts a fresh exchange. Only ever touched on this channel's event loop.
271+
private AuthenticationExchange authExchange;
272+
// PIP-478: round state. AuthenticationExchange is single-round and non-thread-safe, and serializing
273+
// its rounds is the caller's obligation; this class is its second caller after ClientCnx. While the
274+
// frame decoder is still running (state Init) two challenge frames arriving in one read reach
275+
// handleAuthChallenge in the same event-loop turn, before either resolution has completed, and would
276+
// otherwise drive the same exchange concurrently. Both fields are touched only on this channel's
277+
// event loop (channelActive, handleAuthChallenge, and the continuations dispatched there), so they
278+
// need no synchronization.
279+
private boolean authRoundInProgress;
280+
private int authChallengeRounds;
262281

263282
public ProxyBackendHandler(ProxyConfiguration config, int protocolVersion, String remoteHostName,
264283
FeatureFlags featureFlags) {
@@ -275,16 +294,76 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception {
275294
if (config.isHaProxyProtocolEnabled()) {
276295
writeHAProxyMessage();
277296
}
278-
279-
// Send the Connect command to broker
280-
authenticationDataProvider = authentication.getAuthData(remoteHostName);
281-
AuthData authData = authenticationDataProvider.authenticate(AuthData.INIT_AUTH_DATA);
282-
ByteBuf command = Commands.newConnect(
283-
authentication.getAuthMethodName(), authData, protocolVersion,
284-
proxyConnection.clientVersion, null /* target broker */,
285-
originalPrincipal, clientAuthData, clientAuthMethod, PulsarVersion.getVersion(), featureFlags);
286-
writeAndFlush(command);
287297
isTlsOutboundChannel = ProxyConnection.isTlsChannel(inboundChannel);
298+
299+
// Send the Connect command to broker. PIP-478: the credential is resolved through a v5 exchange
300+
// rather than by calling the v4 plugin here. This method runs on the Netty event loop, and the v4
301+
// call it used to make is arbitrary plugin code — an OAuth2 token endpoint round trip, an Athenz
302+
// ZTS fetch, a GSSAPI exchange with the KDC — which stalled every connection multiplexed onto
303+
// that loop for its duration. The exchange's calls always off-load.
304+
//
305+
// The auth method name is read from the v4 plugin here and in handleAuthChallenge below, where
306+
// ClientCnx instead takes it from the exchange that produced the credential. Both are correct for
307+
// the proxy — it owns one started plugin, and the bridge's authMethodName() delegates straight to
308+
// it — and reading it from the plugin does not depend on a round having completed. Deliberate.
309+
authExchange = service.getProxyClientAuthenticationDriver().newAuthenticationExchange(remoteHostName);
310+
sendWhenResolved(authExchange.getAuthDataAsync(),
311+
authData -> Commands.newConnect(
312+
authentication.getAuthMethodName(), authData, protocolVersion,
313+
proxyConnection.clientVersion, null /* target broker */,
314+
originalPrincipal, clientAuthData, clientAuthMethod, PulsarVersion.getVersion(),
315+
featureFlags),
316+
"connect");
317+
}
318+
319+
/**
320+
* Send a command built from an asynchronously-resolved credential (PIP-478).
321+
*
322+
* <p>The continuation is dispatched onto this channel's event loop, so the command is built and
323+
* written there whether the credential was already in memory or needed I/O — command ordering on the
324+
* channel is therefore unchanged from the synchronous version. A failure closes the backend channel:
325+
* the proxy has no credential to send, and leaving the connection open would wait out the broker's
326+
* timeout instead of letting the client retry. That covers a failure to build the command too, not
327+
* just a failure to resolve the credential.
328+
*
329+
* <p>This is where an authentication round begins: the round is marked in progress so that a
330+
* challenge arriving before it completes is dropped rather than re-entering the exchange
331+
* concurrently.
332+
*
333+
* @param resolution the credential being resolved
334+
* @param commandBuilder builds the command to send from the resolved credential
335+
* @param what what is being authenticated, for logging
336+
*/
337+
private void sendWhenResolved(CompletableFuture<AuthData> resolution,
338+
Function<AuthData, ByteBuf> commandBuilder, String what) {
339+
authRoundInProgress = true;
340+
// The future returned by whenCompleteAsync is intentionally discarded: the continuation handles
341+
// every outcome itself, and the only way that future fails is ctx.executor() rejecting during
342+
// event-loop shutdown — at which point the channel is already going away.
343+
resolution.whenCompleteAsync((authData, throwable) -> {
344+
authRoundInProgress = false;
345+
if (throwable != null) {
346+
Throwable cause = FutureUtil.unwrapCompletionException(throwable);
347+
log.error().attr("channel", ctx.channel()).attr("stage", what).exception(cause)
348+
.log("Failed to resolve the proxy's broker-client credential");
349+
ctx.close();
350+
return;
351+
}
352+
if (!ctx.channel().isActive()) {
353+
// The backend connection went away while the credential was resolving. Logged so that
354+
// "backend connected but never sent CommandConnect" is diagnosable rather than silent.
355+
log.debug().attr("channel", ctx.channel()).attr("stage", what)
356+
.log("Backend channel closed while the proxy's broker-client credential resolved");
357+
return;
358+
}
359+
try {
360+
writeAndFlush(commandBuilder.apply(authData));
361+
} catch (Throwable t) {
362+
log.error().attr("channel", ctx.channel()).attr("stage", what).exception(t)
363+
.log("Failed to send the proxy's broker-client authentication command");
364+
ctx.close();
365+
}
366+
}, ctx.executor());
288367
}
289368

290369
@Override
@@ -345,37 +424,68 @@ protected void handleAuthChallenge(CommandAuthChallenge authChallenge) {
345424
checkArgument(authChallenge.hasChallenge());
346425
checkArgument(authChallenge.getChallenge().hasAuthData() && authChallenge.getChallenge().hasAuthData());
347426

348-
if (Arrays.equals(AuthData.REFRESH_AUTH_DATA_BYTES, authChallenge.getChallenge().getAuthData())) {
349-
try {
350-
authenticationDataProvider = authentication.getAuthData(remoteHostName);
351-
} catch (PulsarClientException e) {
352-
log.error().attr("channel", ctx.channel())
353-
.exception(e)
354-
.log("Error refreshing authentication data provider");
355-
return;
427+
// PIP-478 binary routing rule 2: the broker's REFRESH sentinel restarts authentication with a
428+
// fresh exchange whose getAuthDataAsync() re-produces the current credential, rather than being
429+
// routed into the conversation it just terminated. Any other challenge is a round of the current
430+
// exchange, whose state slot carries conversation state across rounds. This mirrors ClientCnx.
431+
// The REFRESH branch is conformance with that rule rather than a path the broker can reach here:
432+
// this handler stops decoding once state == HandshakeCompleted, and the broker arms its refresh
433+
// task with an initial delay of authenticationRefreshCheckSeconds after connect completes, so by
434+
// the time a REFRESH is pushed it is proxied straight through to the client, which answers it.
435+
// The proxy's own credential refresh lives in ProxyConnection, not here.
436+
boolean refresh =
437+
Arrays.equals(AuthData.REFRESH_AUTH_DATA_BYTES, authChallenge.getChallenge().getAuthData());
438+
// PIP-478 (serialize-or-drop): a broker never pipelines challenges — it waits for each
439+
// CommandAuthResponse — so a challenge arriving while a round is still in flight is anomalous,
440+
// and servicing it would re-enter the same single-round, non-thread-safe exchange concurrently.
441+
// Dropping it makes rounds strictly serialized, which is why this class needs none of the
442+
// generation guarding ClientCnx carries: nothing here can supersede an in-flight round. ClientCnx
443+
// does need it, because it lets a REFRESH supersede one; the proxy can drop a REFRESH instead,
444+
// both because it cannot reach this handler and because the broker's refresh check is a
445+
// scheduleAtFixedRate task that would re-send it on the next tick.
446+
if (authRoundInProgress) {
447+
log.debug().attr("channel", ctx.channel())
448+
.log("Dropping a broker auth challenge received while an auth round is in progress");
449+
return;
450+
}
451+
// Bound the exchange. A REFRESH opens a fresh exchange, so it resets the counter; any other
452+
// challenge counts towards the cap.
453+
if (refresh) {
454+
authChallengeRounds = 0;
455+
} else if (++authChallengeRounds > MAX_AUTH_CHALLENGE_ROUNDS) {
456+
log.error().attr("channel", ctx.channel()).attr("maxChallengeRounds", MAX_AUTH_CHALLENGE_ROUNDS)
457+
.log("Binary authentication exceeded the maximum challenge rounds; closing the "
458+
+ "broker connection");
459+
ctx.close();
460+
return;
461+
}
462+
CompletableFuture<AuthData> resolution;
463+
try {
464+
if (refresh) {
465+
authExchange =
466+
service.getProxyClientAuthenticationDriver().newAuthenticationExchange(remoteHostName);
467+
resolution = authExchange.getAuthDataAsync();
468+
} else {
469+
resolution = authExchange
470+
.authenticateAsync(AuthData.of(authChallenge.getChallenge().getAuthData()));
356471
}
472+
} catch (Throwable t) {
473+
// One try/catch so a plugin that throws synchronously fails the connection rather than
474+
// propagating up the event loop.
475+
resolution = CompletableFuture.failedFuture(t);
357476
}
358477

359478
// mutual authn. If auth not complete, continue auth; if auth complete, complete connectionFuture.
360-
try {
361-
AuthData authData = authenticationDataProvider
362-
.authenticate(AuthData.of(authChallenge.getChallenge().getAuthData()));
363-
479+
sendWhenResolved(resolution, authData -> {
364480
checkState(!authData.isComplete());
365-
366-
ByteBuf request = Commands.newAuthResponse(authentication.getAuthMethodName(),
367-
authData,
368-
this.protocolVersion,
369-
PulsarVersion.getVersion());
370-
371481
log.debug().attr("channel", ctx.channel())
372482
.attr("authMethod", authentication.getAuthMethodName())
373483
.log("Mutual auth");
374-
375-
writeAndFlush(request);
376-
} catch (Exception e) {
377-
log.error().exception(e).log("Error mutual verify");
378-
}
484+
return Commands.newAuthResponse(authentication.getAuthMethodName(),
485+
authData,
486+
this.protocolVersion,
487+
PulsarVersion.getVersion());
488+
}, "challenge");
379489
}
380490

381491
@Override

0 commit comments

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