You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by "lhotari (via GitHub)" <gi...@apache.org> on 2026/08/04 19:05:16 UTC
[PR] [feat][misc] PIP-478: default file-based TLS factory implementation [pulsar]
lhotari opened a new pull request, #26271:
URL: https://github.com/apache/pulsar/pull/26271
PIP: #25890 ([`pip/pip-478.md`](https://github.com/apache/pulsar/blob/master/pip/pip-478.md))
### Motivation
This is the **second implementation PR** for [PIP-478](https://github.com/apache/pulsar/pull/25890), following #26222 which landed the two SPI modules (`pulsar-tls-factory-api`, `pulsar-http-client-api`). It adds the **default implementation** of the `PulsarTlsFactory` SPI and the JDK-level TLS primitives it is built from.
The PR is **additive**: the PIP-337 stack (`PulsarSslFactory`, `DefaultPulsarSslFactory`, `JettySslContextFactory`, `SecurityUtility`, `KeyStoreSSLContext`) still exists and remains the wired implementation, and the new code is exercised only by its own unit tests. **There is no behavioural change to any existing module.** Wiring the new factory into the client and the server components, and removing the superseded PIP-337 classes, are later PRs in the series.
### Modifications
**`pulsar-common` — `org.apache.pulsar.common.tls.impl`, the default factory:**
- **`FileBasedTlsFactory`** + `FileBasedTlsFactorySettings`: the default `PulsarTlsFactory`, built from PEM or keystore file material. It owns the purpose→source registry, purpose resolution (direct map lookup, then the role's terminal rule — client purposes resolve to the system default, server purposes fail the request), and the reload fan-out to subscribers.
- **`TlsMaterialSource`** / `MaterialSource` / `AuthProvidedMaterialSource` / `TlsMaterial`: per-purpose material load, watch and cache. Value equality on the loaded material suppresses spurious rebuilds when files are touched but unchanged, a failed reload keeps the last good material, and contexts are **rebuilt, never mutated in place**, so a native OpenSSL engine never observes a torn context.
- **`TlsContexts`** / `TlsContextAcquisition` / `SynthesizedEngineSslContext` / `TlsSynthesisSpec`: SSL context assembly, per-acquisition read of the current context, and `SSLParameters` companion synthesis.
- `TlsKeyStoreLoader`, `TlsFactoryProbe`, `TlsReloadMetrics`, `package-info`.
**`pulsar-common` — `org.apache.pulsar.common.util.tls`, the JDK-level primitives:**
- `PemReader` (PEM parsing), `JdkSslContexts` (JDK `SSLContext` assembly), `JcaProviders` (provider resolution), `JcaKeyStores` (`KeyStore` creation through a pinned provider). Extracted from the `SecurityUtility` grab-bag.
- Together these implement both provider axes carried by `TlsPolicy`: **`jsseProvider`** pins the `SSLContext` / `KeyManagerFactory` / `TrustManagerFactory`, and **`jcaProvider`** pins the `KeyStore` / `CertificateFactory` / `KeyFactory` engines that parse the material. Both are unset by default, which is exactly today's behaviour.
- `KeyStoreHolder` gains an optional pinned JCA provider and, on that path only, a random per-instance entry password (a FIPS provider in approved-only mode rejects an empty password-based-KDF password). With no pinned provider its behaviour is unchanged.
**`pulsar-broker-common`:**
- `broker/tls/DefaultBrokerTlsFactory` + `TlsFactorySupport`: the default broker-side factory, composed from the **existing** base `tls*` fields of `ServiceConfiguration`. No new configuration keys are added in this PR — those arrive with the migration PR.
- `jetty/tls/JettyTlsFactory`: the framework-side Jetty reload driver built on the new factory.
**Engine selection.** An unset `tlsProvider` selects Netty's `OPENSSL_REFCNT` when a `netty-tcnative` binary is available for the platform, else the JDK engine. This preserves the historical default — the PIP-337 path passes a null provider and `SslContextBuilder` then picks the native engine — while keeping the new factory off finalization: `OpenSslContext` frees its native `SSL_CTX` from a `finalize()`, which is deprecated for removal ([JEP 421](https://openjdk.org/jeps/421)) and can already be disabled with `--finalization=disabled`. Both variants expose real reference counting; this factory owns and deterministically releases every context it builds, so the finalizer only ever masked a bug. An explicitly configured engine literal is honoured verbatim.
`tlsProvider` and `webServiceTlsProvider` are now documented as the distinct axes they are — a Netty **engine** versus a Jetty **JSSE (`SSLContext`) provider** — in `ServiceConfiguration`, `ProxyConfiguration`, `broker.conf`, `standalone.conf` and `proxy.conf`. **No default values change.**
### Relationship to FIPS and to PIP-489
The main focus of this PR is the default TLS factory above. It does, however, lay the groundwork for a FIPS-compliant TLS transport, which is the subject of [PIP-489](https://github.com/apache/pulsar/pull/26155) ([discussion](https://lists.apache.org/thread/cq6v9z2wszb6lsorvl0nbj85sc00pd6j)).
PIP-489's own Goals section states that it delivers a FIPS-capable TLS transport **by building on PIP-478** rather than defining a parallel TLS configuration path. Because PIP-478 replaces the PIP-337 `PulsarSslFactory` / `PulsarSslConfiguration` surface outright in 5.0, parts of the PIP-489 design that are written against that surface — the per-listener `.tlsProvider(...)` wiring gaps in `PulsarChannelInitializer`, `WebService`, the WebSocket proxy and the function worker — **become obsolete on `master`**: those call sites do not survive the migration, and the equivalent capability is expressed through `TlsPolicy` and the factory instead. The remaining PIP-489 scope — the BC/BC-FIPS packaging story, the non-approved algorithms in the crypto and authentication paths, FIPS documentation, and the distribution variant — is unaffected by this PR.
The FIPS-relevant pieces here are:
- Both provider axes are implemented, including the key/trust-manager algorithm negotiation a FIPS JSSE provider needs (BCJSSE registers `KeyManagerFactory.X.509` with a `PKIX` alias but **not** the JDK-default `SunX509`), and pinned in-memory carrier keystores so parsed key material stays inside the pinned module.
- Pulsar had **no BouncyCastle JSSE dependency at all** (see [pulsar-site#974](https://github.com/apache/pulsar-site/pull/974)). `bctls` is added to the version catalog, and `JcaProviders` registers `BCJSSE` on demand when it is the pinned `jsseProvider`: an operator-registered instance always wins, otherwise it is constructed from the classpath — in **FIPS mode bound to the FIPS JCA provider** when that is the BouncyCastle artifact present, and in the default mode otherwise. `bctls` ships no `META-INF/services/java.security.Provider` entry and its FIPS mode is a constructor argument while it registers under the plain name `BCJSSE` either way, so neither `ServiceLoader` discovery nor default construction can produce the right provider — hence the explicit registration.
- BouncyCastle is no longer mandatory: it is resolved lazily and reported as an `Optional`, so a deployment without it on the classpath still resolves named providers.
**Deliberately not in this PR:** `bctls` is a *test* dependency only, matching how `bcprov` is already scoped in `pulsar-common` (loaded reflectively in main). Which BouncyCastle artifacts land on the Pulsar classpath — selecting the non-FIPS or the FIPS jars via an environment variable in the `bin/pulsar` script, since the two cannot coexist on one classpath — will come in a **later PR**, together with the distribution and `LICENSE` wiring that implies.
### Where the rest of PIP-478 goes
Subsequent implementation PRs in this series will cover the migration itself, and with it the TLS-transport essence of PIP-489:
1. **Core migration** — the asynchronous v5 client authentication engine and its v4 compatibility bridges, plus wiring the TLS factory into every server component (broker binary listener and web service, proxy, WebSocket proxy, function worker) and the client. This introduces the new configuration surface (`tlsFactoryClassName`, `jsseProvider` / `jcaProvider` and their broker-client counterparts) and makes the new SPI the TLS path in use — which is what turns the engine and provider selection above into something an operator can actually configure end to end.
2. **Authentication plugin migration** — the Athenz and SASL plugins onto the v5 asynchronous SPI.
3. **PIP-337 removal** — deleting `PulsarSslFactory`, `SecurityUtility`, `KeyStoreSSLContext` and the deprecated CN-based hostname matching, leaving the new SPI as the only TLS path.
### Verifying this change
This change added tests and can be verified as follows:
- `FileBasedTlsFactoryTest`, `TlsMaterialSourceTest`, `AuthProvidedMaterialFoldTest` — context building, purpose resolution, rotation with keep-last-good, and rebuild-not-mutate semantics, exercised with **real in-memory TLS handshakes** (no broker, no sockets), including the OpenSSL engine path and a reference-count-reaches-zero assertion (there is no finalizer to fall back on with `OPENSSL_REFCNT`).
- `SslParametersSynthesisTest`, `TlsReloadMetricsTest` — `SSLParameters` companion synthesis and the `pulsar.tls.reload` metric.
- `JcaProviderPinningTest`, `JcaProvidersTest`, `JdkSslContextsTest` — the two provider axes: name resolution and ordering, key/trust-manager algorithm negotiation, material loading through a pinned JCA provider, that the Netty builders route their carrier keystore and manager factories through the pins rather than letting Netty build them via the JVM search order, and BCJSSE on-demand registration (including that it supplies `SSLContext.TLS` and `TrustManagerFactory.PKIX` but not `SunX509`).
- `PemReaderTest` — PEM preamble parsing across leading-line parities.
- `TlsFactorySupportTest`, `JettyTlsFactoryTest` — the broker-side scaffolding and the Jetty reload driver.
- `./gradlew :pulsar-common:test :pulsar-broker-common:test` — 1261 tests, 0 failures.
- `./gradlew assemble rat spotlessCheck checkstyleMain checkstyleTest checkBinaryLicense` passes.
### Does this pull request potentially affect one of the following parts:
*If the box was checked, please highlight the changes*
- [x] Dependencies (add or upgrade a dependency) — adds `org.bouncycastle:bctls-jdk18on` to the version catalog and as a **test** dependency of `pulsar-common`. Nothing new ships in the distribution.
- [x] The public API — adds the `org.apache.pulsar.common.tls.impl` and `org.apache.pulsar.common.util.tls` packages, and the `org.apache.pulsar.broker.tls` / `org.apache.pulsar.jetty.tls` classes. All additive and unreferenced by existing code in this PR. `KeyStoreHolder` gains one method and one constructor overload; its existing behaviour is unchanged.
- [ ] The schema
- [ ] The default values of configurations
- [ ] The threading model
- [ ] The binary protocol
- [ ] The REST endpoints
- [ ] The admin CLI options
- [ ] The metrics
- [ ] Anything that affects deployment
### Documentation
- [ ] `doc-required`
- [x] `doc-not-needed` — the new implementation is not wired to any user-facing surface yet, and the PIP-478 design document covers the design. The `tlsProvider` / `webServiceTlsProvider` comments in the shipped `conf/*.conf` files are updated here to describe the two provider axes accurately; no website documentation change is needed.
- [ ] `doc`
- [ ] `doc-complete`
### Matching PR in forked repository
PR in forked repository: https://github.com/lhotari/pulsar/pull/248 (Personal CI — full matrix green)
<sub>This PR was prepared with the assistance of Claude Code (Opus 5); the change was reviewed and is submitted by a human contributor who takes responsibility for it, per the ASF Generative Tooling guidance.</sub>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [feat][misc] PIP-478: default file-based TLS factory implementation [pulsar]
Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari merged PR #26271:
URL: https://github.com/apache/pulsar/pull/26271
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [feat][misc] PIP-478: default file-based TLS factory implementation [pulsar]
Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #26271:
URL: https://github.com/apache/pulsar/pull/26271#discussion_r3730335375
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/FileBasedTlsFactory.java:
##########
@@ -0,0 +1,835 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.util.ReferenceCountUtil;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import javax.net.ssl.SSLContext;
+import lombok.CustomLog;
+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.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsEndpoint;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The default, file-based {@link PulsarTlsFactory} (PIP-478).
+ *
+ * <p>Immutable after construction: the complete {@code TlsPurpose -> TlsPolicy} map and the
+ * factory-wide {@link FileBasedTlsFactorySettings} are fixed by the constructor and never mutated. The
+ * owning component (the v5 client builder, or {@code DefaultBrokerTlsFactory} on the server side)
+ * composes the final map before constructing the factory.
+ *
+ * <p>Natively supplies the Netty {@code SslContext} (on the configured engine — JDK or OpenSSL) and the
+ * JDK {@code SSLContext}; returns {@code empty()} for every other class (notably Jetty's
+ * {@code SslContextFactory.Server} and {@code SslContextFactory.Client}), which the framework synthesizes
+ * from the JDK {@code SSLContext}. It also
+ * returns {@code empty()} for the {@code javax.net.ssl.SSLParameters} companion (PIP-478): its engine policy
+ * (protocols, ciphers, client-auth mode, hostname verification) is baked natively into the Netty contexts it
+ * builds, so it exposes no separate baseline for the framework to overlay on those.
+ *
+ * <p>A JDK {@code SSLContext} cannot itself carry that policy — enabled protocols and cipher suites,
+ * algorithm constraints and the endpoint-identification algorithm are all per-engine {@code SSLParameters}
+ * settings — so the JDK context this factory returns is a <em>material carrier</em>: it holds the key and
+ * trust managers (built through the pinned providers) and nothing else. Every consumer of it applies the
+ * engine policy itself from the same {@link TlsPolicy}, which is what {@code JettyTlsFactory} does. A
+ * consumer that instead created engines straight from this {@code SSLContext} would get the provider defaults,
+ * so consumers must not do that.
+ *
+ * <p><b>Purpose resolution.</b> A request resolves the requested purpose directly against the configured
+ * {@code TlsPurpose -> TlsPolicy} map. When nothing is configured for the purpose, a {@code CLIENT}-role
+ * purpose resolves to the system default (OS trust store, no client certificate) and a {@code SERVER}-role
+ * purpose fails the request. A resolved-but-unbuildable request completes the future <em>exceptionally</em>
+ * — never {@code empty()}, which strictly means "unsupported {@code (purpose, class)} combination".
+ *
+ * <p><b>Rotation.</b> One {@link TlsMaterialSource} is shared per configured purpose. Server-side
+ * subscribers are pushed rebuilt instances by a background poll (interval from the settings, on the
+ * framework scheduler); client-side one-shot callers re-stat on each request and pick up rotation
+ * naturally. Because a re-stat consumes the source's change signal, an acquisition that observes a change
+ * first also fans it out to that purpose's subscribers, so a rotation is never swallowed by whoever happened
+ * to look first. A failed rebuild keeps the last-good instance, logs at WARN, and retries on the next
+ * change; a subscriber callback that throws is caught and logged, and the subscription stays live.
+ */
+@CustomLog
+public class FileBasedTlsFactory implements PulsarTlsFactory {
+
+ private final Map<TlsPurpose, RegisteredSource> registry;
+ private final FileBasedTlsFactorySettings settings;
+
+ private volatile TlsFactoryInitContext initContext;
+ private volatile TlsReloadMetrics metrics;
+ private volatile RegisteredSource systemDefaultSource;
+ private volatile ScheduledFuture<?> pollFuture;
+ private volatile boolean closed;
+ // Stands in for scheduleWithFixedDelay's no-overlap guarantee once the poll body is dispatched.
+ private final AtomicBoolean pollInFlight = new AtomicBoolean();
+
+ /**
+ * Construct an immutable file-based factory.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ this(policies, settings, Map.of());
+ }
+
+ /**
+ * Construct an immutable file-based factory that additionally folds an authentication plugin's TLS
+ * material over the configured file policy for the named purposes (the server-side {@code BROKER_CLIENT}
+ * fold — PIP-478). For a purpose present in {@code authMaterialSuppliers}, the supplier's
+ * {@code Authentication} material overrides the file policy's key/cert per
+ * {@link AuthProvidedMaterialSource} (auth-cert-wins); other purposes use the file policy unchanged.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ Objects.requireNonNull(policies, "policies must not be null");
+ this.settings = Objects.requireNonNull(settings, "settings must not be null");
+ Objects.requireNonNull(authMaterialSuppliers, "authMaterialSuppliers must not be null");
+ Map<TlsPurpose, RegisteredSource> built = new LinkedHashMap<>();
+ for (Map.Entry<TlsPurpose, TlsPolicy> entry : policies.entrySet()) {
+ TlsPurpose purpose = Objects.requireNonNull(entry.getKey(), "purpose key must not be null");
+ TlsPolicy policy = Objects.requireNonNull(entry.getValue(), "policy must not be null");
+ TlsMaterialSource fileSource = new TlsMaterialSource(policy);
+ Supplier<AuthenticationDataProvider> authSupplier = authMaterialSuppliers.get(purpose);
+ MaterialSource source = authSupplier == null
+ ? fileSource
+ : new AuthProvidedMaterialSource(fileSource, authSupplier);
+ built.put(purpose, new RegisteredSource(purpose, policy, source));
+ }
+ this.registry = Map.copyOf(built);
+ }
+
+ /**
+ * Adapt a component's broker-client {@link Authentication} to a per-refresh
+ * {@link AuthenticationDataProvider} supplier for use with the {@code BROKER_CLIENT} fold constructor.
+ * The supplier re-reads {@code getAuthData()} on each poll so credential rotation is observed; a checked
+ * {@link PulsarClientException} is rethrown unchecked and handled by the factory's keep-last-good poll.
+ *
+ * @param authentication the broker-client authentication plugin (never {@code null})
+ * @return a supplier of the plugin's current authentication data
+ */
+ public static Supplier<AuthenticationDataProvider> authMaterialSupplier(Authentication authentication) {
+ Objects.requireNonNull(authentication, "authentication must not be null");
+ return () -> {
+ try {
+ return resolveAuthData(authentication);
+ } catch (PulsarClientException e) {
+ throw new RuntimeException("Failed to obtain broker-client authentication TLS material", e);
+ }
+ };
+ }
+
+ // The BROKER_CLIENT TLS fold is host-agnostic — TLS key material does not vary by peer — so the
+ // host-less getAuthData() is exactly what we want; isolate its deprecation here.
+ @SuppressWarnings("deprecation")
+ private static AuthenticationDataProvider resolveAuthData(Authentication authentication)
+ throws PulsarClientException {
+ return authentication.getAuthData();
+ }
+
+ @Override
+ public CompletableFuture<Void> initialize(TlsFactoryInitContext context) {
+ try {
+ Objects.requireNonNull(context, "context must not be null");
+ // Required, not optional: every acquisition path in this factory reads files and parses key
+ // material. Without an executor the work would run inline on the caller's thread, which the SPI
+ // contract says may be a consumer event loop. Fail at wiring time rather than stalling a channel.
+ Objects.requireNonNull(context.blockingExecutor(),
+ "TlsFactoryInitContext.blockingExecutor() must not be null: FileBasedTlsFactory performs "
+ + "blocking file and key-material loading and must never run it on a consumer thread");
+ this.initContext = context;
+ // Cancel any poll scheduled by a prior initialize() so a second call does not orphan the first:
+ // the field is overwritten below and the old task would otherwise run forever.
+ ScheduledFuture<?> previousPoll = this.pollFuture;
+ if (previousPoll != null) {
+ previousPoll.cancel(false);
+ }
+ // Same reasoning for the metrics: a prior initialize() registered an observable gauge that stays
+ // registered on the meter until close(), so overwriting the field without closing it would leave
+ // an orphaned callback reporting stale per-purpose timestamps forever.
+ TlsReloadMetrics previousMetrics = this.metrics;
+ if (previousMetrics != null) {
+ previousMetrics.close();
+ }
+ this.metrics = TlsReloadMetrics.create(context.openTelemetry(), context.clock());
+ int interval = settings.refreshIntervalSeconds();
+ if (interval > 0 && context.scheduler() != null) {
+ // The scheduler only TRIGGERS the poll; the work runs on the blocking executor. The poll
+ // stats files, parses PEM/keystores and rebuilds contexts, which is exactly the work this
+ // method refuses to run without a blocking executor a few lines above — running it on a
+ // shared framework scheduler thread would occupy that thread for the duration, and with
+ // material on slow or network-backed storage that is not bounded by anything.
+ this.pollFuture = context.scheduler().scheduleWithFixedDelay(
+ this::triggerPoll, interval, interval, TimeUnit.SECONDS);
+ }
+ log.debug().attr("purposes", registry.keySet()).attr("refreshIntervalSeconds", interval)
+ .log("Initialized FileBasedTlsFactory");
+ return CompletableFuture.completedFuture(null);
+ } catch (Throwable t) {
+ return CompletableFuture.failedFuture(t);
+ }
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(TlsPurpose purpose, Class<T> instanceClass) {
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, TlsEndpoint endpoint, Class<T> instanceClass) {
+ // The default file-based factory serves purpose-scoped material and ignores the endpoint hint.
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, Class<T> instanceClass, Consumer<T> onLoadOrReload) {
+ if (onLoadOrReload == null) {
+ // SPI contract: argument-validation failures complete the returned future exceptionally — this
+ // method never throws on the calling thread.
+ return CompletableFuture.failedFuture(new NullPointerException("onLoadOrReload must not be null"));
+ }
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ rejectReentrantAcquisition(source, purpose);
Review Comment:
You're right, and the mutation test settles it. Fixed in 323e0cca8c9.
Your three-way analysis matches what I found. I'd add the sharpest version of it: with a direct executor — the one configuration where the guard *did* fire — the deadlock is not reachable at all, because monitors are reentrant and the nested acquisition simply succeeds inline. So the guard fired only where the hang cannot happen, and turned a working case into a failure, while leaving both real deadlocks untouched. That is worse than not having it.
The check now happens on the caller's thread, before dispatch, in both acquisition paths.
One amendment to your snippet, which I'd have shipped as another broken fix had I applied it verbatim: `resolve(purpose)` cannot be called bare on the caller thread. It is more than a registry lookup — it rejects a null purpose and throws `TlsMaterialUnavailableException` for an unconfigured server purpose, and `PulsarTlsFactory:88-90` states the SPI "never throws on the calling thread". So it moves inside a try/catch and its failure becomes a failed future too:
```java
final RegisteredSource source;
try {
source = resolve(purpose);
} catch (Throwable t) {
return CompletableFuture.failedFuture(t);
}
if (Thread.holdsLock(source)) {
return CompletableFuture.failedFuture(reentrantAcquisition(purpose));
}
return runAsync(() -> { ... });
```
Semantics are otherwise unchanged: resolve failures already surfaced as a failed future (thrown in-task), they are still excluded from `recordLoad`, and the in-task `closed` re-check under the monitor still handles the close race.
Two things the Javadoc now says that it didn't. First, that the detection must happen pre-dispatch, and why — otherwise the next person moves it back. Second, that a callback acquiring a *different* purpose avoids this deadlock but can still starve on a single-threaded blocking executor, because its task queues behind the callback whatever the monitor; the old wording called that "merely inadvisable", which understated it. It also now records that a non-blocking same-purpose acquisition is rejected as well, since the two cannot be told apart at the point of the call.
The test now uses a real single-threaded blocking executor with bounded waits, so a regression fails instead of hanging the suite, and covers a rotation delivery as well as the initial one — the original only exercised the initial delivery, which happens inside the acquisition task rather than from the poll. Verified by mutation: removing the pre-dispatch guard fails it.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/FileBasedTlsFactory.java:
##########
@@ -0,0 +1,835 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.util.ReferenceCountUtil;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import javax.net.ssl.SSLContext;
+import lombok.CustomLog;
+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.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsEndpoint;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The default, file-based {@link PulsarTlsFactory} (PIP-478).
+ *
+ * <p>Immutable after construction: the complete {@code TlsPurpose -> TlsPolicy} map and the
+ * factory-wide {@link FileBasedTlsFactorySettings} are fixed by the constructor and never mutated. The
+ * owning component (the v5 client builder, or {@code DefaultBrokerTlsFactory} on the server side)
+ * composes the final map before constructing the factory.
+ *
+ * <p>Natively supplies the Netty {@code SslContext} (on the configured engine — JDK or OpenSSL) and the
+ * JDK {@code SSLContext}; returns {@code empty()} for every other class (notably Jetty's
+ * {@code SslContextFactory.Server} and {@code SslContextFactory.Client}), which the framework synthesizes
+ * from the JDK {@code SSLContext}. It also
+ * returns {@code empty()} for the {@code javax.net.ssl.SSLParameters} companion (PIP-478): its engine policy
+ * (protocols, ciphers, client-auth mode, hostname verification) is baked natively into the Netty contexts it
+ * builds, so it exposes no separate baseline for the framework to overlay on those.
+ *
+ * <p>A JDK {@code SSLContext} cannot itself carry that policy — enabled protocols and cipher suites,
+ * algorithm constraints and the endpoint-identification algorithm are all per-engine {@code SSLParameters}
+ * settings — so the JDK context this factory returns is a <em>material carrier</em>: it holds the key and
+ * trust managers (built through the pinned providers) and nothing else. Every consumer of it applies the
+ * engine policy itself from the same {@link TlsPolicy}, which is what {@code JettyTlsFactory} does. A
+ * consumer that instead created engines straight from this {@code SSLContext} would get the provider defaults,
+ * so consumers must not do that.
+ *
+ * <p><b>Purpose resolution.</b> A request resolves the requested purpose directly against the configured
+ * {@code TlsPurpose -> TlsPolicy} map. When nothing is configured for the purpose, a {@code CLIENT}-role
+ * purpose resolves to the system default (OS trust store, no client certificate) and a {@code SERVER}-role
+ * purpose fails the request. A resolved-but-unbuildable request completes the future <em>exceptionally</em>
+ * — never {@code empty()}, which strictly means "unsupported {@code (purpose, class)} combination".
+ *
+ * <p><b>Rotation.</b> One {@link TlsMaterialSource} is shared per configured purpose. Server-side
+ * subscribers are pushed rebuilt instances by a background poll (interval from the settings, on the
+ * framework scheduler); client-side one-shot callers re-stat on each request and pick up rotation
+ * naturally. Because a re-stat consumes the source's change signal, an acquisition that observes a change
+ * first also fans it out to that purpose's subscribers, so a rotation is never swallowed by whoever happened
+ * to look first. A failed rebuild keeps the last-good instance, logs at WARN, and retries on the next
+ * change; a subscriber callback that throws is caught and logged, and the subscription stays live.
+ */
+@CustomLog
+public class FileBasedTlsFactory implements PulsarTlsFactory {
+
+ private final Map<TlsPurpose, RegisteredSource> registry;
+ private final FileBasedTlsFactorySettings settings;
+
+ private volatile TlsFactoryInitContext initContext;
+ private volatile TlsReloadMetrics metrics;
+ private volatile RegisteredSource systemDefaultSource;
+ private volatile ScheduledFuture<?> pollFuture;
+ private volatile boolean closed;
+ // Stands in for scheduleWithFixedDelay's no-overlap guarantee once the poll body is dispatched.
+ private final AtomicBoolean pollInFlight = new AtomicBoolean();
+
+ /**
+ * Construct an immutable file-based factory.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ this(policies, settings, Map.of());
+ }
+
+ /**
+ * Construct an immutable file-based factory that additionally folds an authentication plugin's TLS
+ * material over the configured file policy for the named purposes (the server-side {@code BROKER_CLIENT}
+ * fold — PIP-478). For a purpose present in {@code authMaterialSuppliers}, the supplier's
+ * {@code Authentication} material overrides the file policy's key/cert per
+ * {@link AuthProvidedMaterialSource} (auth-cert-wins); other purposes use the file policy unchanged.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ Objects.requireNonNull(policies, "policies must not be null");
+ this.settings = Objects.requireNonNull(settings, "settings must not be null");
+ Objects.requireNonNull(authMaterialSuppliers, "authMaterialSuppliers must not be null");
+ Map<TlsPurpose, RegisteredSource> built = new LinkedHashMap<>();
+ for (Map.Entry<TlsPurpose, TlsPolicy> entry : policies.entrySet()) {
+ TlsPurpose purpose = Objects.requireNonNull(entry.getKey(), "purpose key must not be null");
+ TlsPolicy policy = Objects.requireNonNull(entry.getValue(), "policy must not be null");
+ TlsMaterialSource fileSource = new TlsMaterialSource(policy);
+ Supplier<AuthenticationDataProvider> authSupplier = authMaterialSuppliers.get(purpose);
+ MaterialSource source = authSupplier == null
+ ? fileSource
+ : new AuthProvidedMaterialSource(fileSource, authSupplier);
+ built.put(purpose, new RegisteredSource(purpose, policy, source));
+ }
+ this.registry = Map.copyOf(built);
+ }
+
+ /**
+ * Adapt a component's broker-client {@link Authentication} to a per-refresh
+ * {@link AuthenticationDataProvider} supplier for use with the {@code BROKER_CLIENT} fold constructor.
+ * The supplier re-reads {@code getAuthData()} on each poll so credential rotation is observed; a checked
+ * {@link PulsarClientException} is rethrown unchecked and handled by the factory's keep-last-good poll.
+ *
+ * @param authentication the broker-client authentication plugin (never {@code null})
+ * @return a supplier of the plugin's current authentication data
+ */
+ public static Supplier<AuthenticationDataProvider> authMaterialSupplier(Authentication authentication) {
+ Objects.requireNonNull(authentication, "authentication must not be null");
+ return () -> {
+ try {
+ return resolveAuthData(authentication);
+ } catch (PulsarClientException e) {
+ throw new RuntimeException("Failed to obtain broker-client authentication TLS material", e);
+ }
+ };
+ }
+
+ // The BROKER_CLIENT TLS fold is host-agnostic — TLS key material does not vary by peer — so the
+ // host-less getAuthData() is exactly what we want; isolate its deprecation here.
+ @SuppressWarnings("deprecation")
+ private static AuthenticationDataProvider resolveAuthData(Authentication authentication)
+ throws PulsarClientException {
+ return authentication.getAuthData();
+ }
+
+ @Override
+ public CompletableFuture<Void> initialize(TlsFactoryInitContext context) {
+ try {
+ Objects.requireNonNull(context, "context must not be null");
+ // Required, not optional: every acquisition path in this factory reads files and parses key
+ // material. Without an executor the work would run inline on the caller's thread, which the SPI
+ // contract says may be a consumer event loop. Fail at wiring time rather than stalling a channel.
+ Objects.requireNonNull(context.blockingExecutor(),
+ "TlsFactoryInitContext.blockingExecutor() must not be null: FileBasedTlsFactory performs "
+ + "blocking file and key-material loading and must never run it on a consumer thread");
+ this.initContext = context;
+ // Cancel any poll scheduled by a prior initialize() so a second call does not orphan the first:
+ // the field is overwritten below and the old task would otherwise run forever.
+ ScheduledFuture<?> previousPoll = this.pollFuture;
+ if (previousPoll != null) {
+ previousPoll.cancel(false);
+ }
+ // Same reasoning for the metrics: a prior initialize() registered an observable gauge that stays
+ // registered on the meter until close(), so overwriting the field without closing it would leave
+ // an orphaned callback reporting stale per-purpose timestamps forever.
+ TlsReloadMetrics previousMetrics = this.metrics;
+ if (previousMetrics != null) {
+ previousMetrics.close();
+ }
+ this.metrics = TlsReloadMetrics.create(context.openTelemetry(), context.clock());
+ int interval = settings.refreshIntervalSeconds();
+ if (interval > 0 && context.scheduler() != null) {
+ // The scheduler only TRIGGERS the poll; the work runs on the blocking executor. The poll
+ // stats files, parses PEM/keystores and rebuilds contexts, which is exactly the work this
+ // method refuses to run without a blocking executor a few lines above — running it on a
+ // shared framework scheduler thread would occupy that thread for the duration, and with
+ // material on slow or network-backed storage that is not bounded by anything.
+ this.pollFuture = context.scheduler().scheduleWithFixedDelay(
+ this::triggerPoll, interval, interval, TimeUnit.SECONDS);
+ }
+ log.debug().attr("purposes", registry.keySet()).attr("refreshIntervalSeconds", interval)
+ .log("Initialized FileBasedTlsFactory");
+ return CompletableFuture.completedFuture(null);
+ } catch (Throwable t) {
+ return CompletableFuture.failedFuture(t);
+ }
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(TlsPurpose purpose, Class<T> instanceClass) {
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, TlsEndpoint endpoint, Class<T> instanceClass) {
+ // The default file-based factory serves purpose-scoped material and ignores the endpoint hint.
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, Class<T> instanceClass, Consumer<T> onLoadOrReload) {
+ if (onLoadOrReload == null) {
+ // SPI contract: argument-validation failures complete the returned future exceptionally — this
+ // method never throws on the calling thread.
+ return CompletableFuture.failedFuture(new NullPointerException("onLoadOrReload must not be null"));
+ }
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ rejectReentrantAcquisition(source, purpose);
+ synchronized (source) {
+ // FIX F: close() runs releaseAll() under this same source lock, and may have completed after
+ // the outer closed-check but before this task acquired the lock. Re-check here so we never
+ // build+cache+deliver a context (and register a subscription) whose factory-owned reference
+ // would then never be released — that would leak past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ Subscription<T> subscription = new Subscription<>(instanceClass, onLoadOrReload);
+ // Initial delivery happens-before the returned future completes (same thread, ordered).
+ subscription.deliver(instance);
+ source.subscriptions.add(subscription);
+ return Optional.of((TlsHandle<T>) new SubscriptionHandle<>(source, subscription));
+ }
+ });
+ }
+
+ private <T> CompletableFuture<Optional<TlsHandle<T>>> createOneShot(TlsPurpose purpose, Class<T> instanceClass) {
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ rejectReentrantAcquisition(source, purpose);
+ synchronized (source) {
+ // FIX F: re-check under the source lock (see createInstance above) so a task racing a
+ // concurrent close()/releaseAll() never builds+retains a context that then leaks past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ retain(instance);
+ return Optional.of((TlsHandle<T>) new OneShotHandle<>(instance));
+ }
+ });
+ }
+
+ /**
+ * Load (or reuse the cached) instance of {@code instanceClass} for the resolved source, recording a
+ * {@code pulsar.tls.reload} attempt for the source's purpose. A resolution failure upstream (an
+ * unconfigured server purpose) is a startup configuration error and is not counted here — only actual
+ * material loads are. Must be called while holding the source monitor.
+ *
+ * <p>Success is counted only for a <em>real</em> (re)load, mirroring the poll path: the first build of a
+ * context class for this source, or a refresh that found changed material. A repeat one-shot acquisition
+ * that re-serves the memoized context (every new connection, on the acquire-per-connection paths) is not a
+ * reload — counting it would inflate {@code pulsar.tls.reload} and keep advancing
+ * {@code pulsar.tls.last_reload_success}, masking exactly the stalled rotation the Monitoring section
+ * alerts on. Failures stay unconditional: an attempt that threw is always worth counting.
+ */
+ private <T> T loadInitialInstance(RegisteredSource source, Class<T> instanceClass) throws Exception {
+ // Hoisted out of the try so the catch can tell whether this call already CONSUMED a rotation before
+ // failing (see the comment on the catch below). Null means currentMaterial() itself threw, which
+ // commits no baseline and so consumes nothing.
+ MaterialSource.RefreshOutcome outcome = null;
+ try {
+ outcome = source.currentMaterial();
+ // Sampled before acquireInstance, which is what populates the memo (both calls run under the
+ // source monitor held by the caller, so no other acquisition can interleave).
+ boolean firstBuild = source.cachedInstance(instanceClass) == null;
+ T instance = source.acquireInstance(instanceClass, outcome.material(), settings);
+ // Rotation fan-out: currentMaterial() CONSUMES the source's change signal (refresh() commits the new
+ // mtime baseline), so whoever refreshes first is the only caller that ever sees changed=true. Without
+ // this, a one-shot acquisition (or an initial subscribing acquisition) that observes a rotation first
+ // leaves every later poll reporting changed=false and the subscribers on this same purpose wedged on
+ // the pre-rotation instance forever — e.g. an https:// client whose FrameworkHttpClientFactory
+ // subscribes to CLIENT_DEFAULT while another path acquires one-shot on it. Deliver the observed
+ // change here, exactly as the poll would have; a delivery failure arms pendingRedeliver so the next
+ // poll retries. No extra metric is recorded — this shares the single recordLoad below.
+ // Also drive the retry when a previous rotation's fan-out failed: the poll is the usual driver,
+ // but it is disabled entirely when refreshIntervalSeconds <= 0, and even when enabled an
+ // acquisition may get here first. Without this, a subscriber wedged by a failed rebuild would
+ // stay on the pre-rotation instance until the files changed again.
+ boolean retryPending = source.pendingRedeliver();
+ boolean delivered = true;
+ if (outcome.changed() || retryPending) {
+ delivered = source.deliverToSubscribers(outcome.material(), settings);
+ }
+ if (outcome.changed() || retryPending || firstBuild) {
+ recordLoad(source.purpose, delivered);
+ }
+ return instance;
+ } catch (Exception e) {
+ recordLoad(source.purpose, false);
+ // The material parsed (the baseline is committed) but building or delivering the context failed.
+ // currentMaterial() has therefore already CONSUMED this rotation's change signal, so every later
+ // poll would report changed=false and — without arming the redeliver flag here — return early,
+ // leaving the subscribers wedged on the pre-rotation instance until the files change again.
+ // deliverToSubscribers arms the flag itself on a partial delivery failure; this covers the case
+ // where the failure happened before it was ever reached.
+ if (outcome != null && outcome.changed()) {
+ source.armRedeliver();
+ }
+ // Keep-last-good (PIP-478): a one-shot (or initial subscribing) acquisition during a
+ // non-atomic rotation window — e.g. the cert file briefly unreadable while it is being replaced —
+ // must not fail when a prior load already built a context of this class. Serve that last-good
+ // instance and WARN; the reload-failure metric was recorded above. Fail only when there is no
+ // last-good to fall back on (a genuine startup misconfiguration, per the fail-fast contract).
+ T cached = source.cachedInstance(instanceClass);
+ if (cached != null) {
+ log.warn().attr("purpose", source.purpose).exception(e)
+ .log("Failed to load TLS material; serving the last-good instance");
+ return cached;
+ }
+ throw e;
+ }
+ }
+
+ private void recordLoad(TlsPurpose purpose, boolean success) {
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.recordLoad(purpose, success);
+ }
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ ScheduledFuture<?> poll = this.pollFuture;
+ if (poll != null) {
+ poll.cancel(false);
+ }
+ for (RegisteredSource source : registry.values()) {
+ source.releaseAll();
+ }
+ RegisteredSource systemDefault = this.systemDefaultSource;
+ if (systemDefault != null) {
+ systemDefault.releaseAll();
+ }
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.close();
+ }
+ }
+
+ /**
+ * Resolve a requested purpose to the {@link RegisteredSource} that owns its material, applying the
+ * role's terminal-resolution rule when nothing is configured for the purpose.
+ *
+ * @throws TlsMaterialUnavailableException when a server-role purpose has no material configured
+ */
+ private RegisteredSource resolve(TlsPurpose purpose) {
+ Objects.requireNonNull(purpose, "purpose must not be null");
+ RegisteredSource source = registry.get(purpose);
+ if (source != null) {
+ return source;
+ }
+ if (purpose.role() == TlsPurpose.Role.CLIENT) {
+ return systemDefaultSource();
+ }
+ throw new TlsMaterialUnavailableException(
+ "No TLS material configured for server purpose " + purpose);
+ }
+
+ private RegisteredSource systemDefaultSource() {
+ RegisteredSource existing = this.systemDefaultSource;
+ if (existing != null) {
+ return existing;
+ }
+ synchronized (this) {
+ if (this.systemDefaultSource == null) {
+ // System default: verify hostnames, OS trust store, no client certificate. A constant
+ // source (no files, never rotates).
+ TlsPolicy defaultPolicy = TlsPolicy.builder().build();
+ this.systemDefaultSource = new RegisteredSource(
+ TlsPurpose.CLIENT_DEFAULT, defaultPolicy, null);
+ }
+ return this.systemDefaultSource;
+ }
+ }
+
+ /**
+ * Hand the poll to the blocking executor, preserving {@code scheduleWithFixedDelay}'s no-overlap
+ * property: dispatching breaks the scheduler's own guarantee that one run finishes before the next is
+ * scheduled, so an in-flight flag stands in for it. A poll slower than the interval therefore skips
+ * ticks rather than queueing them up behind itself.
+ */
+ private void triggerPoll() {
+ if (closed || !pollInFlight.compareAndSet(false, true)) {
+ return;
+ }
+ try {
+ pollExecutor().execute(() -> {
+ try {
+ pollSafely();
+ } finally {
+ pollInFlight.set(false);
+ }
+ });
+ } catch (Throwable t) {
+ // Rejected (executor shutting down, queue full): clear the flag so a later tick can retry.
+ pollInFlight.set(false);
+ log.debug().exception(t).log("Could not dispatch the TLS material poll");
+ }
+ }
+
+ private Executor pollExecutor() {
+ TlsFactoryInitContext context = this.initContext;
+ return context != null ? context.blockingExecutor() : Runnable::run;
+ }
+
+ private void pollSafely() {
+ if (closed) {
+ return;
+ }
+ try {
+ for (RegisteredSource source : registry.values()) {
+ source.poll(settings, metrics);
+ }
+ } catch (Throwable t) {
+ log.warn().exception(t).log("Unexpected error during TLS material poll");
+ }
+ }
+
+ private <R> CompletableFuture<R> runAsync(Callable<R> task) {
+ CompletableFuture<R> future = new CompletableFuture<>();
+ TlsFactoryInitContext context = this.initContext;
+ // initialize() rejects a null blockingExecutor, so the caller-thread fallback is reachable only before
+ // initialize() has run — a direct-construction path (tests, or a component acquiring during its own
+ // startup) that is by definition not on a consumer event loop.
+ Executor executor = context != null ? context.blockingExecutor() : Runnable::run;
+ try {
+ executor.execute(() -> {
+ try {
+ R result = task.call();
+ if (!future.complete(result)) {
+ // The caller cancelled (or otherwise completed) the future while the acquisition was
+ // still running, so nothing will ever receive this handle. The task has already
+ // retained the context on its behalf, and with the finalizer-free OPENSSL_REFCNT
+ // engine an unbalanced retain is a permanent native leak — dispose the orphan here.
+ disposeOrphan(result);
+ }
+ } catch (Throwable t) {
+ future.completeExceptionally(t);
+ }
+ });
+ } catch (Throwable t) {
+ future.completeExceptionally(t);
+ }
+ return future;
+ }
+
+ /**
+ * Release a handle that was built but could not be delivered to its caller. Both acquisition forms
+ * produce an {@code Optional<TlsHandle<?>>}, and disposing it is exactly what the caller would have done:
+ * it drops the one-shot's retained reference, or unregisters the subscription and releases its borrows.
+ */
+ private static void disposeOrphan(Object result) {
+ if (result instanceof Optional<?> optional && optional.orElse(null) instanceof TlsHandle<?> handle) {
+ try {
+ handle.dispose();
+ } catch (Throwable t) {
+ log.warn().exception(t).log("Failed to dispose an undelivered TLS handle");
+ }
+ }
+ }
+
+ private static boolean isSupported(Class<?> instanceClass) {
+ return instanceClass == SslContext.class || instanceClass == SSLContext.class;
+ }
+
+ /**
+ * Fail an acquisition that re-enters the factory from inside a reload callback for the same purpose.
+ *
+ * <p>Consumer callbacks run while the source monitor is held (see
+ * {@link RegisteredSource#deliverToSubscribers}), so a callback that acquires the same purpose and
+ * blocks on the returned future deadlocks: the acquisition task needs the monitor its own caller is
+ * holding. The contract has always said not to do that, but a documented constraint that fails as a
+ * hang is a poor contract — this turns it into an immediate, self-describing error.
+ *
+ * <p>Only same-purpose re-entry is caught, because that is the case that cannot succeed. A callback
+ * acquiring a DIFFERENT purpose takes a different monitor and is merely inadvisable.
+ */
+ private static void rejectReentrantAcquisition(RegisteredSource source, TlsPurpose purpose) {
+ if (Thread.holdsLock(source)) {
+ throw new IllegalStateException("Re-entrant TLS acquisition for purpose " + purpose
+ + ": a reload callback must not call createInstance(...) for the purpose it is being "
+ + "delivered for and block on the result — the callback already holds that purpose's "
+ + "monitor, so the acquisition could never complete. Do the work outside the callback; "
+ + "the callback contract is a cheap, non-blocking store.");
+ }
+ }
Review Comment:
Done in the same commit (323e0cca8c9) — `rejectReentrantAcquisition` is now `reentrantAcquisition(TlsPurpose) → IllegalStateException`, used by both call sites to build the failed future. Message kept verbatim; you're right that it was the reachability, not the wording.
Small correction on the cross-reference: the Javadoc at line 657 belongs to `RegisteredSource.deliverToSubscribers`, not `SubscriptionHandle` (which starts around line 800). I've updated it to name the factory method and to say the *entry points* fail the call, since that is now where it happens.
##########
pulsar-broker-common/src/test/java/org/apache/pulsar/jetty/tls/JettyTlsFactoryTest.java:
##########
@@ -0,0 +1,1341 @@
+/*
+ * 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.jetty.tls;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import com.google.common.io.Resources;
+import io.opentelemetry.api.OpenTelemetry;
+import java.io.File;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.net.Socket;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.FileTime;
+import java.security.KeyStore;
+import java.security.Principal;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+import java.time.Clock;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLParameters;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509ExtendedKeyManager;
+import org.apache.commons.io.FileUtils;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactory;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactorySettings;
+import org.apache.pulsar.common.util.tls.JdkSslContexts;
+import org.apache.pulsar.common.util.tls.PemReader;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.awaitility.Awaitility;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class JettyTlsFactoryTest {
+
+ /**
+ * Reload executor for tests: same-thread, so a delivery's reload has completed by the time the call
+ * that triggered it returns and the assertions below stay deterministic. That publish genuinely runs
+ * OFF the delivery thread when a real executor is supplied has its own test
+ * ({@link #rotationReloadRunsOnTheSuppliedExecutorNotTheDeliveryThread()}).
+ */
+ private static final Executor SAME_THREAD = Runnable::run;
+
+ private static final String CA = resource("certificate-authority/certs/ca.cert.pem");
+ private static final String BROKER_CERT = resource("certificate-authority/server-keys/broker.cert.pem");
+ private static final String BROKER_KEY = resource("certificate-authority/server-keys/broker.key-pk8.pem");
+ private static final String PROXY_CERT = resource("certificate-authority/server-keys/proxy.cert.pem");
+ private static final String PROXY_KEY = resource("certificate-authority/server-keys/proxy.key-pk8.pem");
+ // Client certificates (clientAuth EKU) trusted by the shared CA above.
+ private static final String TRUSTED_CLIENT_CERT = resource("certificate-authority/client-keys/admin.cert.pem");
+ private static final String TRUSTED_CLIENT_KEY = resource("certificate-authority/client-keys/admin.key-pk8.pem");
+ private static final String USER1_CLIENT_CERT = resource("certificate-authority/client-keys/user1.cert.pem");
+ private static final String USER1_CLIENT_KEY = resource("certificate-authority/client-keys/user1.key-pk8.pem");
+ // A self-signed client certificate NOT signed by the shared CA (from a separate my-ca root).
+ private static final String UNTRUSTED_CLIENT_CERT = resource("ssl/my-ca/client-ca.pem");
+ private static final String UNTRUSTED_CLIENT_KEY = resource("ssl/my-ca/client-key.pem");
+
+ private ScheduledExecutorService scheduler;
+ private Path tempDir;
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ scheduler = Executors.newSingleThreadScheduledExecutor();
+ tempDir = Files.createTempDirectory("pip478-jetty-");
+ Files.copy(Paths.get(CA), tempDir.resolve("ca.pem"), StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(BROKER_CERT), tempDir.resolve("cert.pem"), StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(BROKER_KEY), tempDir.resolve("key.pem"), StandardCopyOption.REPLACE_EXISTING);
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown() throws Exception {
+ scheduler.shutdownNow();
+ if (tempDir != null) {
+ FileUtils.deleteDirectory(tempDir.toFile());
+ }
+ }
+
+ @Test
+ public void reloadingServerFactoryServesRotatedCertificateToNewConnections() throws Exception {
+ FileBasedTlsFactory factory = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().refreshIntervalSeconds(1).build());
+ factory.initialize(initContext()).join();
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+
+ Server server = new Server();
+ ServerConnector connector = new ServerConnector(server, reloadable.sslContextFactory());
+ connector.setPort(0);
+ server.setConnectors(new ServerConnector[] {connector});
+ server.start();
+ try {
+ SSLContext clientContext = JdkSslContexts.createSslContext(false,
+ PemReader.loadCertificatesFromPemFile(CA), null, null);
+ int port = connector.getLocalPort();
+
+ BigInteger initialSerial = serverCertSerial(clientContext, port);
+ assertThat(initialSerial).isEqualTo(certSerial(BROKER_CERT));
+
+ // Rotate the server material to a different (proxy) certificate signed by the same CA.
+ Files.copy(Paths.get(PROXY_CERT), tempDir.resolve("cert.pem"), StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(PROXY_KEY), tempDir.resolve("key.pem"), StandardCopyOption.REPLACE_EXISTING);
+ long later = System.currentTimeMillis() + 5000;
+ Files.setLastModifiedTime(tempDir.resolve("cert.pem"), FileTime.fromMillis(later));
+ Files.setLastModifiedTime(tempDir.resolve("key.pem"), FileTime.fromMillis(later));
+
+ BigInteger proxySerial = certSerial(PROXY_CERT);
+ Awaitility.await().atMost(Duration.ofSeconds(15))
+ .until(() -> serverCertSerial(clientContext, port).equals(proxySerial));
+ assertThat(serverCertSerial(clientContext, port))
+ .as("new connections use the rotated certificate")
+ .isEqualTo(proxySerial).isNotEqualTo(initialSerial);
+ } finally {
+ reloadable.subscription().dispose();
+ server.stop();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478: a self-reloading {@link SslContextFactory.Client} presents rotated client-certificate
+ * material to new connections while the factory stays alive (mirrors the server rotation test).
+ */
+ @Test
+ public void reloadingClientFactoryPresentsRotatedClientCertOnNewConnections() throws Exception {
+ // Distinct filenames from the server rotation test's cert.pem/key.pem; these hold a client-auth
+ // certificate (the broker/proxy server certs carry a serverAuth-only EKU and cannot be presented as
+ // a client identity).
+ Path clientCert = tempDir.resolve("clientcert.pem");
+ Path clientKey = tempDir.resolve("clientkey.pem");
+ Files.copy(Paths.get(TRUSTED_CLIENT_CERT), clientCert, StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(TRUSTED_CLIENT_KEY), clientKey, StandardCopyOption.REPLACE_EXISTING);
+
+ FileBasedTlsFactory factory = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.BROKER_CLIENT, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ clientCert.toString(), clientKey.toString())),
+ FileBasedTlsFactorySettings.builder().refreshIntervalSeconds(1).build());
+ factory.initialize(initContext()).join();
+
+ JettyTlsFactory.ReloadableClientTls reloadable = JettyTlsFactory.createReloadingClientFactory(
+ factory, TlsPurpose.BROKER_CLIENT, SAME_THREAD, null, true);
+ SslContextFactory.Client clientFactory = reloadable.sslContextFactory();
+ clientFactory.start();
+ try {
+ assertThat(presentedClientCertSerial(clientFactory)).isEqualTo(certSerial(TRUSTED_CLIENT_CERT));
+
+ // Rotate the client identity to a different client certificate signed by the same CA.
+ Files.copy(Paths.get(USER1_CLIENT_CERT), clientCert, StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(USER1_CLIENT_KEY), clientKey, StandardCopyOption.REPLACE_EXISTING);
+ long later = System.currentTimeMillis() + 5000;
+ Files.setLastModifiedTime(clientCert, FileTime.fromMillis(later));
+ Files.setLastModifiedTime(clientKey, FileTime.fromMillis(later));
+
+ BigInteger rotatedSerial = certSerial(USER1_CLIENT_CERT);
+ Awaitility.await().atMost(Duration.ofSeconds(15))
+ .until(() -> presentedClientCertSerial(clientFactory).equals(rotatedSerial));
+ assertThat(presentedClientCertSerial(clientFactory))
+ .as("new connections present the rotated client certificate")
+ .isEqualTo(rotatedSerial).isNotEqualTo(certSerial(TRUSTED_CLIENT_CERT));
+ } finally {
+ clientFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ // Handshake the reloading client factory's current context against a client-auth-requiring server and
+ // return the serial of the client certificate the server observed.
+ private BigInteger presentedClientCertSerial(SslContextFactory.Client clientFactory) throws Exception {
+ SSLContext serverContext = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ try (SSLServerSocket serverSocket =
+ (SSLServerSocket) serverContext.getServerSocketFactory().createServerSocket(0)) {
+ serverSocket.setNeedClientAuth(true);
+ // TLSv1.2 so client auth completes symmetrically within the handshake (avoids the TLS 1.3
+ // post-handshake close race where the server closes before the client flushes its Finished).
+ serverSocket.setEnabledProtocols(new String[] {"TLSv1.2"});
+ serverSocket.setSoTimeout(15000);
+ int port = serverSocket.getLocalPort();
+ CompletableFuture<BigInteger> serverSaw = new CompletableFuture<>();
+ Thread serverThread = new Thread(() -> {
+ try (SSLSocket accepted = (SSLSocket) serverSocket.accept()) {
+ accepted.setSoTimeout(15000);
+ accepted.startHandshake();
+ X509Certificate peer = (X509Certificate) accepted.getSession().getPeerCertificates()[0];
+ serverSaw.complete(peer.getSerialNumber());
+ } catch (Throwable t) {
+ serverSaw.completeExceptionally(t);
+ }
+ });
+ serverThread.setDaemon(true);
+ serverThread.start();
+
+ SSLContext clientContext = clientFactory.getSslContext();
+ try (SSLSocket clientSocket =
+ (SSLSocket) clientContext.getSocketFactory().createSocket("localhost", port)) {
+ clientSocket.setEnabledProtocols(new String[] {"TLSv1.2"});
+ clientSocket.setSoTimeout(15000);
+ clientSocket.startHandshake();
+ }
+ return serverSaw.get(15, TimeUnit.SECONDS);
+ }
+ }
+
+ /**
+ * PIP-478: under optional client auth ({@code requireTrustedClientCert=false}), an <em>untrusted</em>
+ * client certificate is rejected at the web listener's handshake when {@code allowInsecureConnection=false}
+ * and accepted when it is true; a trusted client certificate is accepted in both cases.
+ */
+ @Test
+ public void optionalClientAuthScopesTrustAllToInsecureFlag() throws Exception {
+ // Secure (insecure=false): untrusted client cert is rejected, trusted client cert is accepted. The
+ // server aborts the handshake, surfaced to the client either as an SSLHandshakeException or, once the
+ // server has already sent its close/alert, as a broken-pipe SocketException — both are handshake
+ // failures.
+ try (JettyServer secure = startWebServer(false)) {
+ assertThatThrownBy(() -> handshakeWithClientCert(secure.port, UNTRUSTED_CLIENT_CERT, UNTRUSTED_CLIENT_KEY))
+ .as("an untrusted client cert must be rejected when insecure=false")
+ .isInstanceOf(IOException.class);
+ handshakeWithClientCert(secure.port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY);
+ }
+ // Insecure (insecure=true): both untrusted and trusted client certs are accepted (trust-all).
+ try (JettyServer insecure = startWebServer(true)) {
+ handshakeWithClientCert(insecure.port, UNTRUSTED_CLIENT_CERT, UNTRUSTED_CLIENT_KEY);
+ handshakeWithClientCert(insecure.port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY);
+ }
+ }
+
+ /**
+ * PIP-478: a factory that supplies its {@code SSLContext} together with an {@code SSLParameters} companion
+ * drives the synthesized server {@link SslContextFactory.Server} — its enabled protocols/ciphers and its
+ * client-auth mode are mapped from the companion, the latter authoritatively (merge rule 4).
+ */
+ @Test
+ public void serverFactoryMapsCompanionProtocolsAndClientAuth() throws Exception {
+ SSLParameters companion = new SSLParameters();
+ companion.setProtocols(new String[] {"TLSv1.2"});
+ companion.setCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});
+ companion.setNeedClientAuth(true);
+
+ FileBasedTlsFactory delegate = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().build());
+ CompanionFactory factory = new CompanionFactory(delegate, companion);
+ factory.initialize(initContext()).join();
+
+ // Consumer config asks for no protocol/cipher restriction and only optional client auth; the companion
+ // overrides all three.
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ try {
+ assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+ assertThat(sslContextFactory.getIncludeCipherSuites())
+ .containsExactly("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
+ assertThat(sslContextFactory.getNeedClientAuth()).isTrue();
+ } finally {
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * T4: the companion's protocol restriction and {@code needClientAuth} are not just mapped onto the
+ * synthesized Jetty {@link SslContextFactory.Server} getters — they decide a real handshake against a live
+ * server. A trusted client certificate over the allowed protocol succeeds; a client presenting no
+ * certificate is rejected (needClientAuth); a client offering only a disallowed protocol is rejected.
+ */
+ @Test
+ public void serverCompanionNeedClientAuthAndProtocolEnforcedAtHandshake() throws Exception {
+ SSLParameters companion = new SSLParameters();
+ companion.setProtocols(new String[] {"TLSv1.2"});
+ companion.setNeedClientAuth(true);
+
+ FileBasedTlsFactory delegate = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().build());
+ CompanionFactory factory = new CompanionFactory(delegate, companion);
+ factory.initialize(initContext()).join();
+
+ // Consumer config asks for no protocol restriction and only optional client auth; the companion wins.
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ Server server = new Server();
+ ServerConnector connector = new ServerConnector(server, reloadable.sslContextFactory());
+ connector.setPort(0);
+ server.setConnectors(new ServerConnector[] {connector});
+ server.start();
+ int port = connector.getLocalPort();
+ try {
+ // A trusted client certificate over the allowed protocol completes the handshake.
+ handshakeWithClientCert(port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY);
+ // The companion's needClientAuth rejects a client that presents no certificate.
+ assertThatThrownBy(() -> handshakeWithoutClientCert(port))
+ .as("needClientAuth from the companion rejects a client with no certificate")
+ .isInstanceOf(IOException.class);
+ // The companion's TLSv1.2-only restriction rejects a client offering only TLSv1.3.
+ assertThatThrownBy(() -> handshakeWithClientCert(port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY,
+ "TLSv1.3"))
+ .as("a TLSv1.3-only client cannot handshake with the companion-pinned TLSv1.2 server")
+ .isInstanceOf(IOException.class);
+ } finally {
+ reloadable.subscription().dispose();
+ server.stop();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 (pip-478.md:736): the {@code SSLParameters} companion is re-requested on <em>every</em>
+ * {@code SSLContext} delivery, not just at build time — so engine policy (here the server client-auth mode)
+ * rotates with material. A companion that flips {@code needClientAuth} on rotation must be reflected in the
+ * synthesized Jetty {@link SslContextFactory.Server} after the reload, and dropping the companion must
+ * revert client-auth to the consumer default rather than leaving the prior value stuck.
+ *
+ * <p>The companion is resolved on the <em>same single-thread scheduler</em> that runs the poll deliveries
+ * (see {@link CompanionFactory}'s executor): this reproduces the self-deadlock hazard a synchronous
+ * {@code join} on the delivery thread would hit. The reload path re-requests the companion asynchronously,
+ * so the rotation still applies (the assertions are awaited rather than read synchronously).
+ */
+ @Test
+ public void serverCompanionClientAuthRotatesWithMaterialOnReload() throws Exception {
+ // Build-time companion: no client auth. This overrides the consumer default (optional client auth).
+ SSLParameters noClientAuth = new SSLParameters();
+ noClientAuth.setNeedClientAuth(false);
+
+ FileBasedTlsFactory delegate = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().refreshIntervalSeconds(1).build());
+ // Dispatch companion creation onto the shared scheduler (the delivery thread), so a join inside the
+ // reload callback would deadlock; the async re-request must keep the rotation working.
+ CompanionFactory factory = new CompanionFactory(delegate, noClientAuth, scheduler);
+ factory.initialize(initContext()).join();
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ // Start standalone (no full Jetty server needed) so the reload path (isStarted()) runs on delivery.
+ sslContextFactory.start();
+ try {
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("the build-time companion (needClientAuth=false) is authoritative")
+ .isFalse();
+
+ // Flip the companion to require client auth, then rotate material to trigger an SSLContext delivery.
+ SSLParameters needClientAuth = new SSLParameters();
+ needClientAuth.setNeedClientAuth(true);
+ factory.setCompanion(needClientAuth);
+ rotateWebMaterial();
+
+ // The reload re-requests the companion and re-applies it under Jetty's lock, so the new
+ // needClientAuth takes effect on the synthesized factory.
+ Awaitility.await().atMost(Duration.ofSeconds(15)).until(sslContextFactory::getNeedClientAuth);
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("the companion is re-requested on delivery, so client-auth rotates with material")
+ .isTrue();
+
+ // Drop the companion entirely and rotate again: client-auth must revert to the consumer default
+ // (optional client auth => wantClientAuth, needClientAuth cleared) instead of staying stuck at need.
+ factory.setCompanion(null);
+ rotateWebMaterial();
+ Awaitility.await().atMost(Duration.ofSeconds(15)).until(() -> !sslContextFactory.getNeedClientAuth());
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("dropping the companion reverts needClientAuth to the consumer default")
+ .isFalse();
+ assertThat(sslContextFactory.getWantClientAuth())
+ .as("the consumer default (optional client auth) is restored")
+ .isTrue();
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 generation guard: two rotation companions that complete OUT OF ORDER must leave the NEWER
+ * rotation's context and baseline applied, never regressing to the older one. Each rotation captures a
+ * strictly increasing delivery generation; when the older rotation's companion completes last, its
+ * reload is dropped because a newer generation has already been published (mirroring
+ * {@code TlsContextAcquisition.SynthesizingSubscription}'s generation-guarded {@code publish}). Without the
+ * guard the stale companion would pin the synthesized {@link SslContextFactory.Server} to the older
+ * context/baseline until the next rotation.
+ */
+ @Test
+ public void serverRotationOutOfOrderCompanionKeepsNewerContextAndBaseline() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext contextA = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext contextB = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ ScriptableFactory factory = new ScriptableFactory(initial, null);
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ // Start standalone so the reload path (isStarted()) runs on each rotation delivery.
+ sslContextFactory.start();
+ try {
+ factory.deferCompanions();
+ // Two rotations: A (older, generation N) then B (newer, generation N+1).
+ factory.deliver(contextA);
+ factory.deliver(contextB);
+
+ SSLParameters baselineA = new SSLParameters();
+ baselineA.setProtocols(new String[] {"TLSv1.2"});
+ SSLParameters baselineB = new SSLParameters();
+ baselineB.setProtocols(new String[] {"TLSv1.3"});
+
+ // Complete the NEWER rotation's companion first, then the older one; the generation guard must
+ // drop the stale (older) result so the newer context/baseline stays applied.
+ factory.completeCompanion(1, baselineB);
+ factory.completeCompanion(0, baselineA);
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(sslContextFactory.getIncludeProtocols())
+ .as("the newer rotation's baseline wins despite the older companion completing last")
+ .containsExactly("TLSv1.3");
+ assertThat(sslContextFactory.getSslContext())
+ .as("the newer rotation's context stays pinned")
+ .isSameAs(contextB);
+ });
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 last-good retention: a rotation whose companion re-request fails transiently must retain the
+ * last successfully-resolved baseline (seeded from the build-time companion) rather than downgrading to
+ * consumer defaults. Here the build companion pins TLSv1.2 and {@code needClientAuth}; the rotation's
+ * companion then fails, and the reload must still apply the rotated context while keeping client-auth and
+ * the protocol restriction — the guarantee {@code SynthesizingSubscription} provides via its retained
+ * {@code lastBaseline}. Without it, the failed companion would silently drop client-auth/protocols.
+ */
+ @Test
+ public void serverRotationCompanionFailureRetainsLastGoodBaseline() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ SSLParameters lastGood = new SSLParameters();
+ lastGood.setProtocols(new String[] {"TLSv1.2"});
+ lastGood.setNeedClientAuth(true);
+ ScriptableFactory factory = new ScriptableFactory(initial, lastGood);
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ sslContextFactory.start();
+ try {
+ // The build-time companion is authoritative and seeds the retained last-good baseline.
+ assertThat(sslContextFactory.getNeedClientAuth()).isTrue();
+ assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+
+ factory.deferCompanions();
+ // Rotate material; the companion re-request for this rotation fails transiently.
+ factory.deliver(rotated);
+ factory.failCompanion(0, new IllegalStateException("companion temporarily unavailable"));
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(sslContextFactory.getSslContext())
+ .as("the rotated context is applied even though the companion failed")
+ .isSameAs(rotated);
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("a transient companion failure retains the last-good client-auth")
+ .isTrue();
+ assertThat(sslContextFactory.getIncludeProtocols())
+ .as("a transient companion failure retains the last-good protocol restriction")
+ .containsExactly("TLSv1.2");
+ });
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 companion revert, cipher suites: a companion that pins cipher suites on one delivery and drops them
+ * on the next must revert to the consumer default (here: no restriction) rather than leaving the stale
+ * allowlist pinned on the long-lived {@link SslContextFactory.Server}, which persists setter state across
+ * {@code reload()}. This is the same guarantee already covered for client-auth in
+ * {@link #serverCompanionClientAuthRotatesWithMaterialOnReload}, extended to the cipher/protocol members.
+ */
+ @Test
+ public void serverDroppedCompanionRevertsCipherSuitesToConsumerDefault() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ SSLParameters buildCompanion = new SSLParameters();
+ buildCompanion.setCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});
+ buildCompanion.setProtocols(new String[] {"TLSv1.2"});
+ ScriptableFactory factory = new ScriptableFactory(initial, buildCompanion);
+
+ // The consumer configures neither ciphers nor protocols, so the defaults are "no cipher restriction" and
+ // the {TLSv1.3, TLSv1.2} protocol floor.
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ sslContextFactory.start();
+ try {
+ assertThat(sslContextFactory.getIncludeCipherSuites())
+ .containsExactly("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
+ assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+
+ // Rotate with a companion that supplies nothing at all (empty()), modelling a delivery that
+ // legitimately drops the previously pinned members.
+ factory.deferCompanions();
+ factory.deliver(rotated);
+ factory.completeCompanion(0, null);
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(sslContextFactory.getIncludeCipherSuites())
+ .as("a dropped companion reverts cipher suites to the consumer default (unrestricted)")
+ .isEmpty();
+ assertThat(sslContextFactory.getIncludeProtocols())
+ .as("a dropped companion reverts protocols to the consumer default floor")
+ .containsExactlyInAnyOrder("TLSv1.3", "TLSv1.2");
+ });
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /** The client path is symmetric: a dropped companion must not leave a stale cipher allowlist pinned. */
+ @Test
+ public void clientDroppedCompanionRevertsCipherSuitesToConsumerDefault() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, USER1_CLIENT_CERT, USER1_CLIENT_KEY, null);
+ SSLParameters buildCompanion = new SSLParameters();
+ buildCompanion.setCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});
+ buildCompanion.setProtocols(new String[] {"TLSv1.2"});
+ ScriptableFactory factory = new ScriptableFactory(initial, buildCompanion);
+
+ JettyTlsFactory.ReloadableClientTls reloadable = JettyTlsFactory.createReloadingClientFactory(
+ factory, TlsPurpose.BROKER_CLIENT, SAME_THREAD, null, true);
+ SslContextFactory.Client clientFactory = reloadable.sslContextFactory();
+ clientFactory.start();
+ try {
+ assertThat(clientFactory.getIncludeCipherSuites())
+ .containsExactly("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
+ assertThat(clientFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+
+ factory.deferCompanions();
+ factory.deliver(rotated);
+ factory.completeCompanion(0, null);
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(clientFactory.getIncludeCipherSuites())
+ .as("a dropped companion reverts cipher suites to the consumer default (unrestricted)")
+ .isEmpty();
+ assertThat(clientFactory.getIncludeProtocols())
+ .as("a dropped companion reverts protocols to the consumer default floor")
+ .containsExactlyInAnyOrder("TLSv1.3", "TLSv1.2");
+ });
+ } finally {
+ clientFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478: a rotation delivered BEFORE the connector starts must still refresh the companion. Only the very
+ * first (pre-fetched, synchronous) delivery reuses the build-time baseline; a later delivery that lands while
+ * the factory is still unstarted re-requests the companion and applies it directly (Jetty's {@code reload()}
+ * is for a live factory), so the started factory runs the rotation's engine policy — protocols, cipher suites
+ * and client-auth — rather than the stale build-time one.
+ */
+ /**
+ * The reload must not run on the thread that delivered the rotation.
+ *
+ * <p>For the default factory the companion request completes synchronously — {@code SSLParameters} is
+ * an unsupported class, so {@code createInstance} returns an already-completed future — which means a
+ * plain {@code whenComplete} would run the whole Jetty reload inline, on a delivery thread that is
+ * inside the factory's {@code synchronized} fan-out. That put the source monitor at the head of a
+ * source -> coordinator -> Jetty lock chain and broke the delivery contract's "cheap non-blocking
+ * store". Dispatching to the supplied executor is what keeps that from happening.
+ */
+ @Test
+ public void rotationReloadRunsOnTheSuppliedExecutorNotTheDeliveryThread() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ ScriptableFactory factory = new ScriptableFactory(initial, null);
+ ExecutorService reloadExecutor = Executors.newSingleThreadExecutor(r -> new Thread(r, "reload-executor"));
+ try {
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, reloadExecutor, null, false, false, null, null);
+ SslContextFactory.Server target = reloadable.sslContextFactory();
+ target.start();
+
+ AtomicReference<String> reloadThread = new AtomicReference<>();
+ Thread deliveringThread = new Thread(() -> factory.deliver(rotated), "delivery-thread");
+ // Capture the thread the applied context lands on by observing the factory after the reload.
+ deliveringThread.start();
+ deliveringThread.join(TimeUnit.SECONDS.toMillis(10));
+
+ Awaitility.await().atMost(Duration.ofSeconds(10))
+ .untilAsserted(() -> assertThat(target.getSslContext()).isSameAs(rotated));
+ reloadExecutor.submit(() -> reloadThread.set(Thread.currentThread().getName()))
+ .get(10, TimeUnit.SECONDS);
+
+ assertThat(reloadThread.get()).as("the reload executor is the one that ran publish")
+ .isEqualTo("reload-executor");
+ assertThat(deliveringThread.isAlive())
+ .as("the delivery thread was not held for the duration of the reload").isFalse();
Review Comment:
Both tautologies confirmed, and the mutation result reproduces. Replaced in afa92685af1.
One correction to the remediation, because I tried it your way first and it doesn't discriminate: gating the **companion future** is not enough. Registering an inline `whenComplete` on an incomplete future also returns immediately, so the delivery thread comes back promptly under both variants and the assertions stay green under your own mutation. The gate has to be on the **reloadExecutor**, with the companion completing **synchronously** — which is exactly the default factory's behaviour, since `SSLParameters` is unsupported and `createInstance` returns an already-completed future.
So: a holding executor parks submitted tasks; after `deliver(...)` returns, assert the rotation has **not** been applied and exactly one task is parked; release it and assert it has. Under inline `whenComplete` the reload has already run inside `deliver(...)` and the first assertion fails immediately. No sleeps, no thread names, no Awaitility.
Verified by mutation: with `whenCompleteAsync` reverted to `whenComplete`, this test fails.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/JettyTlsFactory.java:
##########
@@ -0,0 +1,637 @@
+/*
+ * 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.jetty.tls;
+
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.tls.impl.TlsContexts;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * The framework's Jetty integration for the PIP-478 TLS SPI. Both {@link SslContextFactory.Server} and
+ * {@link SslContextFactory.Client} are well-known SPI classes: the framework first asks the
+ * {@link PulsarTlsFactory} to supply one natively (a custom factory may build and own it, reload
+ * included); only when the factory returns {@code empty()} for the Jetty class does the framework
+ * synthesize a <em>vanilla</em> (never subclassed) one from an {@code SSLContext} subscription. The
+ * default {@code FileBasedTlsFactory} returns {@code empty()} for the Jetty classes, so the synthesized
+ * path is the usual one.
+ *
+ * <p><b>Factory-supplied (native) instances.</b> When the factory supplies the Jetty factory directly it
+ * is handed back <em>unstarted</em> (the connector / {@code HttpClient} starts it), is the factory's
+ * same-instance-per-purpose, and the factory owns its reload on material rotation. The framework only
+ * holds the returned {@link TlsHandle} for disposal and never drives {@code setSslContext}/{@code reload}
+ * or overlays consumer configuration on such an instance.
+ *
+ * <p>This deliberately abandons the unsound {@code getSslContext()} override of the superseded PIP-337
+ * {@code JettySslContextFactory}. Instead it uses
+ * Jetty's documented hot-reload API — the same one {@code KeyStoreScanner} uses: an {@code SSLContext}
+ * subscription drives {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each
+ * later delivery (once started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context and re-selects
+ * protocols/ciphers. Existing connections keep their sessions; new connections use the new context.
+ *
+ * <p><b>{@code SSLParameters} companion (PIP-478).</b> Because these are synthesized paths (the factory
+ * returned {@code empty()} for the Jetty class and supplies only the {@code SSLContext}), the framework also
+ * asks the factory for its optional {@code javax.net.ssl.SSLParameters} companion — the engine-level baseline
+ * a bare {@code SSLContext} cannot express — and maps its non-null members onto the Jetty setters: enabled
+ * protocols ({@link SslContextFactory#setIncludeProtocols}) and cipher suites
+ * ({@link SslContextFactory#setIncludeCipherSuites}), and (server side, merge rule 4) the authoritative
+ * client-auth mode ({@link SslContextFactory.Server#setNeedClientAuth} /
+ * {@link SslContextFactory.Server#setWantClientAuth}). The initial companion is overlaid before start (at build
+ * time); on each subsequent <em>rotation</em> delivery it is re-requested <em>asynchronously</em> — the reload
+ * callback composes {@code createInstance(purpose, SSLParameters.class)} with {@code whenComplete} and only then
+ * calls {@code reload(...)}, so engine policy rotates with material (pip-478.md:736) yet the companion is
+ * <b>never joined on the delivery thread</b>. Joining there would self-deadlock a custom factory that dispatches
+ * companion creation to the same single-thread scheduler that runs the poll delivery — the exact hazard
+ * {@code TlsContextAcquisition.SynthesizingSubscription} avoids by composing the companion asynchronously.
+ *
+ * <p>Because those asynchronous re-requests complete on arbitrary threads and may finish out of order, the
+ * synthesized reload mirrors the two ordering guarantees of {@code SynthesizingSubscription} (see
+ * {@code JettyReloadCoordinator}): each delivery captures a strictly increasing <em>generation</em> and applies
+ * its {@code reload(...)} only while that generation is still the latest, so a companion superseded by a newer
+ * rotation is dropped rather than pinning the listener to a stale context/baseline; and the last
+ * successfully-resolved companion is <em>retained</em> (seeded from the build-time baseline) so a transient
+ * companion-fetch failure during rotation reloads with that last-good baseline rather than downgrading engine
+ * policy (protocols/ciphers and, server side, client-auth) to consumer defaults. Consumer defaults are still
+ * re-applied <em>in full</em> first inside every {@code reload(...)} lambda — protocols, cipher suites and, server
+ * side, client-auth are each re-pinned or cleared unconditionally, since the long-lived {@code SslContextFactory}
+ * persists setter state across {@code reload()} — so any companion member legitimately dropped by a newer delivery
+ * reverts to the consumer default rather than staying stuck from the previous companion.
+ * {@code empty()} leaves the consumer's configuration in force, exactly as before.
+ */
+@CustomLog
+public final class JettyTlsFactory {
+
+ static {
+ // Install Conscrypt process-wide, if present, before any TLS object is built here. Jetty resolves a
+ // JSSE provider by name, so the provider has to be registered by the time a factory is configured.
+ JcaProviders.ensureConscryptRegistered();
+ }
+
+ private JettyTlsFactory() {
+ }
+
+ /**
+ * A Jetty server factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the web service stops.
+ *
+ * @param sslContextFactory the (unstarted) Jetty server factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableServerTls(SslContextFactory.Server sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * A Jetty client factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the owning HTTP client
+ * / servlet is destroyed.
+ *
+ * @param sslContextFactory the (unstarted) Jetty client factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableClientTls(SslContextFactory.Client sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * Build a self-reloading {@link SslContextFactory.Server} for a purpose, handed back <em>unstarted</em>
+ * (Jetty starts it with the connector lifecycle) with its initial {@code SSLContext} already set.
+ *
+ * <p><b>Must not be called from the factory's blocking executor.</b> This builder blocks on the
+ * factory's acquisition, and the default factory dispatches acquisitions to
+ * {@code TlsFactoryInitContext.blockingExecutor()} — so calling it from that executor waits on work
+ * queued behind itself, which deadlocks when the executor is single-threaded. Call it from the owning
+ * component's startup thread.
+ *
+ * @param factory the TLS factory to subscribe to
+ * @param purpose the server purpose (e.g. {@link TlsPurpose#WEB})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param requireTrustedClientCert whether to require (vs. request) a trusted client certificate
+ * @param allowInsecureConnection whether an untrusted client cert is accepted under optional client auth
+ * @param ciphers enabled cipher suites, or {@code null} for defaults
+ * @param protocols enabled protocols, or {@code null} for defaults
+ * @return the reloading factory and its subscription handle
+ */
+ public static ReloadableServerTls createReloadingServerFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ Executor reloadExecutor,
+ String sslProviderString,
+ boolean requireTrustedClientCert,
+ boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ // Ask the factory first: a custom factory may natively supply the Jetty server factory (a
+ // well-known class). When it does, hand it back unstarted with the factory owning its reload and
+ // configuration; the framework overlays no consumer config on it. The default file-based factory
+ // returns empty() here, so the synthesized, self-reloading fallback below runs (the usual path).
+ Optional<TlsHandle<SslContextFactory.Server>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Server.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Server> handle = nativeFactory.get();
+ return new ReloadableServerTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
+ // Consumer config plus the factory's engine-policy companion (if any), before start. The resolved
+ // companion seeds the coordinator's last-good baseline so a companion-fetch failure on the very first
+ // rotation retains it rather than downgrading to consumer defaults.
+ SSLParameters initialBaseline = configureServerBaseline(sslContextFactory, factory, purpose,
+ sslProviderString, requireTrustedClientCert, allowInsecureConnection, ciphers, protocols);
+
+ // Each rotation re-requests the companion asynchronously (off the delivery thread) and applies it under
+ // a generation guard so an out-of-order companion cannot pin a stale context, retaining the last-good
+ // baseline across a transient companion failure. See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, reloadExecutor,
+ sslContextFactory, initialBaseline, (newContext, baseline) -> {
+ sslContextFactory.setSslContext(newContext);
+ // Re-apply the consumer defaults first so a companion member dropped by this delivery
+ // (notably client-auth) reverts to the consumer default rather than staying stuck from the
+ // previous companion, then overlay the generation-guarded, last-good companion.
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert,
+ allowInsecureConnection, ciphers, protocols);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ awaitAcquisition(factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery), purpose)
+ .orElseThrow(() -> new IllegalStateException(
+ "TLS factory supplied no SSLContext for purpose " + purpose));
+ return new ReloadableServerTls(sslContextFactory, coordinator.bind(subscription));
+ }
+
+ /**
+ * Build an {@link SslContextFactory.Client} for a purpose (used by the proxy's {@code AdminProxyHandler},
+ * whose Jetty {@code HttpClient} outlives broker-client material rotation), handed back
+ * <em>unstarted</em>. Mirroring {@link #createReloadingServerFactory}, the framework first asks the
+ * factory to supply the Jetty client factory natively; a custom factory that does so owns its reload and
+ * endpoint identification, and the framework overlays nothing on it. Otherwise a vanilla, self-reloading
+ * one is synthesized: an {@code SSLContext} subscription drives
+ * {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each later delivery (once
+ * started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context so new connections use
+ * the rotated material. Dispose the returned {@link ReloadableClientTls#subscription()} when the owning
+ * client is destroyed.
+ *
+ * <p><b>Must not be called from the factory's blocking executor.</b> This builder blocks on the
+ * factory's acquisition, and the default factory dispatches acquisitions to
+ * {@code TlsFactoryInitContext.blockingExecutor()} — so calling it from that executor waits on work
+ * queued behind itself, which deadlocks when the executor is single-threaded. Call it from the owning
+ * component's startup thread.
+ *
+ * @param factory the TLS factory to acquire from / subscribe to
+ * @param purpose the client purpose (e.g. {@link TlsPurpose#BROKER_CLIENT})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param enableHostnameVerification whether to verify the peer hostname; when {@code false} the
+ * synthesized client's endpoint identification is disabled (a
+ * factory-supplied native client owns this itself and is left untouched)
+ * @return the client factory and the handle backing it
+ */
+ public static ReloadableClientTls createReloadingClientFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ Executor reloadExecutor,
+ String sslProviderString,
+ boolean enableHostnameVerification) {
+ // Ask the factory first: a custom factory may natively supply the Jetty client factory (a well-known
+ // class, mirroring the Server variant) to customize proxy->broker admin TLS. When it does, hand it
+ // back unstarted with the factory owning its reload and its own endpoint identification; the
+ // framework overlays no consumer config on it. The default file-based factory returns empty() here,
+ // so the SSLContext-synthesized, self-reloading fallback below runs (the usual path, including
+ // rotation of the long-lived admin HttpClient's broker-client material).
+ Optional<TlsHandle<SslContextFactory.Client>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Client.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Client> handle = nativeFactory.get();
+ return new ReloadableClientTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Client client = new SslContextFactory.Client();
+ if (StringUtils.isNotBlank(sslProviderString)) {
+ client.setProvider(sslProviderString);
+ }
+ // Pin the {TLSv1.3, TLSv1.2} floor and overlay the factory's engine-policy companion (if any), before
+ // start; the resolved companion seeds the coordinator's last-good baseline (see the Server variant).
+ SSLParameters initialBaseline = configureClientBaseline(client, factory, purpose);
+ // Hostname verification is a consumer (proxy) concern on the synthesized path: disable endpoint
+ // identification when the consumer has it off (a native factory, handled above, owns this itself). This
+ // is a per-consumer setting applied once at build, not part of the per-delivery companion overlay.
+ if (!enableHostnameVerification) {
+ client.setEndpointIdentificationAlgorithm(null);
+ }
+
+ // Rotations re-request the companion asynchronously (off the delivery thread) and apply it under a
+ // generation guard, retaining the last-good baseline across a transient companion failure (client-auth
+ // is a server concept; endpoint identification stays as set at build). See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, reloadExecutor, client,
+ initialBaseline,
+ (newContext, baseline) -> {
+ client.setSslContext(newContext);
+ // Re-apply the consumer defaults first (the {TLSv1.3, TLSv1.2} floor and an unrestricted cipher
+ // list), then overlay the generation-guarded, last-good companion so a companion member dropped
+ // by this delivery reverts to those defaults rather than staying stuck from the previous one.
+ applyClientConfig(client);
+ if (baseline != null) {
+ applyClientBaseline(client, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ awaitAcquisition(factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery), purpose)
+ .orElseThrow(() -> new IllegalStateException(
+ "TLS factory supplied no SSLContext for purpose " + purpose));
+ return new ReloadableClientTls(client, coordinator.bind(subscription));
+ }
+
+ /**
+ * Apply the consumer config, then overlay the factory's engine-policy companion, onto a synthesized server
+ * factory — at build time only (off any event loop; the companion is joined here). Each subsequent rotation
+ * delivery re-requests the companion asynchronously and re-applies it inside the {@code reload(...)} lambda
+ * (see {@link JettyReloadCoordinator}), never joined on the delivery thread.
+ *
+ * @return the resolved companion baseline, or {@code null} when the factory supplied none — used to seed the
+ * coordinator's retained last-good baseline.
+ */
+ private static SSLParameters configureServerBaseline(SslContextFactory.Server sslContextFactory,
+ PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString, boolean requireTrustedClientCert,
+ boolean allowInsecureConnection, Set<String> ciphers,
+ Set<String> protocols) {
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert, allowInsecureConnection,
+ ciphers, protocols);
+ SSLParameters baseline = resolveBaselineParameters(factory, purpose).orElse(null);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ return baseline;
+ }
+
+ /**
+ * Pin the {@code {TLSv1.3, TLSv1.2}} floor, then overlay the factory companion's protocols/ciphers, onto a
+ * synthesized client factory — at build time only (off any event loop; the companion is joined here). Each
+ * subsequent rotation delivery re-requests the companion asynchronously and re-pins the floor + overlays it
+ * inside the {@code reload(...)} lambda (see {@link JettyReloadCoordinator}), never joined on the delivery
+ * thread. Client-auth is a server concept and is not mapped here; endpoint identification is a per-consumer
+ * setting applied once at build.
+ *
+ * @return the resolved companion baseline, or {@code null} when the factory supplied none — used to seed the
+ * coordinator's retained last-good baseline.
+ */
+ private static SSLParameters configureClientBaseline(SslContextFactory.Client client, PulsarTlsFactory factory,
+ TlsPurpose purpose) {
+ applyClientConfig(client);
+ SSLParameters baseline = resolveBaselineParameters(factory, purpose).orElse(null);
+ if (baseline != null) {
+ applyClientBaseline(client, baseline);
+ }
+ return baseline;
+ }
+
+ /**
+ * The synthesized client's consumer defaults, shared by the build-time overlay and every reload lambda so both
+ * agree on what a dropped companion member reverts to: the {@code {TLSv1.3, TLSv1.2}} floor, and an unrestricted
+ * cipher list (an empty include list means "no restriction" in Jetty). Both are cleared/re-pinned unconditionally
+ * because the factory is long-lived and persists setter state across {@code reload()}. The provider and endpoint
+ * identification are per-consumer settings applied once at build, not part of this per-delivery reset.
+ */
+ private static void applyClientConfig(SslContextFactory.Client client) {
+ client.setIncludeProtocols(TlsContexts.DEFAULT_ENABLED_PROTOCOLS.toArray(new String[0]));
+ client.setIncludeCipherSuites();
+ }
+
+ private static void applyServerConfig(SslContextFactory.Server sslContextFactory, String sslProviderString,
+ boolean requireTrustedClientCertOnConnect, boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ if (ciphers != null && !ciphers.isEmpty()) {
+ sslContextFactory.setIncludeCipherSuites(ciphers.toArray(new String[0]));
+ } else {
+ // Clear the include list explicitly (not just rely on the fresh-factory default), for the same reason
+ // needClientAuth is reset below: this method is re-applied on each reload of a long-lived factory, so a
+ // prior companion delivery that pinned cipher suites must revert to the consumer default before a later
+ // companion (or its absence) is overlaid. An empty include list means "no restriction" in Jetty --
+ // SslContextFactory.processIncludeExcludePatterns falls back to the SSLContext's enabled suites.
+ sslContextFactory.setIncludeCipherSuites();
+ }
+ // Pin the enabled protocols even when unconfigured, matching the {TLSv1.3, TLSv1.2} floor the native
+ // Netty path applies rather than deferring to the provider default. A factory-supplied companion,
+ // applied afterwards by applyServerBaseline, still overrides this.
+ if (protocols != null && !protocols.isEmpty()) {
+ sslContextFactory.setIncludeProtocols(protocols.toArray(new String[0]));
+ } else {
+ sslContextFactory.setIncludeProtocols(TlsContexts.DEFAULT_ENABLED_PROTOCOLS.toArray(new String[0]));
+ }
+ if (StringUtils.isNotBlank(sslProviderString)) {
+ sslContextFactory.setProvider(sslProviderString);
+ }
+ if (requireTrustedClientCertOnConnect) {
+ sslContextFactory.setNeedClientAuth(true);
+ sslContextFactory.setTrustAll(false);
+ } else {
+ // PIP-478: optional client auth requests but does not require a client cert. An untrusted
+ // client cert is accepted at the handshake only when tlsAllowInsecureConnection=true, aligning the
+ // web listener with the Netty binary listener's semantics and diverging from the pre-5.0 Jetty
+ // path, which trusted any presented client cert whenever client auth was optional (see PIP-478
+ // Security Considerations).
+ //
+ // The actual enforcement is the trust managers baked into the SSLContext the framework hands to
+ // Jetty via setSslContext (built from the WEB TlsPolicy's allowInsecureConnection: CA-validating
+ // when secure, insecure-trust-all when insecure). Jetty's own setTrustAll only takes effect when
+ // Jetty builds the SSLContext itself, so it is inert on this setSslContext path; we still scope it
+ // to the insecure flag so the two never disagree (defence in depth) rather than leaving the
+ // inherited unconditional setTrustAll(true).
+ // Clear needClientAuth explicitly (not just rely on the fresh-factory default): this method is
+ // re-applied on each reload, so a prior companion delivery that set needClientAuth must be reset to
+ // the consumer default here before a later companion (or its absence) is overlaid.
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(true);
+ sslContextFactory.setTrustAll(allowInsecureConnection);
+ }
+ // https://jetty.org/docs/jetty/12.1/operations-guide/protocols/index.html#ssl-sni
+ // Set to false for backwards compatibility with Jetty 9.x
+ sslContextFactory.setSniRequired(false);
+ }
+
+ /**
+ * Ask the factory to supply a native Jetty {@code jettyClass} for {@code purpose} (one-shot). Jetty's
+ * {@link SslContextFactory.Server} and {@link SslContextFactory.Client} are well-known SPI classes, so a
+ * custom factory MAY build one directly; the default {@code FileBasedTlsFactory} returns
+ * {@link Optional#empty()}, in which case the caller synthesizes the factory from an {@code SSLContext}
+ * subscription. A supplied instance is the factory's own (unstarted, same-instance-per-purpose,
+ * factory-driven reload) — the caller returns it verbatim and keeps the {@link TlsHandle} for disposal.
+ * Resolved at factory-build time (off any event loop), mirroring {@link #resolveBaselineParameters}.
+ */
+ private static <T extends SslContextFactory> Optional<TlsHandle<T>> acquireNativeJettyFactory(
+ PulsarTlsFactory factory, TlsPurpose purpose, Class<T> jettyClass) {
+ return awaitAcquisition(factory.createInstance(purpose, jettyClass), purpose);
+ }
+
+ /**
+ * Request the factory's optional {@code SSLParameters} companion for a purpose (one-shot) at factory-build
+ * time, joining off any event loop, and return the supplied instance or {@link Optional#empty()} when the
+ * factory supplies none. Rotation deliveries do NOT use this: they re-request the companion asynchronously
+ * inside {@link JettyReloadCoordinator} (never joined on the delivery thread) and unwrap it via
+ * {@link #extractBaseline}.
+ */
+ private static Optional<SSLParameters> resolveBaselineParameters(PulsarTlsFactory factory, TlsPurpose purpose) {
+ return Optional.ofNullable(
+ extractBaseline(awaitAcquisition(factory.createInstance(purpose, SSLParameters.class), purpose)));
+ }
+
+ /**
+ * Unwrap the factory's {@code SSLParameters} companion from its handle, disposing the handle afterwards (a
+ * companion carries no reference-counted state). Returns {@code null} when the factory supplied none
+ * ({@link Optional#empty()}). Used both by the build-time {@link #resolveBaselineParameters} and by the
+ * asynchronous per-rotation re-request in {@link JettyReloadCoordinator}.
+ */
+ private static SSLParameters extractBaseline(Optional<TlsHandle<SSLParameters>> handle) {
+ if (handle.isEmpty()) {
+ return null;
+ }
+ TlsHandle<SSLParameters> paramsHandle = handle.get();
+ try {
+ return paramsHandle.get();
+ } finally {
+ paramsHandle.dispose();
+ }
+ }
+
+ /**
+ * Await a factory acquisition made during a synchronous builder, unwrapping {@link CompletionException}
+ * so a configuration failure surfaces as its own cause. The underlying messages ("No TLS material
+ * configured for server purpose WEB") are the actionable ones and should not arrive wrapped.
+ *
+ * @param pending the acquisition
+ * @param purpose the purpose being acquired, for the failure message
+ * @return the acquisition result
+ */
+ private static <T> T awaitAcquisition(CompletableFuture<T> pending, TlsPurpose purpose) {
+ try {
+ return pending.join();
+ } catch (CompletionException e) {
+ Throwable cause = e.getCause() != null ? e.getCause() : e;
+ if (cause instanceof RuntimeException runtime) {
+ throw runtime;
+ }
+ if (cause instanceof Error error) {
+ throw error;
+ }
+ throw new IllegalStateException("Failed to acquire TLS material for purpose " + purpose, cause);
+ }
+ }
+
+ /**
+ * Overlay a factory-supplied engine baseline onto a synthesized server factory (PIP-478 merge order):
+ * enabled protocols/cipher suites when the companion sets them, and the companion's client-auth mode as
+ * authoritative (rule 4) — {@code needClientAuth} wins over {@code wantClientAuth}, neither means none.
+ */
+ private static void applyServerBaseline(SslContextFactory.Server sslContextFactory, SSLParameters baseline) {
+ if (baseline.getProtocols() != null) {
+ sslContextFactory.setIncludeProtocols(baseline.getProtocols());
+ }
+ if (baseline.getCipherSuites() != null) {
+ sslContextFactory.setIncludeCipherSuites(baseline.getCipherSuites());
+ }
+ if (baseline.getNeedClientAuth()) {
+ sslContextFactory.setNeedClientAuth(true);
+ } else if (baseline.getWantClientAuth()) {
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(true);
+ } else {
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(false);
+ }
+ }
+
+ /**
+ * Overlay a factory-supplied engine baseline onto a synthesized client factory: enabled protocols/cipher
+ * suites only (client-auth is a server concept; SNI/hostname verification remain per-connection).
+ */
+ private static void applyClientBaseline(SslContextFactory.Client client, SSLParameters baseline) {
+ if (baseline.getProtocols() != null) {
+ client.setIncludeProtocols(baseline.getProtocols());
+ }
+ if (baseline.getCipherSuites() != null) {
+ client.setIncludeCipherSuites(baseline.getCipherSuites());
+ }
+ }
+
+ /**
+ * Per-subscription reload coordinator for the synthesized Jetty paths. It ports the two ordering guarantees
+ * of {@code TlsContextAcquisition.SynthesizingSubscription} to Jetty's hot-reload API, which the naive
+ * "compose {@code createInstance(SSLParameters)} then {@code reload}" delivery lacked:
+ *
+ * <ul>
+ * <li><b>Generation guard.</b> Each delivery captures a strictly increasing generation (deliveries are
+ * serial per subscription, per the SPI contract). A rotation's companion re-request is composed
+ * asynchronously and may complete on an arbitrary thread and out of order, so its {@code reload(...)}
+ * is applied — under a lock — only while its generation is still the latest; a companion superseded
+ * by a newer rotation is dropped rather than pinning the listener to a stale context/baseline.</li>
+ * <li><b>Last-good baseline retention.</b> The last successfully-resolved companion is retained (seeded
+ * from the build-time baseline). A transient companion-fetch failure during rotation reloads with that
+ * last-good baseline rather than consumer defaults, so it cannot silently drop protocols/ciphers or
+ * (server side) client-auth. The retained baseline is updated only for a successfully-resolved,
+ * non-superseded companion, under the same lock.</li>
+ * </ul>
+ *
+ * <p>The companion is never joined on the delivery thread (the self-deadlock hazard described on the class
+ * javadoc); only the <em>first</em> delivery — which fires synchronously inside the subscribe call, before the
+ * built factory is even returned — sets the already-overlaid context directly, mirroring
+ * {@code SynthesizingSubscription}'s pre-fetched first delivery. Every later delivery is a rotation and
+ * re-requests the companion, <em>including one that arrives before the connector/client starts</em>; whether
+ * the factory is started only decides how the result is applied (Jetty's {@code reload(...)} once started, the
+ * same setters directly before), so a factory started after such a rotation starts with that rotation's
+ * material AND its companion policy rather than the stale build-time baseline.
+ */
+ private static final class JettyReloadCoordinator {
+
+ private final PulsarTlsFactory factory;
+ private final TlsPurpose purpose;
+ // Where publish() runs. The companion request is composed, never joined — but for the DEFAULT
+ // factory it completes synchronously (SSLParameters is an unsupported class, so createInstance
+ // returns an already-completed empty future), which would run the whole Jetty reload inline on the
+ // delivery thread, i.e. while the factory holds its source monitor. Dispatching keeps the source
+ // monitor out of the Jetty lock chain and honours the delivery contract's "cheap non-blocking store".
+ private final Executor reloadExecutor;
+ private final SslContextFactory target;
+ // Applies the rotated context + (nullable) companion baseline inside Jetty's reload lambda.
+ private final BiConsumer<SSLContext, SSLParameters> applyReload;
+ // Last successfully-resolved companion, seeded from the pre-fetched build-time baseline. Retained across
+ // a transient companion-fetch failure so a rotation cannot silently downgrade engine policy.
+ private volatile SSLParameters lastBaseline;
+ // One-shot: only the first (synchronous, pre-fetched) delivery reuses the build-time baseline; every
+ // later delivery is a rotation and re-requests the companion, started or not.
+ private final AtomicBoolean firstDelivery = new AtomicBoolean(true);
+ private final AtomicLong deliveryGeneration = new AtomicLong();
+ private long lastPublishedGeneration;
+ // A rotation's companion request is composed asynchronously, so its completion can land after the
+ // owner disposed the subscription (and, on the server path, after Jetty stopped the connector).
+ // Reloading a stopped/abandoned factory then would be a pointless mutation at best.
+ private final AtomicBoolean disposed = new AtomicBoolean();
+
+ JettyReloadCoordinator(PulsarTlsFactory factory, TlsPurpose purpose, Executor reloadExecutor,
+ SslContextFactory target, SSLParameters initialBaseline,
+ BiConsumer<SSLContext, SSLParameters> applyReload) {
+ this.factory = factory;
+ this.purpose = purpose;
+ this.reloadExecutor = reloadExecutor == null ? Runnable::run : reloadExecutor;
Review Comment:
Agreed — 82019a67ae3. Made required rather than permissive; the code is additive with no production callers, so there is no compatibility cost now and a real one later.
One improvement on placement: the `requireNonNull` goes at both public builder entry points rather than in the coordinator. On the native-factory path the coordinator is never constructed, so a null would have sailed through your suggested placement and only surfaced later if the custom factory stopped supplying its native instance. Validating at the entry also fails before any factory acquisition side effects.
Small correction: "every production caller would [pass null]" — there are no production callers on this branch at all; the two declarations are the only non-test references, which is what makes this free to tighten now.
Worth being explicit that non-null is not the same as asynchronous: `Runnable::run` is non-null and still inline. What actually protects the invariant is the dispatch test above, which now fails if the reload runs inline.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/JettyTlsFactory.java:
##########
@@ -0,0 +1,637 @@
+/*
+ * 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.jetty.tls;
+
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.tls.impl.TlsContexts;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * The framework's Jetty integration for the PIP-478 TLS SPI. Both {@link SslContextFactory.Server} and
+ * {@link SslContextFactory.Client} are well-known SPI classes: the framework first asks the
+ * {@link PulsarTlsFactory} to supply one natively (a custom factory may build and own it, reload
+ * included); only when the factory returns {@code empty()} for the Jetty class does the framework
+ * synthesize a <em>vanilla</em> (never subclassed) one from an {@code SSLContext} subscription. The
+ * default {@code FileBasedTlsFactory} returns {@code empty()} for the Jetty classes, so the synthesized
+ * path is the usual one.
+ *
+ * <p><b>Factory-supplied (native) instances.</b> When the factory supplies the Jetty factory directly it
+ * is handed back <em>unstarted</em> (the connector / {@code HttpClient} starts it), is the factory's
+ * same-instance-per-purpose, and the factory owns its reload on material rotation. The framework only
+ * holds the returned {@link TlsHandle} for disposal and never drives {@code setSslContext}/{@code reload}
+ * or overlays consumer configuration on such an instance.
+ *
+ * <p>This deliberately abandons the unsound {@code getSslContext()} override of the superseded PIP-337
+ * {@code JettySslContextFactory}. Instead it uses
+ * Jetty's documented hot-reload API — the same one {@code KeyStoreScanner} uses: an {@code SSLContext}
+ * subscription drives {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each
+ * later delivery (once started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context and re-selects
+ * protocols/ciphers. Existing connections keep their sessions; new connections use the new context.
+ *
+ * <p><b>{@code SSLParameters} companion (PIP-478).</b> Because these are synthesized paths (the factory
+ * returned {@code empty()} for the Jetty class and supplies only the {@code SSLContext}), the framework also
+ * asks the factory for its optional {@code javax.net.ssl.SSLParameters} companion — the engine-level baseline
+ * a bare {@code SSLContext} cannot express — and maps its non-null members onto the Jetty setters: enabled
+ * protocols ({@link SslContextFactory#setIncludeProtocols}) and cipher suites
+ * ({@link SslContextFactory#setIncludeCipherSuites}), and (server side, merge rule 4) the authoritative
+ * client-auth mode ({@link SslContextFactory.Server#setNeedClientAuth} /
+ * {@link SslContextFactory.Server#setWantClientAuth}). The initial companion is overlaid before start (at build
+ * time); on each subsequent <em>rotation</em> delivery it is re-requested <em>asynchronously</em> — the reload
+ * callback composes {@code createInstance(purpose, SSLParameters.class)} with {@code whenComplete} and only then
+ * calls {@code reload(...)}, so engine policy rotates with material (pip-478.md:736) yet the companion is
+ * <b>never joined on the delivery thread</b>. Joining there would self-deadlock a custom factory that dispatches
+ * companion creation to the same single-thread scheduler that runs the poll delivery — the exact hazard
+ * {@code TlsContextAcquisition.SynthesizingSubscription} avoids by composing the companion asynchronously.
+ *
+ * <p>Because those asynchronous re-requests complete on arbitrary threads and may finish out of order, the
+ * synthesized reload mirrors the two ordering guarantees of {@code SynthesizingSubscription} (see
+ * {@code JettyReloadCoordinator}): each delivery captures a strictly increasing <em>generation</em> and applies
+ * its {@code reload(...)} only while that generation is still the latest, so a companion superseded by a newer
+ * rotation is dropped rather than pinning the listener to a stale context/baseline; and the last
+ * successfully-resolved companion is <em>retained</em> (seeded from the build-time baseline) so a transient
+ * companion-fetch failure during rotation reloads with that last-good baseline rather than downgrading engine
+ * policy (protocols/ciphers and, server side, client-auth) to consumer defaults. Consumer defaults are still
+ * re-applied <em>in full</em> first inside every {@code reload(...)} lambda — protocols, cipher suites and, server
+ * side, client-auth are each re-pinned or cleared unconditionally, since the long-lived {@code SslContextFactory}
+ * persists setter state across {@code reload()} — so any companion member legitimately dropped by a newer delivery
+ * reverts to the consumer default rather than staying stuck from the previous companion.
+ * {@code empty()} leaves the consumer's configuration in force, exactly as before.
+ */
+@CustomLog
+public final class JettyTlsFactory {
+
+ static {
+ // Install Conscrypt process-wide, if present, before any TLS object is built here. Jetty resolves a
+ // JSSE provider by name, so the provider has to be registered by the time a factory is configured.
+ JcaProviders.ensureConscryptRegistered();
+ }
+
+ private JettyTlsFactory() {
+ }
+
+ /**
+ * A Jetty server factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the web service stops.
+ *
+ * @param sslContextFactory the (unstarted) Jetty server factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableServerTls(SslContextFactory.Server sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * A Jetty client factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the owning HTTP client
+ * / servlet is destroyed.
+ *
+ * @param sslContextFactory the (unstarted) Jetty client factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableClientTls(SslContextFactory.Client sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * Build a self-reloading {@link SslContextFactory.Server} for a purpose, handed back <em>unstarted</em>
+ * (Jetty starts it with the connector lifecycle) with its initial {@code SSLContext} already set.
+ *
+ * <p><b>Must not be called from the factory's blocking executor.</b> This builder blocks on the
+ * factory's acquisition, and the default factory dispatches acquisitions to
+ * {@code TlsFactoryInitContext.blockingExecutor()} — so calling it from that executor waits on work
+ * queued behind itself, which deadlocks when the executor is single-threaded. Call it from the owning
+ * component's startup thread.
+ *
+ * @param factory the TLS factory to subscribe to
+ * @param purpose the server purpose (e.g. {@link TlsPurpose#WEB})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param requireTrustedClientCert whether to require (vs. request) a trusted client certificate
+ * @param allowInsecureConnection whether an untrusted client cert is accepted under optional client auth
+ * @param ciphers enabled cipher suites, or {@code null} for defaults
+ * @param protocols enabled protocols, or {@code null} for defaults
+ * @return the reloading factory and its subscription handle
Review Comment:
Added to both builders in c7a8542b7d4, documenting that it must not be null and must not execute inline on the delivery thread, and that `Runnable::run` is the explicit opt-in for same-thread execution (tests).
##########
pulsar-broker-common/src/test/java/org/apache/pulsar/jetty/tls/JettyTlsFactoryTest.java:
##########
@@ -0,0 +1,1341 @@
+/*
+ * 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.jetty.tls;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import com.google.common.io.Resources;
+import io.opentelemetry.api.OpenTelemetry;
+import java.io.File;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.net.Socket;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.FileTime;
+import java.security.KeyStore;
+import java.security.Principal;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+import java.time.Clock;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLParameters;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509ExtendedKeyManager;
+import org.apache.commons.io.FileUtils;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactory;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactorySettings;
+import org.apache.pulsar.common.util.tls.JdkSslContexts;
+import org.apache.pulsar.common.util.tls.PemReader;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.awaitility.Awaitility;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class JettyTlsFactoryTest {
+
+ /**
+ * Reload executor for tests: same-thread, so a delivery's reload has completed by the time the call
+ * that triggered it returns and the assertions below stay deterministic. That publish genuinely runs
+ * OFF the delivery thread when a real executor is supplied has its own test
+ * ({@link #rotationReloadRunsOnTheSuppliedExecutorNotTheDeliveryThread()}).
+ */
+ private static final Executor SAME_THREAD = Runnable::run;
+
+ private static final String CA = resource("certificate-authority/certs/ca.cert.pem");
+ private static final String BROKER_CERT = resource("certificate-authority/server-keys/broker.cert.pem");
+ private static final String BROKER_KEY = resource("certificate-authority/server-keys/broker.key-pk8.pem");
+ private static final String PROXY_CERT = resource("certificate-authority/server-keys/proxy.cert.pem");
+ private static final String PROXY_KEY = resource("certificate-authority/server-keys/proxy.key-pk8.pem");
+ // Client certificates (clientAuth EKU) trusted by the shared CA above.
+ private static final String TRUSTED_CLIENT_CERT = resource("certificate-authority/client-keys/admin.cert.pem");
+ private static final String TRUSTED_CLIENT_KEY = resource("certificate-authority/client-keys/admin.key-pk8.pem");
+ private static final String USER1_CLIENT_CERT = resource("certificate-authority/client-keys/user1.cert.pem");
+ private static final String USER1_CLIENT_KEY = resource("certificate-authority/client-keys/user1.key-pk8.pem");
+ // A self-signed client certificate NOT signed by the shared CA (from a separate my-ca root).
+ private static final String UNTRUSTED_CLIENT_CERT = resource("ssl/my-ca/client-ca.pem");
+ private static final String UNTRUSTED_CLIENT_KEY = resource("ssl/my-ca/client-key.pem");
+
+ private ScheduledExecutorService scheduler;
+ private Path tempDir;
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ scheduler = Executors.newSingleThreadScheduledExecutor();
+ tempDir = Files.createTempDirectory("pip478-jetty-");
+ Files.copy(Paths.get(CA), tempDir.resolve("ca.pem"), StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(BROKER_CERT), tempDir.resolve("cert.pem"), StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(BROKER_KEY), tempDir.resolve("key.pem"), StandardCopyOption.REPLACE_EXISTING);
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown() throws Exception {
+ scheduler.shutdownNow();
+ if (tempDir != null) {
+ FileUtils.deleteDirectory(tempDir.toFile());
+ }
+ }
+
+ @Test
+ public void reloadingServerFactoryServesRotatedCertificateToNewConnections() throws Exception {
+ FileBasedTlsFactory factory = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().refreshIntervalSeconds(1).build());
+ factory.initialize(initContext()).join();
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+
+ Server server = new Server();
+ ServerConnector connector = new ServerConnector(server, reloadable.sslContextFactory());
+ connector.setPort(0);
+ server.setConnectors(new ServerConnector[] {connector});
+ server.start();
+ try {
+ SSLContext clientContext = JdkSslContexts.createSslContext(false,
+ PemReader.loadCertificatesFromPemFile(CA), null, null);
+ int port = connector.getLocalPort();
+
+ BigInteger initialSerial = serverCertSerial(clientContext, port);
+ assertThat(initialSerial).isEqualTo(certSerial(BROKER_CERT));
+
+ // Rotate the server material to a different (proxy) certificate signed by the same CA.
+ Files.copy(Paths.get(PROXY_CERT), tempDir.resolve("cert.pem"), StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(PROXY_KEY), tempDir.resolve("key.pem"), StandardCopyOption.REPLACE_EXISTING);
+ long later = System.currentTimeMillis() + 5000;
+ Files.setLastModifiedTime(tempDir.resolve("cert.pem"), FileTime.fromMillis(later));
+ Files.setLastModifiedTime(tempDir.resolve("key.pem"), FileTime.fromMillis(later));
+
+ BigInteger proxySerial = certSerial(PROXY_CERT);
+ Awaitility.await().atMost(Duration.ofSeconds(15))
+ .until(() -> serverCertSerial(clientContext, port).equals(proxySerial));
+ assertThat(serverCertSerial(clientContext, port))
+ .as("new connections use the rotated certificate")
+ .isEqualTo(proxySerial).isNotEqualTo(initialSerial);
+ } finally {
+ reloadable.subscription().dispose();
+ server.stop();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478: a self-reloading {@link SslContextFactory.Client} presents rotated client-certificate
+ * material to new connections while the factory stays alive (mirrors the server rotation test).
+ */
+ @Test
+ public void reloadingClientFactoryPresentsRotatedClientCertOnNewConnections() throws Exception {
+ // Distinct filenames from the server rotation test's cert.pem/key.pem; these hold a client-auth
+ // certificate (the broker/proxy server certs carry a serverAuth-only EKU and cannot be presented as
+ // a client identity).
+ Path clientCert = tempDir.resolve("clientcert.pem");
+ Path clientKey = tempDir.resolve("clientkey.pem");
+ Files.copy(Paths.get(TRUSTED_CLIENT_CERT), clientCert, StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(TRUSTED_CLIENT_KEY), clientKey, StandardCopyOption.REPLACE_EXISTING);
+
+ FileBasedTlsFactory factory = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.BROKER_CLIENT, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ clientCert.toString(), clientKey.toString())),
+ FileBasedTlsFactorySettings.builder().refreshIntervalSeconds(1).build());
+ factory.initialize(initContext()).join();
+
+ JettyTlsFactory.ReloadableClientTls reloadable = JettyTlsFactory.createReloadingClientFactory(
+ factory, TlsPurpose.BROKER_CLIENT, SAME_THREAD, null, true);
+ SslContextFactory.Client clientFactory = reloadable.sslContextFactory();
+ clientFactory.start();
+ try {
+ assertThat(presentedClientCertSerial(clientFactory)).isEqualTo(certSerial(TRUSTED_CLIENT_CERT));
+
+ // Rotate the client identity to a different client certificate signed by the same CA.
+ Files.copy(Paths.get(USER1_CLIENT_CERT), clientCert, StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(USER1_CLIENT_KEY), clientKey, StandardCopyOption.REPLACE_EXISTING);
+ long later = System.currentTimeMillis() + 5000;
+ Files.setLastModifiedTime(clientCert, FileTime.fromMillis(later));
+ Files.setLastModifiedTime(clientKey, FileTime.fromMillis(later));
+
+ BigInteger rotatedSerial = certSerial(USER1_CLIENT_CERT);
+ Awaitility.await().atMost(Duration.ofSeconds(15))
+ .until(() -> presentedClientCertSerial(clientFactory).equals(rotatedSerial));
+ assertThat(presentedClientCertSerial(clientFactory))
+ .as("new connections present the rotated client certificate")
+ .isEqualTo(rotatedSerial).isNotEqualTo(certSerial(TRUSTED_CLIENT_CERT));
+ } finally {
+ clientFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ // Handshake the reloading client factory's current context against a client-auth-requiring server and
+ // return the serial of the client certificate the server observed.
+ private BigInteger presentedClientCertSerial(SslContextFactory.Client clientFactory) throws Exception {
+ SSLContext serverContext = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ try (SSLServerSocket serverSocket =
+ (SSLServerSocket) serverContext.getServerSocketFactory().createServerSocket(0)) {
+ serverSocket.setNeedClientAuth(true);
+ // TLSv1.2 so client auth completes symmetrically within the handshake (avoids the TLS 1.3
+ // post-handshake close race where the server closes before the client flushes its Finished).
+ serverSocket.setEnabledProtocols(new String[] {"TLSv1.2"});
+ serverSocket.setSoTimeout(15000);
+ int port = serverSocket.getLocalPort();
+ CompletableFuture<BigInteger> serverSaw = new CompletableFuture<>();
+ Thread serverThread = new Thread(() -> {
+ try (SSLSocket accepted = (SSLSocket) serverSocket.accept()) {
+ accepted.setSoTimeout(15000);
+ accepted.startHandshake();
+ X509Certificate peer = (X509Certificate) accepted.getSession().getPeerCertificates()[0];
+ serverSaw.complete(peer.getSerialNumber());
+ } catch (Throwable t) {
+ serverSaw.completeExceptionally(t);
+ }
+ });
+ serverThread.setDaemon(true);
+ serverThread.start();
+
+ SSLContext clientContext = clientFactory.getSslContext();
+ try (SSLSocket clientSocket =
+ (SSLSocket) clientContext.getSocketFactory().createSocket("localhost", port)) {
+ clientSocket.setEnabledProtocols(new String[] {"TLSv1.2"});
+ clientSocket.setSoTimeout(15000);
+ clientSocket.startHandshake();
+ }
+ return serverSaw.get(15, TimeUnit.SECONDS);
+ }
+ }
+
+ /**
+ * PIP-478: under optional client auth ({@code requireTrustedClientCert=false}), an <em>untrusted</em>
+ * client certificate is rejected at the web listener's handshake when {@code allowInsecureConnection=false}
+ * and accepted when it is true; a trusted client certificate is accepted in both cases.
+ */
+ @Test
+ public void optionalClientAuthScopesTrustAllToInsecureFlag() throws Exception {
+ // Secure (insecure=false): untrusted client cert is rejected, trusted client cert is accepted. The
+ // server aborts the handshake, surfaced to the client either as an SSLHandshakeException or, once the
+ // server has already sent its close/alert, as a broken-pipe SocketException — both are handshake
+ // failures.
+ try (JettyServer secure = startWebServer(false)) {
+ assertThatThrownBy(() -> handshakeWithClientCert(secure.port, UNTRUSTED_CLIENT_CERT, UNTRUSTED_CLIENT_KEY))
+ .as("an untrusted client cert must be rejected when insecure=false")
+ .isInstanceOf(IOException.class);
+ handshakeWithClientCert(secure.port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY);
+ }
+ // Insecure (insecure=true): both untrusted and trusted client certs are accepted (trust-all).
+ try (JettyServer insecure = startWebServer(true)) {
+ handshakeWithClientCert(insecure.port, UNTRUSTED_CLIENT_CERT, UNTRUSTED_CLIENT_KEY);
+ handshakeWithClientCert(insecure.port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY);
+ }
+ }
+
+ /**
+ * PIP-478: a factory that supplies its {@code SSLContext} together with an {@code SSLParameters} companion
+ * drives the synthesized server {@link SslContextFactory.Server} — its enabled protocols/ciphers and its
+ * client-auth mode are mapped from the companion, the latter authoritatively (merge rule 4).
+ */
+ @Test
+ public void serverFactoryMapsCompanionProtocolsAndClientAuth() throws Exception {
+ SSLParameters companion = new SSLParameters();
+ companion.setProtocols(new String[] {"TLSv1.2"});
+ companion.setCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});
+ companion.setNeedClientAuth(true);
+
+ FileBasedTlsFactory delegate = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().build());
+ CompanionFactory factory = new CompanionFactory(delegate, companion);
+ factory.initialize(initContext()).join();
+
+ // Consumer config asks for no protocol/cipher restriction and only optional client auth; the companion
+ // overrides all three.
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ try {
+ assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+ assertThat(sslContextFactory.getIncludeCipherSuites())
+ .containsExactly("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
+ assertThat(sslContextFactory.getNeedClientAuth()).isTrue();
+ } finally {
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * T4: the companion's protocol restriction and {@code needClientAuth} are not just mapped onto the
+ * synthesized Jetty {@link SslContextFactory.Server} getters — they decide a real handshake against a live
+ * server. A trusted client certificate over the allowed protocol succeeds; a client presenting no
+ * certificate is rejected (needClientAuth); a client offering only a disallowed protocol is rejected.
+ */
+ @Test
+ public void serverCompanionNeedClientAuthAndProtocolEnforcedAtHandshake() throws Exception {
+ SSLParameters companion = new SSLParameters();
+ companion.setProtocols(new String[] {"TLSv1.2"});
+ companion.setNeedClientAuth(true);
+
+ FileBasedTlsFactory delegate = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().build());
+ CompanionFactory factory = new CompanionFactory(delegate, companion);
+ factory.initialize(initContext()).join();
+
+ // Consumer config asks for no protocol restriction and only optional client auth; the companion wins.
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ Server server = new Server();
+ ServerConnector connector = new ServerConnector(server, reloadable.sslContextFactory());
+ connector.setPort(0);
+ server.setConnectors(new ServerConnector[] {connector});
+ server.start();
+ int port = connector.getLocalPort();
+ try {
+ // A trusted client certificate over the allowed protocol completes the handshake.
+ handshakeWithClientCert(port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY);
+ // The companion's needClientAuth rejects a client that presents no certificate.
+ assertThatThrownBy(() -> handshakeWithoutClientCert(port))
+ .as("needClientAuth from the companion rejects a client with no certificate")
+ .isInstanceOf(IOException.class);
+ // The companion's TLSv1.2-only restriction rejects a client offering only TLSv1.3.
+ assertThatThrownBy(() -> handshakeWithClientCert(port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY,
+ "TLSv1.3"))
+ .as("a TLSv1.3-only client cannot handshake with the companion-pinned TLSv1.2 server")
+ .isInstanceOf(IOException.class);
+ } finally {
+ reloadable.subscription().dispose();
+ server.stop();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 (pip-478.md:736): the {@code SSLParameters} companion is re-requested on <em>every</em>
+ * {@code SSLContext} delivery, not just at build time — so engine policy (here the server client-auth mode)
+ * rotates with material. A companion that flips {@code needClientAuth} on rotation must be reflected in the
+ * synthesized Jetty {@link SslContextFactory.Server} after the reload, and dropping the companion must
+ * revert client-auth to the consumer default rather than leaving the prior value stuck.
+ *
+ * <p>The companion is resolved on the <em>same single-thread scheduler</em> that runs the poll deliveries
+ * (see {@link CompanionFactory}'s executor): this reproduces the self-deadlock hazard a synchronous
+ * {@code join} on the delivery thread would hit. The reload path re-requests the companion asynchronously,
+ * so the rotation still applies (the assertions are awaited rather than read synchronously).
+ */
+ @Test
+ public void serverCompanionClientAuthRotatesWithMaterialOnReload() throws Exception {
+ // Build-time companion: no client auth. This overrides the consumer default (optional client auth).
+ SSLParameters noClientAuth = new SSLParameters();
+ noClientAuth.setNeedClientAuth(false);
+
+ FileBasedTlsFactory delegate = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().refreshIntervalSeconds(1).build());
+ // Dispatch companion creation onto the shared scheduler (the delivery thread), so a join inside the
+ // reload callback would deadlock; the async re-request must keep the rotation working.
+ CompanionFactory factory = new CompanionFactory(delegate, noClientAuth, scheduler);
+ factory.initialize(initContext()).join();
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ // Start standalone (no full Jetty server needed) so the reload path (isStarted()) runs on delivery.
+ sslContextFactory.start();
+ try {
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("the build-time companion (needClientAuth=false) is authoritative")
+ .isFalse();
+
+ // Flip the companion to require client auth, then rotate material to trigger an SSLContext delivery.
+ SSLParameters needClientAuth = new SSLParameters();
+ needClientAuth.setNeedClientAuth(true);
+ factory.setCompanion(needClientAuth);
+ rotateWebMaterial();
+
+ // The reload re-requests the companion and re-applies it under Jetty's lock, so the new
+ // needClientAuth takes effect on the synthesized factory.
+ Awaitility.await().atMost(Duration.ofSeconds(15)).until(sslContextFactory::getNeedClientAuth);
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("the companion is re-requested on delivery, so client-auth rotates with material")
+ .isTrue();
+
+ // Drop the companion entirely and rotate again: client-auth must revert to the consumer default
+ // (optional client auth => wantClientAuth, needClientAuth cleared) instead of staying stuck at need.
+ factory.setCompanion(null);
+ rotateWebMaterial();
+ Awaitility.await().atMost(Duration.ofSeconds(15)).until(() -> !sslContextFactory.getNeedClientAuth());
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("dropping the companion reverts needClientAuth to the consumer default")
+ .isFalse();
+ assertThat(sslContextFactory.getWantClientAuth())
+ .as("the consumer default (optional client auth) is restored")
+ .isTrue();
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 generation guard: two rotation companions that complete OUT OF ORDER must leave the NEWER
+ * rotation's context and baseline applied, never regressing to the older one. Each rotation captures a
+ * strictly increasing delivery generation; when the older rotation's companion completes last, its
+ * reload is dropped because a newer generation has already been published (mirroring
+ * {@code TlsContextAcquisition.SynthesizingSubscription}'s generation-guarded {@code publish}). Without the
+ * guard the stale companion would pin the synthesized {@link SslContextFactory.Server} to the older
+ * context/baseline until the next rotation.
+ */
+ @Test
+ public void serverRotationOutOfOrderCompanionKeepsNewerContextAndBaseline() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext contextA = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext contextB = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ ScriptableFactory factory = new ScriptableFactory(initial, null);
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ // Start standalone so the reload path (isStarted()) runs on each rotation delivery.
+ sslContextFactory.start();
+ try {
+ factory.deferCompanions();
+ // Two rotations: A (older, generation N) then B (newer, generation N+1).
+ factory.deliver(contextA);
+ factory.deliver(contextB);
+
+ SSLParameters baselineA = new SSLParameters();
+ baselineA.setProtocols(new String[] {"TLSv1.2"});
+ SSLParameters baselineB = new SSLParameters();
+ baselineB.setProtocols(new String[] {"TLSv1.3"});
+
+ // Complete the NEWER rotation's companion first, then the older one; the generation guard must
+ // drop the stale (older) result so the newer context/baseline stays applied.
+ factory.completeCompanion(1, baselineB);
+ factory.completeCompanion(0, baselineA);
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(sslContextFactory.getIncludeProtocols())
+ .as("the newer rotation's baseline wins despite the older companion completing last")
+ .containsExactly("TLSv1.3");
+ assertThat(sslContextFactory.getSslContext())
+ .as("the newer rotation's context stays pinned")
+ .isSameAs(contextB);
+ });
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 last-good retention: a rotation whose companion re-request fails transiently must retain the
+ * last successfully-resolved baseline (seeded from the build-time companion) rather than downgrading to
+ * consumer defaults. Here the build companion pins TLSv1.2 and {@code needClientAuth}; the rotation's
+ * companion then fails, and the reload must still apply the rotated context while keeping client-auth and
+ * the protocol restriction — the guarantee {@code SynthesizingSubscription} provides via its retained
+ * {@code lastBaseline}. Without it, the failed companion would silently drop client-auth/protocols.
+ */
+ @Test
+ public void serverRotationCompanionFailureRetainsLastGoodBaseline() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ SSLParameters lastGood = new SSLParameters();
+ lastGood.setProtocols(new String[] {"TLSv1.2"});
+ lastGood.setNeedClientAuth(true);
+ ScriptableFactory factory = new ScriptableFactory(initial, lastGood);
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ sslContextFactory.start();
+ try {
+ // The build-time companion is authoritative and seeds the retained last-good baseline.
+ assertThat(sslContextFactory.getNeedClientAuth()).isTrue();
+ assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+
+ factory.deferCompanions();
+ // Rotate material; the companion re-request for this rotation fails transiently.
+ factory.deliver(rotated);
+ factory.failCompanion(0, new IllegalStateException("companion temporarily unavailable"));
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(sslContextFactory.getSslContext())
+ .as("the rotated context is applied even though the companion failed")
+ .isSameAs(rotated);
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("a transient companion failure retains the last-good client-auth")
+ .isTrue();
+ assertThat(sslContextFactory.getIncludeProtocols())
+ .as("a transient companion failure retains the last-good protocol restriction")
+ .containsExactly("TLSv1.2");
+ });
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 companion revert, cipher suites: a companion that pins cipher suites on one delivery and drops them
+ * on the next must revert to the consumer default (here: no restriction) rather than leaving the stale
+ * allowlist pinned on the long-lived {@link SslContextFactory.Server}, which persists setter state across
+ * {@code reload()}. This is the same guarantee already covered for client-auth in
+ * {@link #serverCompanionClientAuthRotatesWithMaterialOnReload}, extended to the cipher/protocol members.
+ */
+ @Test
+ public void serverDroppedCompanionRevertsCipherSuitesToConsumerDefault() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ SSLParameters buildCompanion = new SSLParameters();
+ buildCompanion.setCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});
+ buildCompanion.setProtocols(new String[] {"TLSv1.2"});
+ ScriptableFactory factory = new ScriptableFactory(initial, buildCompanion);
+
+ // The consumer configures neither ciphers nor protocols, so the defaults are "no cipher restriction" and
+ // the {TLSv1.3, TLSv1.2} protocol floor.
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ sslContextFactory.start();
+ try {
+ assertThat(sslContextFactory.getIncludeCipherSuites())
+ .containsExactly("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
+ assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+
+ // Rotate with a companion that supplies nothing at all (empty()), modelling a delivery that
+ // legitimately drops the previously pinned members.
+ factory.deferCompanions();
+ factory.deliver(rotated);
+ factory.completeCompanion(0, null);
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(sslContextFactory.getIncludeCipherSuites())
+ .as("a dropped companion reverts cipher suites to the consumer default (unrestricted)")
+ .isEmpty();
+ assertThat(sslContextFactory.getIncludeProtocols())
+ .as("a dropped companion reverts protocols to the consumer default floor")
+ .containsExactlyInAnyOrder("TLSv1.3", "TLSv1.2");
+ });
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /** The client path is symmetric: a dropped companion must not leave a stale cipher allowlist pinned. */
+ @Test
+ public void clientDroppedCompanionRevertsCipherSuitesToConsumerDefault() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, USER1_CLIENT_CERT, USER1_CLIENT_KEY, null);
+ SSLParameters buildCompanion = new SSLParameters();
+ buildCompanion.setCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});
+ buildCompanion.setProtocols(new String[] {"TLSv1.2"});
+ ScriptableFactory factory = new ScriptableFactory(initial, buildCompanion);
+
+ JettyTlsFactory.ReloadableClientTls reloadable = JettyTlsFactory.createReloadingClientFactory(
+ factory, TlsPurpose.BROKER_CLIENT, SAME_THREAD, null, true);
+ SslContextFactory.Client clientFactory = reloadable.sslContextFactory();
+ clientFactory.start();
+ try {
+ assertThat(clientFactory.getIncludeCipherSuites())
+ .containsExactly("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
+ assertThat(clientFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+
+ factory.deferCompanions();
+ factory.deliver(rotated);
+ factory.completeCompanion(0, null);
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(clientFactory.getIncludeCipherSuites())
+ .as("a dropped companion reverts cipher suites to the consumer default (unrestricted)")
+ .isEmpty();
+ assertThat(clientFactory.getIncludeProtocols())
+ .as("a dropped companion reverts protocols to the consumer default floor")
+ .containsExactlyInAnyOrder("TLSv1.3", "TLSv1.2");
+ });
+ } finally {
+ clientFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478: a rotation delivered BEFORE the connector starts must still refresh the companion. Only the very
+ * first (pre-fetched, synchronous) delivery reuses the build-time baseline; a later delivery that lands while
+ * the factory is still unstarted re-requests the companion and applies it directly (Jetty's {@code reload()}
+ * is for a live factory), so the started factory runs the rotation's engine policy — protocols, cipher suites
+ * and client-auth — rather than the stale build-time one.
+ */
Review Comment:
Correct — rebase artifact. Moved onto `preStartRotationRefreshesCompanionBeforeStart` in 4487e521180.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [feat][misc] PIP-478: default file-based TLS factory implementation [pulsar]
Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #26271:
URL: https://github.com/apache/pulsar/pull/26271#discussion_r3719669507
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/tls/DefaultBrokerTlsFactory.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.broker.tls;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.client.api.Authentication;
+import org.apache.pulsar.client.api.AuthenticationDataProvider;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactory;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactorySettings;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The broker's default {@code PulsarTlsFactory}: a thin {@link FileBasedTlsFactory} whose purpose→
+ * policy map is composed from a {@link ServiceConfiguration} (PIP-478).
+ *
+ * <p>It lives in {@code pulsar-broker-common} — which owns the Jetty integration and the broker
+ * configuration — so that neither the SPI module nor {@code pulsar-common} carries broker-config
+ * knowledge. The class only <em>composes</em> the map; wiring it into the broker/proxy/web services is
+ * a later stage.
+ */
+public class DefaultBrokerTlsFactory extends FileBasedTlsFactory {
+
+ /**
+ * Construct the broker factory from an already-composed purpose→policy map.
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ super(policies, settings);
+ }
+
+ /**
+ * Construct a broker factory that additionally folds the broker-client authentication's TLS material
+ * over the {@link TlsPurpose#BROKER_CLIENT} file policy (PIP-478).
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ super(policies, settings, authMaterialSuppliers);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}.
+ *
+ * @param conf the broker service configuration
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf) {
+ return fromServiceConfiguration(conf, null);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}, optionally folding the
+ * broker's broker-client {@link Authentication} TLS material over the {@link TlsPurpose#BROKER_CLIENT}
+ * file policy (PIP-478) for the broker's own outbound (broker-to-broker / replication) connections.
+ *
+ * <p>The broker's server material is registered for the {@link TlsPurpose#BROKER},
+ * {@link TlsPurpose#PROXY} and {@link TlsPurpose#WEB} purposes; the broker's outbound
+ * (broker-to-broker) material for {@link TlsPurpose#BROKER_CLIENT}. When {@code brokerClientAuth} is
+ * supplied and a broker-client authentication plugin is configured, its in-memory cert/key override the
+ * {@code brokerClient*} file paths (auth-cert-wins), so the broker presents the right identity to its
+ * peers — the server-side mirror of the client TLS override hook.
+ *
+ * @param conf the broker service configuration
+ * @param brokerClientAuth the broker's broker-client authentication, or {@code null} for no fold
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf,
+ Authentication brokerClientAuth) {
+ Map<TlsPurpose, TlsPolicy> policies = new LinkedHashMap<>();
+ TlsPolicy serverPolicy = serverPolicy(conf);
+ policies.put(TlsPurpose.BROKER, serverPolicy);
+ policies.put(TlsPurpose.PROXY, serverPolicy);
+ policies.put(TlsPurpose.WEB, serverPolicy);
Review Comment:
Fixed in a3d135b77aa. `WEB` now has its own policy: `webServiceTlsProvider`, `webServiceTlsProtocols` and `webServiceTlsCiphers` take precedence, falling back to `tlsProvider` / `tlsProtocols` / `tlsCiphers` when unset. Material and the insecure flag stay shared. Tests cover the precedence, the fallback, that the binary-listener policy never reads the web keys, and that an engine literal in the web provider selects no JSSE provider.
Two of the three consequences need qualifying, though — both describe today's broker rather than something this series would introduce:
- **Protocol/cipher lists.** `WebService.java:178-180` already passes `config.getTlsCiphers(), config.getTlsProtocols()` to `JettySslContextFactory` — the broker web listener has never read `webServiceTlsProtocols`/`webServiceTlsCiphers`. Honouring them is new behaviour, and arguably fixes a long-standing gap rather than avoiding a new one.
- **The Conscrypt default.** `webServiceTlsProvider` *is* read at that same call site, but it only reaches Jetty's `setProvider()`; the `SSLContext` Jetty serves with comes from `DefaultPulsarSslFactory` via `buildSslConfiguration` (`WebService.java:596`), which passes no provider, and the PIP-337 `getSslContext()` override shadows whatever Jetty would have built. So the default has been inert on the broker web path since 4.0.
That second point is a consequence of the fix worth flagging: honouring it means a deployment on the default will genuinely get Conscrypt for the web listener. Conscrypt ships in the server distribution, and where its native library cannot load the pin now fails loudly at startup rather than being silently ignored. Say the word if you would rather that stayed inert until the wiring PR.
You also found an error in the PIP: it claimed no code reads `webServiceTlsProvider`. True of the proxy (`WebServer.java:159` uses `tlsProvider`), wrong for the broker. Corrected, and extended to state the new precedence.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/tls/DefaultBrokerTlsFactory.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.broker.tls;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.client.api.Authentication;
+import org.apache.pulsar.client.api.AuthenticationDataProvider;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactory;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactorySettings;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The broker's default {@code PulsarTlsFactory}: a thin {@link FileBasedTlsFactory} whose purpose→
+ * policy map is composed from a {@link ServiceConfiguration} (PIP-478).
+ *
+ * <p>It lives in {@code pulsar-broker-common} — which owns the Jetty integration and the broker
+ * configuration — so that neither the SPI module nor {@code pulsar-common} carries broker-config
+ * knowledge. The class only <em>composes</em> the map; wiring it into the broker/proxy/web services is
+ * a later stage.
+ */
+public class DefaultBrokerTlsFactory extends FileBasedTlsFactory {
+
+ /**
+ * Construct the broker factory from an already-composed purpose→policy map.
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ super(policies, settings);
+ }
+
+ /**
+ * Construct a broker factory that additionally folds the broker-client authentication's TLS material
+ * over the {@link TlsPurpose#BROKER_CLIENT} file policy (PIP-478).
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ super(policies, settings, authMaterialSuppliers);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}.
+ *
+ * @param conf the broker service configuration
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf) {
+ return fromServiceConfiguration(conf, null);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}, optionally folding the
+ * broker's broker-client {@link Authentication} TLS material over the {@link TlsPurpose#BROKER_CLIENT}
+ * file policy (PIP-478) for the broker's own outbound (broker-to-broker / replication) connections.
+ *
+ * <p>The broker's server material is registered for the {@link TlsPurpose#BROKER},
+ * {@link TlsPurpose#PROXY} and {@link TlsPurpose#WEB} purposes; the broker's outbound
+ * (broker-to-broker) material for {@link TlsPurpose#BROKER_CLIENT}. When {@code brokerClientAuth} is
+ * supplied and a broker-client authentication plugin is configured, its in-memory cert/key override the
+ * {@code brokerClient*} file paths (auth-cert-wins), so the broker presents the right identity to its
+ * peers — the server-side mirror of the client TLS override hook.
+ *
+ * @param conf the broker service configuration
+ * @param brokerClientAuth the broker's broker-client authentication, or {@code null} for no fold
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf,
+ Authentication brokerClientAuth) {
+ Map<TlsPurpose, TlsPolicy> policies = new LinkedHashMap<>();
+ TlsPolicy serverPolicy = serverPolicy(conf);
+ policies.put(TlsPurpose.BROKER, serverPolicy);
+ policies.put(TlsPurpose.PROXY, serverPolicy);
+ policies.put(TlsPurpose.WEB, serverPolicy);
+ policies.put(TlsPurpose.BROKER_CLIENT, brokerClientPolicy(conf));
+
+ FileBasedTlsFactorySettings settings = FileBasedTlsFactorySettings.builder()
+ .requireTrustedClientCert(conf.isTlsRequireTrustedClientCertOnConnect())
+ .refreshIntervalSeconds(refreshIntervalSeconds(conf))
+ // Engine selection (JDK vs. OpenSSL) mapped from the broker's tlsProvider field: an explicit
+ // engine literal is honored verbatim, a JSSE provider name selects no engine, and an unset
+ // value takes the native engine as OPENSSL_REFCNT when tcnative is available (see
+ // TlsFactorySupport.engineProvider).
+ .engineProvider(TlsFactorySupport.engineProvider(conf.getTlsProvider()))
+ .build();
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authSuppliers =
+ (brokerClientAuth != null && StringUtils.isNotBlank(conf.getBrokerClientAuthenticationPlugin()))
+ ? Map.of(TlsPurpose.BROKER_CLIENT, FileBasedTlsFactory.authMaterialSupplier(brokerClientAuth))
+ : Map.of();
+ return new DefaultBrokerTlsFactory(policies, settings, authSuppliers);
+ }
+
+ private static TlsPolicy serverPolicy(ServiceConfiguration conf) {
+ TlsPolicy.Builder builder = TlsPolicy.builder()
+ .allowInsecureConnection(conf.isTlsAllowInsecureConnection())
+ .enableHostnameVerification(conf.isTlsHostnameVerificationEnabled())
Review Comment:
Fixed in 984fd9d72d2 — with one wrinkle worth recording, because the suggested form would have made it worse.
"Leave it unset" is not expressible: `TlsPolicy.Builder` defaults `enableHostnameVerification` to **true** (secure-by-default for clients), so omitting the setter left every server policy claiming verification was on. My first attempt did exactly that and a new test caught it. It is now pinned to `false` explicitly, which is the inert value for a server engine, with the reasoning recorded. `brokerClientPolicy()` still maps the setting, which is where it belongs.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/tls/DefaultBrokerTlsFactory.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.broker.tls;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.client.api.Authentication;
+import org.apache.pulsar.client.api.AuthenticationDataProvider;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactory;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactorySettings;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The broker's default {@code PulsarTlsFactory}: a thin {@link FileBasedTlsFactory} whose purpose→
+ * policy map is composed from a {@link ServiceConfiguration} (PIP-478).
+ *
+ * <p>It lives in {@code pulsar-broker-common} — which owns the Jetty integration and the broker
+ * configuration — so that neither the SPI module nor {@code pulsar-common} carries broker-config
+ * knowledge. The class only <em>composes</em> the map; wiring it into the broker/proxy/web services is
+ * a later stage.
+ */
+public class DefaultBrokerTlsFactory extends FileBasedTlsFactory {
+
+ /**
+ * Construct the broker factory from an already-composed purpose→policy map.
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ super(policies, settings);
+ }
+
+ /**
+ * Construct a broker factory that additionally folds the broker-client authentication's TLS material
+ * over the {@link TlsPurpose#BROKER_CLIENT} file policy (PIP-478).
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ super(policies, settings, authMaterialSuppliers);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}.
+ *
+ * @param conf the broker service configuration
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf) {
+ return fromServiceConfiguration(conf, null);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}, optionally folding the
+ * broker's broker-client {@link Authentication} TLS material over the {@link TlsPurpose#BROKER_CLIENT}
+ * file policy (PIP-478) for the broker's own outbound (broker-to-broker / replication) connections.
+ *
+ * <p>The broker's server material is registered for the {@link TlsPurpose#BROKER},
+ * {@link TlsPurpose#PROXY} and {@link TlsPurpose#WEB} purposes; the broker's outbound
+ * (broker-to-broker) material for {@link TlsPurpose#BROKER_CLIENT}. When {@code brokerClientAuth} is
+ * supplied and a broker-client authentication plugin is configured, its in-memory cert/key override the
+ * {@code brokerClient*} file paths (auth-cert-wins), so the broker presents the right identity to its
+ * peers — the server-side mirror of the client TLS override hook.
+ *
+ * @param conf the broker service configuration
+ * @param brokerClientAuth the broker's broker-client authentication, or {@code null} for no fold
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf,
+ Authentication brokerClientAuth) {
+ Map<TlsPurpose, TlsPolicy> policies = new LinkedHashMap<>();
+ TlsPolicy serverPolicy = serverPolicy(conf);
+ policies.put(TlsPurpose.BROKER, serverPolicy);
+ policies.put(TlsPurpose.PROXY, serverPolicy);
+ policies.put(TlsPurpose.WEB, serverPolicy);
+ policies.put(TlsPurpose.BROKER_CLIENT, brokerClientPolicy(conf));
+
+ FileBasedTlsFactorySettings settings = FileBasedTlsFactorySettings.builder()
+ .requireTrustedClientCert(conf.isTlsRequireTrustedClientCertOnConnect())
Review Comment:
Agreed — 0aa644b9d76. It is deliberate parity: v4 keyed all three listeners off the same `tlsRequireTrustedClientCertOnConnect`, `JettySslContextFactory` included, so per-listener client-auth was never configurable. The javadoc said the flag applies to every server purpose but not why; it now says so, and spells the property name in full.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/FileBasedTlsFactory.java:
##########
@@ -0,0 +1,768 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.util.ReferenceCountUtil;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import javax.net.ssl.SSLContext;
+import lombok.CustomLog;
+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.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsEndpoint;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The default, file-based {@link PulsarTlsFactory} (PIP-478).
+ *
+ * <p>Immutable after construction: the complete {@code TlsPurpose -> TlsPolicy} map and the
+ * factory-wide {@link FileBasedTlsFactorySettings} are fixed by the constructor and never mutated. The
+ * owning component (the v5 client builder, or {@code DefaultBrokerTlsFactory} on the server side)
+ * composes the final map before constructing the factory.
+ *
+ * <p>Natively supplies the Netty {@code SslContext} (on the configured engine — JDK or OpenSSL) and the
+ * JDK {@code SSLContext}; returns {@code empty()} for every other class (notably Jetty's
+ * {@code SslContextFactory.Server} and {@code SslContextFactory.Client}), which the framework synthesizes
+ * from the JDK {@code SSLContext}. It also
+ * returns {@code empty()} for the {@code javax.net.ssl.SSLParameters} companion (PIP-478): its engine policy
+ * (protocols, ciphers, client-auth mode, hostname verification) is baked natively into the Netty contexts it
+ * builds, so it exposes no separate baseline for the framework to overlay on those.
+ *
+ * <p>A JDK {@code SSLContext} cannot itself carry that policy — enabled protocols and cipher suites,
+ * algorithm constraints and the endpoint-identification algorithm are all per-engine {@code SSLParameters}
+ * settings — so the JDK context this factory returns is a <em>material carrier</em>: it holds the key and
+ * trust managers (built through the pinned providers) and nothing else. Every consumer of it applies the
+ * engine policy itself from the same {@link TlsPolicy}, which is what {@code JettyTlsFactory} does. A
+ * consumer that instead created engines straight from this {@code SSLContext} would get the provider defaults,
+ * so consumers must not do that.
+ *
+ * <p><b>Purpose resolution.</b> A request resolves the requested purpose directly against the configured
+ * {@code TlsPurpose -> TlsPolicy} map. When nothing is configured for the purpose, a {@code CLIENT}-role
+ * purpose resolves to the system default (OS trust store, no client certificate) and a {@code SERVER}-role
+ * purpose fails the request. A resolved-but-unbuildable request completes the future <em>exceptionally</em>
+ * — never {@code empty()}, which strictly means "unsupported {@code (purpose, class)} combination".
+ *
+ * <p><b>Rotation.</b> One {@link TlsMaterialSource} is shared per configured purpose. Server-side
+ * subscribers are pushed rebuilt instances by a background poll (interval from the settings, on the
+ * framework scheduler); client-side one-shot callers re-stat on each request and pick up rotation
+ * naturally. Because a re-stat consumes the source's change signal, an acquisition that observes a change
+ * first also fans it out to that purpose's subscribers, so a rotation is never swallowed by whoever happened
+ * to look first. A failed rebuild keeps the last-good instance, logs at WARN, and retries on the next
+ * change; a subscriber callback that throws is caught and logged, and the subscription stays live.
+ */
+@CustomLog
+public class FileBasedTlsFactory implements PulsarTlsFactory {
+
+ private final Map<TlsPurpose, RegisteredSource> registry;
+ private final FileBasedTlsFactorySettings settings;
+
+ private volatile TlsFactoryInitContext initContext;
+ private volatile TlsReloadMetrics metrics;
+ private volatile RegisteredSource systemDefaultSource;
+ private volatile ScheduledFuture<?> pollFuture;
+ private volatile boolean closed;
+
+ /**
+ * Construct an immutable file-based factory.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ this(policies, settings, Map.of());
+ }
+
+ /**
+ * Construct an immutable file-based factory that additionally folds an authentication plugin's TLS
+ * material over the configured file policy for the named purposes (the server-side {@code BROKER_CLIENT}
+ * fold — PIP-478). For a purpose present in {@code authMaterialSuppliers}, the supplier's
+ * {@code Authentication} material overrides the file policy's key/cert per
+ * {@link AuthProvidedMaterialSource} (auth-cert-wins); other purposes use the file policy unchanged.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ Objects.requireNonNull(policies, "policies must not be null");
+ this.settings = Objects.requireNonNull(settings, "settings must not be null");
+ Objects.requireNonNull(authMaterialSuppliers, "authMaterialSuppliers must not be null");
+ Map<TlsPurpose, RegisteredSource> built = new LinkedHashMap<>();
+ for (Map.Entry<TlsPurpose, TlsPolicy> entry : policies.entrySet()) {
+ TlsPurpose purpose = Objects.requireNonNull(entry.getKey(), "purpose key must not be null");
+ TlsPolicy policy = Objects.requireNonNull(entry.getValue(), "policy must not be null");
+ TlsMaterialSource fileSource = new TlsMaterialSource(policy);
+ Supplier<AuthenticationDataProvider> authSupplier = authMaterialSuppliers.get(purpose);
+ MaterialSource source = authSupplier == null
+ ? fileSource
+ : new AuthProvidedMaterialSource(fileSource, authSupplier);
+ built.put(purpose, new RegisteredSource(purpose, policy, source));
+ }
+ this.registry = Map.copyOf(built);
+ }
+
+ /**
+ * Adapt a component's broker-client {@link Authentication} to a per-refresh
+ * {@link AuthenticationDataProvider} supplier for use with the {@code BROKER_CLIENT} fold constructor.
+ * The supplier re-reads {@code getAuthData()} on each poll so credential rotation is observed; a checked
+ * {@link PulsarClientException} is rethrown unchecked and handled by the factory's keep-last-good poll.
+ *
+ * @param authentication the broker-client authentication plugin (never {@code null})
+ * @return a supplier of the plugin's current authentication data
+ */
+ public static Supplier<AuthenticationDataProvider> authMaterialSupplier(Authentication authentication) {
+ Objects.requireNonNull(authentication, "authentication must not be null");
+ return () -> {
+ try {
+ return resolveAuthData(authentication);
+ } catch (PulsarClientException e) {
+ throw new RuntimeException("Failed to obtain broker-client authentication TLS material", e);
+ }
+ };
+ }
+
+ // The BROKER_CLIENT TLS fold is host-agnostic — TLS key material does not vary by peer — so the
+ // host-less getAuthData() is exactly what we want; isolate its deprecation here.
+ @SuppressWarnings("deprecation")
+ private static AuthenticationDataProvider resolveAuthData(Authentication authentication)
+ throws PulsarClientException {
+ return authentication.getAuthData();
+ }
+
+ @Override
+ public CompletableFuture<Void> initialize(TlsFactoryInitContext context) {
+ try {
+ Objects.requireNonNull(context, "context must not be null");
+ // Required, not optional: every acquisition path in this factory reads files and parses key
+ // material. Without an executor the work would run inline on the caller's thread, which the SPI
+ // contract says may be a consumer event loop. Fail at wiring time rather than stalling a channel.
+ Objects.requireNonNull(context.blockingExecutor(),
+ "TlsFactoryInitContext.blockingExecutor() must not be null: FileBasedTlsFactory performs "
+ + "blocking file and key-material loading and must never run it on a consumer thread");
+ this.initContext = context;
+ // Cancel any poll scheduled by a prior initialize() so a second call does not orphan the first:
+ // the field is overwritten below and the old task would otherwise run forever.
+ ScheduledFuture<?> previousPoll = this.pollFuture;
+ if (previousPoll != null) {
+ previousPoll.cancel(false);
+ }
+ // Same reasoning for the metrics: a prior initialize() registered an observable gauge that stays
+ // registered on the meter until close(), so overwriting the field without closing it would leave
+ // an orphaned callback reporting stale per-purpose timestamps forever.
+ TlsReloadMetrics previousMetrics = this.metrics;
+ if (previousMetrics != null) {
+ previousMetrics.close();
+ }
+ this.metrics = TlsReloadMetrics.create(context.openTelemetry(), context.clock());
+ int interval = settings.refreshIntervalSeconds();
+ if (interval > 0 && context.scheduler() != null) {
+ this.pollFuture = context.scheduler().scheduleWithFixedDelay(
+ this::pollSafely, interval, interval, TimeUnit.SECONDS);
+ }
+ log.debug().attr("purposes", registry.keySet()).attr("refreshIntervalSeconds", interval)
+ .log("Initialized FileBasedTlsFactory");
+ return CompletableFuture.completedFuture(null);
+ } catch (Throwable t) {
+ return CompletableFuture.failedFuture(t);
+ }
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(TlsPurpose purpose, Class<T> instanceClass) {
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, TlsEndpoint endpoint, Class<T> instanceClass) {
+ // The default file-based factory serves purpose-scoped material and ignores the endpoint hint.
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, Class<T> instanceClass, Consumer<T> onLoadOrReload) {
+ if (onLoadOrReload == null) {
+ // SPI contract: argument-validation failures complete the returned future exceptionally — this
+ // method never throws on the calling thread.
+ return CompletableFuture.failedFuture(new NullPointerException("onLoadOrReload must not be null"));
+ }
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ synchronized (source) {
+ // FIX F: close() runs releaseAll() under this same source lock, and may have completed after
+ // the outer closed-check but before this task acquired the lock. Re-check here so we never
+ // build+cache+deliver a context (and register a subscription) whose factory-owned reference
+ // would then never be released — that would leak past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ Subscription<T> subscription = new Subscription<>(instanceClass, onLoadOrReload);
+ // Initial delivery happens-before the returned future completes (same thread, ordered).
+ subscription.deliver(instance);
+ source.subscriptions.add(subscription);
+ return Optional.of((TlsHandle<T>) new SubscriptionHandle<>(source, subscription));
+ }
+ });
+ }
+
+ private <T> CompletableFuture<Optional<TlsHandle<T>>> createOneShot(TlsPurpose purpose, Class<T> instanceClass) {
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ synchronized (source) {
+ // FIX F: re-check under the source lock (see createInstance above) so a task racing a
+ // concurrent close()/releaseAll() never builds+retains a context that then leaks past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ retain(instance);
+ return Optional.of((TlsHandle<T>) new OneShotHandle<>(instance));
+ }
+ });
+ }
+
+ /**
+ * Load (or reuse the cached) instance of {@code instanceClass} for the resolved source, recording a
+ * {@code pulsar.tls.reload} attempt for the source's purpose. A resolution failure upstream (an
+ * unconfigured server purpose) is a startup configuration error and is not counted here — only actual
+ * material loads are. Must be called while holding the source monitor.
+ *
+ * <p>Success is counted only for a <em>real</em> (re)load, mirroring the poll path: the first build of a
+ * context class for this source, or a refresh that found changed material. A repeat one-shot acquisition
+ * that re-serves the memoized context (every new connection, on the acquire-per-connection paths) is not a
+ * reload — counting it would inflate {@code pulsar.tls.reload} and keep advancing
+ * {@code pulsar.tls.last_reload_success}, masking exactly the stalled rotation the Monitoring section
+ * alerts on. Failures stay unconditional: an attempt that threw is always worth counting.
+ */
+ private <T> T loadInitialInstance(RegisteredSource source, Class<T> instanceClass) throws Exception {
+ // Hoisted out of the try so the catch can tell whether this call already CONSUMED a rotation before
+ // failing (see the comment on the catch below). Null means currentMaterial() itself threw, which
+ // commits no baseline and so consumes nothing.
+ MaterialSource.RefreshOutcome outcome = null;
+ try {
+ outcome = source.currentMaterial();
+ // Sampled before acquireInstance, which is what populates the memo (both calls run under the
+ // source monitor held by the caller, so no other acquisition can interleave).
+ boolean firstBuild = source.cachedInstance(instanceClass) == null;
+ T instance = source.acquireInstance(instanceClass, outcome.material(), settings);
+ // Rotation fan-out: currentMaterial() CONSUMES the source's change signal (refresh() commits the new
+ // mtime baseline), so whoever refreshes first is the only caller that ever sees changed=true. Without
+ // this, a one-shot acquisition (or an initial subscribing acquisition) that observes a rotation first
+ // leaves every later poll reporting changed=false and the subscribers on this same purpose wedged on
+ // the pre-rotation instance forever — e.g. an https:// client whose FrameworkHttpClientFactory
+ // subscribes to CLIENT_DEFAULT while another path acquires one-shot on it. Deliver the observed
+ // change here, exactly as the poll would have; a delivery failure arms pendingRedeliver so the next
+ // poll retries. No extra metric is recorded — this shares the single recordLoad below.
+ // Also drive the retry when a previous rotation's fan-out failed: the poll is the usual driver,
+ // but it is disabled entirely when refreshIntervalSeconds <= 0, and even when enabled an
+ // acquisition may get here first. Without this, a subscriber wedged by a failed rebuild would
+ // stay on the pre-rotation instance until the files changed again.
+ boolean retryPending = source.pendingRedeliver();
+ boolean delivered = true;
+ if (outcome.changed() || retryPending) {
+ delivered = source.deliverToSubscribers(outcome.material(), settings);
+ }
+ if (outcome.changed() || retryPending || firstBuild) {
+ recordLoad(source.purpose, delivered);
+ }
+ return instance;
+ } catch (Exception e) {
+ recordLoad(source.purpose, false);
+ // The material parsed (the baseline is committed) but building or delivering the context failed.
+ // currentMaterial() has therefore already CONSUMED this rotation's change signal, so every later
+ // poll would report changed=false and — without arming the redeliver flag here — return early,
+ // leaving the subscribers wedged on the pre-rotation instance until the files change again.
+ // deliverToSubscribers arms the flag itself on a partial delivery failure; this covers the case
+ // where the failure happened before it was ever reached.
+ if (outcome != null && outcome.changed()) {
+ source.armRedeliver();
+ }
+ // Keep-last-good (PIP-478): a one-shot (or initial subscribing) acquisition during a
+ // non-atomic rotation window — e.g. the cert file briefly unreadable while it is being replaced —
+ // must not fail when a prior load already built a context of this class. Serve that last-good
+ // instance and WARN; the reload-failure metric was recorded above. Fail only when there is no
+ // last-good to fall back on (a genuine startup misconfiguration, per the fail-fast contract).
+ T cached = source.cachedInstance(instanceClass);
+ if (cached != null) {
+ log.warn().attr("purpose", source.purpose).exception(e)
+ .log("Failed to load TLS material; serving the last-good instance");
+ return cached;
+ }
+ throw e;
+ }
+ }
+
+ private void recordLoad(TlsPurpose purpose, boolean success) {
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.recordLoad(purpose, success);
+ }
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ ScheduledFuture<?> poll = this.pollFuture;
+ if (poll != null) {
+ poll.cancel(false);
+ }
+ for (RegisteredSource source : registry.values()) {
+ source.releaseAll();
+ }
+ RegisteredSource systemDefault = this.systemDefaultSource;
+ if (systemDefault != null) {
+ systemDefault.releaseAll();
+ }
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.close();
+ }
+ }
+
+ /**
+ * Resolve a requested purpose to the {@link RegisteredSource} that owns its material, applying the
+ * role's terminal-resolution rule when nothing is configured for the purpose.
+ *
+ * @throws TlsMaterialUnavailableException when a server-role purpose has no material configured
+ */
+ private RegisteredSource resolve(TlsPurpose purpose) {
+ Objects.requireNonNull(purpose, "purpose must not be null");
+ RegisteredSource source = registry.get(purpose);
+ if (source != null) {
+ return source;
+ }
+ if (purpose.role() == TlsPurpose.Role.CLIENT) {
+ return systemDefaultSource();
+ }
+ throw new TlsMaterialUnavailableException(
+ "No TLS material configured for server purpose " + purpose);
+ }
+
+ private RegisteredSource systemDefaultSource() {
+ RegisteredSource existing = this.systemDefaultSource;
+ if (existing != null) {
+ return existing;
+ }
+ synchronized (this) {
+ if (this.systemDefaultSource == null) {
+ // System default: verify hostnames, OS trust store, no client certificate. A constant
+ // source (no files, never rotates).
+ TlsPolicy defaultPolicy = TlsPolicy.builder().build();
+ this.systemDefaultSource = new RegisteredSource(
+ TlsPurpose.CLIENT_DEFAULT, defaultPolicy, null);
+ }
+ return this.systemDefaultSource;
+ }
+ }
+
+ private void pollSafely() {
+ if (closed) {
+ return;
+ }
+ try {
+ for (RegisteredSource source : registry.values()) {
+ source.poll(settings, metrics);
+ }
+ } catch (Throwable t) {
+ log.warn().exception(t).log("Unexpected error during TLS material poll");
+ }
+ }
+
+ private <R> CompletableFuture<R> runAsync(Callable<R> task) {
+ CompletableFuture<R> future = new CompletableFuture<>();
+ TlsFactoryInitContext context = this.initContext;
+ // initialize() rejects a null blockingExecutor, so the caller-thread fallback is reachable only before
+ // initialize() has run — a direct-construction path (tests, or a component acquiring during its own
+ // startup) that is by definition not on a consumer event loop.
+ Executor executor = context != null ? context.blockingExecutor() : Runnable::run;
+ try {
+ executor.execute(() -> {
+ try {
+ R result = task.call();
+ if (!future.complete(result)) {
+ // The caller cancelled (or otherwise completed) the future while the acquisition was
+ // still running, so nothing will ever receive this handle. The task has already
+ // retained the context on its behalf, and with the finalizer-free OPENSSL_REFCNT
+ // engine an unbalanced retain is a permanent native leak — dispose the orphan here.
+ disposeOrphan(result);
+ }
+ } catch (Throwable t) {
+ future.completeExceptionally(t);
+ }
+ });
+ } catch (Throwable t) {
+ future.completeExceptionally(t);
+ }
+ return future;
+ }
+
+ /**
+ * Release a handle that was built but could not be delivered to its caller. Both acquisition forms
+ * produce an {@code Optional<TlsHandle<?>>}, and disposing it is exactly what the caller would have done:
+ * it drops the one-shot's retained reference, or unregisters the subscription and releases its borrows.
+ */
+ private static void disposeOrphan(Object result) {
+ if (result instanceof Optional<?> optional && optional.orElse(null) instanceof TlsHandle<?> handle) {
+ try {
+ handle.dispose();
+ } catch (Throwable t) {
+ log.warn().exception(t).log("Failed to dispose an undelivered TLS handle");
+ }
+ }
+ }
+
+ private static boolean isSupported(Class<?> instanceClass) {
+ return instanceClass == SslContext.class || instanceClass == SSLContext.class;
+ }
+
+ private static void retain(Object instance) {
+ if (instance != null) {
+ ReferenceCountUtil.retain(instance);
+ }
+ }
+
+ private static void release(Object instance) {
+ if (instance != null) {
+ ReferenceCountUtil.release(instance);
+ }
+ }
+
+ /**
+ * A configured purpose's material source together with the cached, factory-owned context instances
+ * and the active subscriptions. All state is guarded by the instance monitor.
+ */
+ private static final class RegisteredSource {
+ private final TlsPurpose purpose;
+ private final TlsPolicy policy;
+ // Null for the system-default source, whose constant material never rotates.
+ private final MaterialSource source;
+ private final CopyOnWriteArrayList<Subscription<?>> subscriptions = new CopyOnWriteArrayList<>();
+
+ private SslContext nettyContext;
+ private TlsMaterial nettyMaterial;
+ private SSLContext jdkContext;
+ private TlsMaterial jdkMaterial;
+ // Set when a rotation's rebuild/delivery to some subscriber failed, so the next poll re-attempts the
+ // rebuild even if the source now reports changed=false (PIP-478 L1 reload-wedge guard).
+ private boolean pendingRedeliver;
+
+ RegisteredSource(TlsPurpose purpose, TlsPolicy policy, MaterialSource source) {
+ this.purpose = purpose;
+ this.policy = policy;
+ this.source = source;
+ }
+
+ /**
+ * Refresh the material, reporting whether it changed in value. The system-default source has no
+ * backing files, so it never changes — its single context build is counted via the first-build check
+ * in {@link FileBasedTlsFactory#loadInitialInstance}.
+ */
+ synchronized MaterialSource.RefreshOutcome currentMaterial() throws Exception {
+ if (source == null) {
+ return new MaterialSource.RefreshOutcome(TlsMaterial.SYSTEM_DEFAULT, false);
+ }
+ return source.refresh();
+ }
+
+ /**
+ * Return the cached context of the requested class, rebuilding it (and releasing the superseded
+ * one) only when the material changed in value. The returned instance is the factory-owned memo;
+ * callers that hand it to a consumer {@link FileBasedTlsFactory#retain(Object) retain} it.
+ */
+ synchronized <T> T acquireInstance(Class<T> instanceClass, TlsMaterial material,
+ FileBasedTlsFactorySettings settings) throws Exception {
+ if (instanceClass == SslContext.class) {
+ if (nettyContext == null || !material.equals(nettyMaterial)) {
+ SslContext built = purpose.role() == TlsPurpose.Role.SERVER
+ ? TlsContexts.buildNettyServerContext(material, policy, settings.engineProvider(),
+ settings.requireTrustedClientCert())
+ : TlsContexts.buildNettyClientContext(material, policy, settings.engineProvider());
+ release(nettyContext);
+ nettyContext = built;
+ nettyMaterial = material;
+ }
+ return instanceClass.cast(nettyContext);
+ }
+ if (instanceClass == SSLContext.class) {
+ if (jdkContext == null || !material.equals(jdkMaterial)) {
+ jdkContext = TlsContexts.buildJdkContext(material, policy);
+ jdkMaterial = material;
+ }
+ return instanceClass.cast(jdkContext);
+ }
+ throw new IllegalArgumentException("Unsupported instance class " + instanceClass);
+ }
+
+ /**
+ * The last-good cached context of the requested class, or {@code null} if none has been built yet.
+ * Used by the keep-last-good one-shot path when a fresh load fails mid-rotation.
+ */
+ synchronized <T> T cachedInstance(Class<T> instanceClass) {
+ if (instanceClass == SslContext.class && nettyContext != null) {
+ return instanceClass.cast(nettyContext);
+ }
+ if (instanceClass == SSLContext.class && jdkContext != null) {
+ return instanceClass.cast(jdkContext);
+ }
+ return null;
+ }
+
+ synchronized void poll(FileBasedTlsFactorySettings settings, TlsReloadMetrics metrics) {
+ if (source == null || subscriptions.isEmpty()) {
+ return;
+ }
+ MaterialSource.RefreshOutcome outcome;
+ try {
+ outcome = source.refresh();
+ } catch (Exception e) {
+ // Keep-last-good: leave every subscription on its current instance and retry next change.
+ recordLoad(metrics, false);
+ log.warn().attr("purpose", purpose).exception(e)
+ .log("Failed to reload TLS material; keeping the last-good instance");
+ return;
+ }
+ // A poll that finds no change is not a reload — do not count it, so the reload counter and the
+ // last-success gauge reflect real (re)load events only. But if a prior rotation's rebuild/delivery
+ // to some subscriber failed (pendingRedeliver), retry it even when the source now reports
+ // changed=false: otherwise, once the source commits the new baseline, every later poll sees
+ // changed=false and that subscriber stays wedged on the old instance until the next file change
+ // (L1). The retry rebuilds against the current last-good material.
+ if (!outcome.changed() && !pendingRedeliver) {
+ return;
+ }
+ recordLoad(metrics, deliverToSubscribers(outcome.material(), settings));
+ }
+
+ /**
+ * Rebuild and hand {@code material} to every live subscription, reporting whether all succeeded. Called
+ * both by the background poll and by an acquisition that consumed the source's change signal first
+ * (see {@link FileBasedTlsFactory#loadInitialInstance}), so a rotation reaches the subscribers no matter
+ * which caller observed it. Records no metric itself — each caller counts the (re)load once.
+ *
+ * <p><b>Consumer callbacks run while this source's monitor is held</b>, which keeps a rotation's
+ * rebuild-and-publish atomic against a concurrent acquisition. The cost is a reentrancy constraint on
+ * consumers: a reload callback must not call {@code createInstance} for the same purpose and block on
+ * the returned future, because that acquisition needs this same monitor and would deadlock when the
+ * blocking executor runs it on another thread. Consumers are expected to do only a volatile store in
+ * the callback (swap the context they hand to new connections) and never to block in it.
+ */
+ synchronized boolean deliverToSubscribers(TlsMaterial material, FileBasedTlsFactorySettings settings) {
Review Comment:
Took the "make it loud" half — 373d462b405. A re-entrant acquisition for the same purpose now fails the returned future with an `IllegalStateException` naming the problem, instead of hanging; failing the future rather than throwing keeps the SPI's never-throw-synchronously rule. Only same-purpose re-entry is rejected, since that is the case that cannot succeed. There is a test that would previously have hung.
On the other half — snapshot and invoke outside the lock — the monitor is doing a second job beyond rebuild-and-publish atomicity: it makes deliveries serial per subscription, which the Jetty coordinator relies on for generation ordering, and `loadInitialInstance` fans out under the same lock when an acquisition observes a rotation first. Moving callbacks out needs per-subscription serialization machinery, which I would rather not introduce in the PR that has no consumers yet.
Your comment on `JettyTlsFactory.java:549` was the concrete instance of this, and that one is fixed directly in a4832cd40e1.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/FileBasedTlsFactory.java:
##########
@@ -0,0 +1,768 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.util.ReferenceCountUtil;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import javax.net.ssl.SSLContext;
+import lombok.CustomLog;
+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.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsEndpoint;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The default, file-based {@link PulsarTlsFactory} (PIP-478).
+ *
+ * <p>Immutable after construction: the complete {@code TlsPurpose -> TlsPolicy} map and the
+ * factory-wide {@link FileBasedTlsFactorySettings} are fixed by the constructor and never mutated. The
+ * owning component (the v5 client builder, or {@code DefaultBrokerTlsFactory} on the server side)
+ * composes the final map before constructing the factory.
+ *
+ * <p>Natively supplies the Netty {@code SslContext} (on the configured engine — JDK or OpenSSL) and the
+ * JDK {@code SSLContext}; returns {@code empty()} for every other class (notably Jetty's
+ * {@code SslContextFactory.Server} and {@code SslContextFactory.Client}), which the framework synthesizes
+ * from the JDK {@code SSLContext}. It also
+ * returns {@code empty()} for the {@code javax.net.ssl.SSLParameters} companion (PIP-478): its engine policy
+ * (protocols, ciphers, client-auth mode, hostname verification) is baked natively into the Netty contexts it
+ * builds, so it exposes no separate baseline for the framework to overlay on those.
+ *
+ * <p>A JDK {@code SSLContext} cannot itself carry that policy — enabled protocols and cipher suites,
+ * algorithm constraints and the endpoint-identification algorithm are all per-engine {@code SSLParameters}
+ * settings — so the JDK context this factory returns is a <em>material carrier</em>: it holds the key and
+ * trust managers (built through the pinned providers) and nothing else. Every consumer of it applies the
+ * engine policy itself from the same {@link TlsPolicy}, which is what {@code JettyTlsFactory} does. A
+ * consumer that instead created engines straight from this {@code SSLContext} would get the provider defaults,
+ * so consumers must not do that.
+ *
+ * <p><b>Purpose resolution.</b> A request resolves the requested purpose directly against the configured
+ * {@code TlsPurpose -> TlsPolicy} map. When nothing is configured for the purpose, a {@code CLIENT}-role
+ * purpose resolves to the system default (OS trust store, no client certificate) and a {@code SERVER}-role
+ * purpose fails the request. A resolved-but-unbuildable request completes the future <em>exceptionally</em>
+ * — never {@code empty()}, which strictly means "unsupported {@code (purpose, class)} combination".
+ *
+ * <p><b>Rotation.</b> One {@link TlsMaterialSource} is shared per configured purpose. Server-side
+ * subscribers are pushed rebuilt instances by a background poll (interval from the settings, on the
+ * framework scheduler); client-side one-shot callers re-stat on each request and pick up rotation
+ * naturally. Because a re-stat consumes the source's change signal, an acquisition that observes a change
+ * first also fans it out to that purpose's subscribers, so a rotation is never swallowed by whoever happened
+ * to look first. A failed rebuild keeps the last-good instance, logs at WARN, and retries on the next
+ * change; a subscriber callback that throws is caught and logged, and the subscription stays live.
+ */
+@CustomLog
+public class FileBasedTlsFactory implements PulsarTlsFactory {
+
+ private final Map<TlsPurpose, RegisteredSource> registry;
+ private final FileBasedTlsFactorySettings settings;
+
+ private volatile TlsFactoryInitContext initContext;
+ private volatile TlsReloadMetrics metrics;
+ private volatile RegisteredSource systemDefaultSource;
+ private volatile ScheduledFuture<?> pollFuture;
+ private volatile boolean closed;
+
+ /**
+ * Construct an immutable file-based factory.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ this(policies, settings, Map.of());
+ }
+
+ /**
+ * Construct an immutable file-based factory that additionally folds an authentication plugin's TLS
+ * material over the configured file policy for the named purposes (the server-side {@code BROKER_CLIENT}
+ * fold — PIP-478). For a purpose present in {@code authMaterialSuppliers}, the supplier's
+ * {@code Authentication} material overrides the file policy's key/cert per
+ * {@link AuthProvidedMaterialSource} (auth-cert-wins); other purposes use the file policy unchanged.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ Objects.requireNonNull(policies, "policies must not be null");
+ this.settings = Objects.requireNonNull(settings, "settings must not be null");
+ Objects.requireNonNull(authMaterialSuppliers, "authMaterialSuppliers must not be null");
+ Map<TlsPurpose, RegisteredSource> built = new LinkedHashMap<>();
+ for (Map.Entry<TlsPurpose, TlsPolicy> entry : policies.entrySet()) {
+ TlsPurpose purpose = Objects.requireNonNull(entry.getKey(), "purpose key must not be null");
+ TlsPolicy policy = Objects.requireNonNull(entry.getValue(), "policy must not be null");
+ TlsMaterialSource fileSource = new TlsMaterialSource(policy);
+ Supplier<AuthenticationDataProvider> authSupplier = authMaterialSuppliers.get(purpose);
+ MaterialSource source = authSupplier == null
+ ? fileSource
+ : new AuthProvidedMaterialSource(fileSource, authSupplier);
+ built.put(purpose, new RegisteredSource(purpose, policy, source));
+ }
+ this.registry = Map.copyOf(built);
+ }
+
+ /**
+ * Adapt a component's broker-client {@link Authentication} to a per-refresh
+ * {@link AuthenticationDataProvider} supplier for use with the {@code BROKER_CLIENT} fold constructor.
+ * The supplier re-reads {@code getAuthData()} on each poll so credential rotation is observed; a checked
+ * {@link PulsarClientException} is rethrown unchecked and handled by the factory's keep-last-good poll.
+ *
+ * @param authentication the broker-client authentication plugin (never {@code null})
+ * @return a supplier of the plugin's current authentication data
+ */
+ public static Supplier<AuthenticationDataProvider> authMaterialSupplier(Authentication authentication) {
+ Objects.requireNonNull(authentication, "authentication must not be null");
+ return () -> {
+ try {
+ return resolveAuthData(authentication);
+ } catch (PulsarClientException e) {
+ throw new RuntimeException("Failed to obtain broker-client authentication TLS material", e);
+ }
+ };
+ }
+
+ // The BROKER_CLIENT TLS fold is host-agnostic — TLS key material does not vary by peer — so the
+ // host-less getAuthData() is exactly what we want; isolate its deprecation here.
+ @SuppressWarnings("deprecation")
+ private static AuthenticationDataProvider resolveAuthData(Authentication authentication)
+ throws PulsarClientException {
+ return authentication.getAuthData();
+ }
+
+ @Override
+ public CompletableFuture<Void> initialize(TlsFactoryInitContext context) {
+ try {
+ Objects.requireNonNull(context, "context must not be null");
+ // Required, not optional: every acquisition path in this factory reads files and parses key
+ // material. Without an executor the work would run inline on the caller's thread, which the SPI
+ // contract says may be a consumer event loop. Fail at wiring time rather than stalling a channel.
+ Objects.requireNonNull(context.blockingExecutor(),
+ "TlsFactoryInitContext.blockingExecutor() must not be null: FileBasedTlsFactory performs "
+ + "blocking file and key-material loading and must never run it on a consumer thread");
+ this.initContext = context;
+ // Cancel any poll scheduled by a prior initialize() so a second call does not orphan the first:
+ // the field is overwritten below and the old task would otherwise run forever.
+ ScheduledFuture<?> previousPoll = this.pollFuture;
+ if (previousPoll != null) {
+ previousPoll.cancel(false);
+ }
+ // Same reasoning for the metrics: a prior initialize() registered an observable gauge that stays
+ // registered on the meter until close(), so overwriting the field without closing it would leave
+ // an orphaned callback reporting stale per-purpose timestamps forever.
+ TlsReloadMetrics previousMetrics = this.metrics;
+ if (previousMetrics != null) {
+ previousMetrics.close();
+ }
+ this.metrics = TlsReloadMetrics.create(context.openTelemetry(), context.clock());
+ int interval = settings.refreshIntervalSeconds();
+ if (interval > 0 && context.scheduler() != null) {
+ this.pollFuture = context.scheduler().scheduleWithFixedDelay(
+ this::pollSafely, interval, interval, TimeUnit.SECONDS);
+ }
+ log.debug().attr("purposes", registry.keySet()).attr("refreshIntervalSeconds", interval)
+ .log("Initialized FileBasedTlsFactory");
+ return CompletableFuture.completedFuture(null);
+ } catch (Throwable t) {
+ return CompletableFuture.failedFuture(t);
+ }
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(TlsPurpose purpose, Class<T> instanceClass) {
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, TlsEndpoint endpoint, Class<T> instanceClass) {
+ // The default file-based factory serves purpose-scoped material and ignores the endpoint hint.
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, Class<T> instanceClass, Consumer<T> onLoadOrReload) {
+ if (onLoadOrReload == null) {
+ // SPI contract: argument-validation failures complete the returned future exceptionally — this
+ // method never throws on the calling thread.
+ return CompletableFuture.failedFuture(new NullPointerException("onLoadOrReload must not be null"));
+ }
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ synchronized (source) {
+ // FIX F: close() runs releaseAll() under this same source lock, and may have completed after
+ // the outer closed-check but before this task acquired the lock. Re-check here so we never
+ // build+cache+deliver a context (and register a subscription) whose factory-owned reference
+ // would then never be released — that would leak past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ Subscription<T> subscription = new Subscription<>(instanceClass, onLoadOrReload);
+ // Initial delivery happens-before the returned future completes (same thread, ordered).
+ subscription.deliver(instance);
+ source.subscriptions.add(subscription);
+ return Optional.of((TlsHandle<T>) new SubscriptionHandle<>(source, subscription));
+ }
+ });
+ }
+
+ private <T> CompletableFuture<Optional<TlsHandle<T>>> createOneShot(TlsPurpose purpose, Class<T> instanceClass) {
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ synchronized (source) {
+ // FIX F: re-check under the source lock (see createInstance above) so a task racing a
+ // concurrent close()/releaseAll() never builds+retains a context that then leaks past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ retain(instance);
+ return Optional.of((TlsHandle<T>) new OneShotHandle<>(instance));
+ }
+ });
+ }
+
+ /**
+ * Load (or reuse the cached) instance of {@code instanceClass} for the resolved source, recording a
+ * {@code pulsar.tls.reload} attempt for the source's purpose. A resolution failure upstream (an
+ * unconfigured server purpose) is a startup configuration error and is not counted here — only actual
+ * material loads are. Must be called while holding the source monitor.
+ *
+ * <p>Success is counted only for a <em>real</em> (re)load, mirroring the poll path: the first build of a
+ * context class for this source, or a refresh that found changed material. A repeat one-shot acquisition
+ * that re-serves the memoized context (every new connection, on the acquire-per-connection paths) is not a
+ * reload — counting it would inflate {@code pulsar.tls.reload} and keep advancing
+ * {@code pulsar.tls.last_reload_success}, masking exactly the stalled rotation the Monitoring section
+ * alerts on. Failures stay unconditional: an attempt that threw is always worth counting.
+ */
+ private <T> T loadInitialInstance(RegisteredSource source, Class<T> instanceClass) throws Exception {
+ // Hoisted out of the try so the catch can tell whether this call already CONSUMED a rotation before
+ // failing (see the comment on the catch below). Null means currentMaterial() itself threw, which
+ // commits no baseline and so consumes nothing.
+ MaterialSource.RefreshOutcome outcome = null;
+ try {
+ outcome = source.currentMaterial();
+ // Sampled before acquireInstance, which is what populates the memo (both calls run under the
+ // source monitor held by the caller, so no other acquisition can interleave).
+ boolean firstBuild = source.cachedInstance(instanceClass) == null;
+ T instance = source.acquireInstance(instanceClass, outcome.material(), settings);
+ // Rotation fan-out: currentMaterial() CONSUMES the source's change signal (refresh() commits the new
+ // mtime baseline), so whoever refreshes first is the only caller that ever sees changed=true. Without
+ // this, a one-shot acquisition (or an initial subscribing acquisition) that observes a rotation first
+ // leaves every later poll reporting changed=false and the subscribers on this same purpose wedged on
+ // the pre-rotation instance forever — e.g. an https:// client whose FrameworkHttpClientFactory
+ // subscribes to CLIENT_DEFAULT while another path acquires one-shot on it. Deliver the observed
+ // change here, exactly as the poll would have; a delivery failure arms pendingRedeliver so the next
+ // poll retries. No extra metric is recorded — this shares the single recordLoad below.
+ // Also drive the retry when a previous rotation's fan-out failed: the poll is the usual driver,
+ // but it is disabled entirely when refreshIntervalSeconds <= 0, and even when enabled an
+ // acquisition may get here first. Without this, a subscriber wedged by a failed rebuild would
+ // stay on the pre-rotation instance until the files changed again.
+ boolean retryPending = source.pendingRedeliver();
+ boolean delivered = true;
+ if (outcome.changed() || retryPending) {
+ delivered = source.deliverToSubscribers(outcome.material(), settings);
+ }
+ if (outcome.changed() || retryPending || firstBuild) {
+ recordLoad(source.purpose, delivered);
+ }
+ return instance;
+ } catch (Exception e) {
+ recordLoad(source.purpose, false);
+ // The material parsed (the baseline is committed) but building or delivering the context failed.
+ // currentMaterial() has therefore already CONSUMED this rotation's change signal, so every later
+ // poll would report changed=false and — without arming the redeliver flag here — return early,
+ // leaving the subscribers wedged on the pre-rotation instance until the files change again.
+ // deliverToSubscribers arms the flag itself on a partial delivery failure; this covers the case
+ // where the failure happened before it was ever reached.
+ if (outcome != null && outcome.changed()) {
+ source.armRedeliver();
+ }
+ // Keep-last-good (PIP-478): a one-shot (or initial subscribing) acquisition during a
+ // non-atomic rotation window — e.g. the cert file briefly unreadable while it is being replaced —
+ // must not fail when a prior load already built a context of this class. Serve that last-good
+ // instance and WARN; the reload-failure metric was recorded above. Fail only when there is no
+ // last-good to fall back on (a genuine startup misconfiguration, per the fail-fast contract).
+ T cached = source.cachedInstance(instanceClass);
+ if (cached != null) {
+ log.warn().attr("purpose", source.purpose).exception(e)
+ .log("Failed to load TLS material; serving the last-good instance");
+ return cached;
+ }
+ throw e;
+ }
+ }
+
+ private void recordLoad(TlsPurpose purpose, boolean success) {
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.recordLoad(purpose, success);
+ }
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ ScheduledFuture<?> poll = this.pollFuture;
+ if (poll != null) {
+ poll.cancel(false);
+ }
+ for (RegisteredSource source : registry.values()) {
+ source.releaseAll();
+ }
+ RegisteredSource systemDefault = this.systemDefaultSource;
+ if (systemDefault != null) {
+ systemDefault.releaseAll();
+ }
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.close();
+ }
+ }
+
+ /**
+ * Resolve a requested purpose to the {@link RegisteredSource} that owns its material, applying the
+ * role's terminal-resolution rule when nothing is configured for the purpose.
+ *
+ * @throws TlsMaterialUnavailableException when a server-role purpose has no material configured
+ */
+ private RegisteredSource resolve(TlsPurpose purpose) {
+ Objects.requireNonNull(purpose, "purpose must not be null");
+ RegisteredSource source = registry.get(purpose);
+ if (source != null) {
+ return source;
+ }
+ if (purpose.role() == TlsPurpose.Role.CLIENT) {
+ return systemDefaultSource();
+ }
+ throw new TlsMaterialUnavailableException(
+ "No TLS material configured for server purpose " + purpose);
+ }
+
+ private RegisteredSource systemDefaultSource() {
+ RegisteredSource existing = this.systemDefaultSource;
+ if (existing != null) {
+ return existing;
+ }
+ synchronized (this) {
+ if (this.systemDefaultSource == null) {
+ // System default: verify hostnames, OS trust store, no client certificate. A constant
+ // source (no files, never rotates).
+ TlsPolicy defaultPolicy = TlsPolicy.builder().build();
+ this.systemDefaultSource = new RegisteredSource(
+ TlsPurpose.CLIENT_DEFAULT, defaultPolicy, null);
+ }
+ return this.systemDefaultSource;
+ }
+ }
+
+ private void pollSafely() {
+ if (closed) {
+ return;
+ }
+ try {
+ for (RegisteredSource source : registry.values()) {
+ source.poll(settings, metrics);
Review Comment:
Fixed in 49ef9ebefe7, and the inconsistency was with our own rationale a few lines up. The scheduler now only triggers the poll; the work runs on the blocking executor.
Dispatching gives up `scheduleWithFixedDelay`'s no-overlap guarantee, so an in-flight flag stands in for it — a poll slower than the interval skips ticks rather than queueing behind itself — and a rejected dispatch (executor shutting down, queue full) clears the flag so a later tick retries rather than wedging the poll permanently.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/FileBasedTlsFactory.java:
##########
@@ -0,0 +1,768 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.util.ReferenceCountUtil;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import javax.net.ssl.SSLContext;
+import lombok.CustomLog;
+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.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsEndpoint;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The default, file-based {@link PulsarTlsFactory} (PIP-478).
+ *
+ * <p>Immutable after construction: the complete {@code TlsPurpose -> TlsPolicy} map and the
+ * factory-wide {@link FileBasedTlsFactorySettings} are fixed by the constructor and never mutated. The
+ * owning component (the v5 client builder, or {@code DefaultBrokerTlsFactory} on the server side)
+ * composes the final map before constructing the factory.
+ *
+ * <p>Natively supplies the Netty {@code SslContext} (on the configured engine — JDK or OpenSSL) and the
+ * JDK {@code SSLContext}; returns {@code empty()} for every other class (notably Jetty's
+ * {@code SslContextFactory.Server} and {@code SslContextFactory.Client}), which the framework synthesizes
+ * from the JDK {@code SSLContext}. It also
+ * returns {@code empty()} for the {@code javax.net.ssl.SSLParameters} companion (PIP-478): its engine policy
+ * (protocols, ciphers, client-auth mode, hostname verification) is baked natively into the Netty contexts it
+ * builds, so it exposes no separate baseline for the framework to overlay on those.
+ *
+ * <p>A JDK {@code SSLContext} cannot itself carry that policy — enabled protocols and cipher suites,
+ * algorithm constraints and the endpoint-identification algorithm are all per-engine {@code SSLParameters}
+ * settings — so the JDK context this factory returns is a <em>material carrier</em>: it holds the key and
+ * trust managers (built through the pinned providers) and nothing else. Every consumer of it applies the
+ * engine policy itself from the same {@link TlsPolicy}, which is what {@code JettyTlsFactory} does. A
+ * consumer that instead created engines straight from this {@code SSLContext} would get the provider defaults,
+ * so consumers must not do that.
+ *
+ * <p><b>Purpose resolution.</b> A request resolves the requested purpose directly against the configured
+ * {@code TlsPurpose -> TlsPolicy} map. When nothing is configured for the purpose, a {@code CLIENT}-role
+ * purpose resolves to the system default (OS trust store, no client certificate) and a {@code SERVER}-role
+ * purpose fails the request. A resolved-but-unbuildable request completes the future <em>exceptionally</em>
+ * — never {@code empty()}, which strictly means "unsupported {@code (purpose, class)} combination".
+ *
+ * <p><b>Rotation.</b> One {@link TlsMaterialSource} is shared per configured purpose. Server-side
+ * subscribers are pushed rebuilt instances by a background poll (interval from the settings, on the
+ * framework scheduler); client-side one-shot callers re-stat on each request and pick up rotation
+ * naturally. Because a re-stat consumes the source's change signal, an acquisition that observes a change
+ * first also fans it out to that purpose's subscribers, so a rotation is never swallowed by whoever happened
+ * to look first. A failed rebuild keeps the last-good instance, logs at WARN, and retries on the next
+ * change; a subscriber callback that throws is caught and logged, and the subscription stays live.
+ */
+@CustomLog
+public class FileBasedTlsFactory implements PulsarTlsFactory {
+
+ private final Map<TlsPurpose, RegisteredSource> registry;
+ private final FileBasedTlsFactorySettings settings;
+
+ private volatile TlsFactoryInitContext initContext;
+ private volatile TlsReloadMetrics metrics;
+ private volatile RegisteredSource systemDefaultSource;
+ private volatile ScheduledFuture<?> pollFuture;
+ private volatile boolean closed;
+
+ /**
+ * Construct an immutable file-based factory.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ this(policies, settings, Map.of());
+ }
+
+ /**
+ * Construct an immutable file-based factory that additionally folds an authentication plugin's TLS
+ * material over the configured file policy for the named purposes (the server-side {@code BROKER_CLIENT}
+ * fold — PIP-478). For a purpose present in {@code authMaterialSuppliers}, the supplier's
+ * {@code Authentication} material overrides the file policy's key/cert per
+ * {@link AuthProvidedMaterialSource} (auth-cert-wins); other purposes use the file policy unchanged.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ Objects.requireNonNull(policies, "policies must not be null");
+ this.settings = Objects.requireNonNull(settings, "settings must not be null");
+ Objects.requireNonNull(authMaterialSuppliers, "authMaterialSuppliers must not be null");
+ Map<TlsPurpose, RegisteredSource> built = new LinkedHashMap<>();
+ for (Map.Entry<TlsPurpose, TlsPolicy> entry : policies.entrySet()) {
+ TlsPurpose purpose = Objects.requireNonNull(entry.getKey(), "purpose key must not be null");
+ TlsPolicy policy = Objects.requireNonNull(entry.getValue(), "policy must not be null");
+ TlsMaterialSource fileSource = new TlsMaterialSource(policy);
+ Supplier<AuthenticationDataProvider> authSupplier = authMaterialSuppliers.get(purpose);
+ MaterialSource source = authSupplier == null
+ ? fileSource
+ : new AuthProvidedMaterialSource(fileSource, authSupplier);
+ built.put(purpose, new RegisteredSource(purpose, policy, source));
+ }
+ this.registry = Map.copyOf(built);
+ }
+
+ /**
+ * Adapt a component's broker-client {@link Authentication} to a per-refresh
+ * {@link AuthenticationDataProvider} supplier for use with the {@code BROKER_CLIENT} fold constructor.
+ * The supplier re-reads {@code getAuthData()} on each poll so credential rotation is observed; a checked
+ * {@link PulsarClientException} is rethrown unchecked and handled by the factory's keep-last-good poll.
+ *
+ * @param authentication the broker-client authentication plugin (never {@code null})
+ * @return a supplier of the plugin's current authentication data
+ */
+ public static Supplier<AuthenticationDataProvider> authMaterialSupplier(Authentication authentication) {
+ Objects.requireNonNull(authentication, "authentication must not be null");
+ return () -> {
+ try {
+ return resolveAuthData(authentication);
+ } catch (PulsarClientException e) {
+ throw new RuntimeException("Failed to obtain broker-client authentication TLS material", e);
+ }
+ };
+ }
+
+ // The BROKER_CLIENT TLS fold is host-agnostic — TLS key material does not vary by peer — so the
+ // host-less getAuthData() is exactly what we want; isolate its deprecation here.
+ @SuppressWarnings("deprecation")
+ private static AuthenticationDataProvider resolveAuthData(Authentication authentication)
+ throws PulsarClientException {
+ return authentication.getAuthData();
+ }
+
+ @Override
+ public CompletableFuture<Void> initialize(TlsFactoryInitContext context) {
+ try {
+ Objects.requireNonNull(context, "context must not be null");
+ // Required, not optional: every acquisition path in this factory reads files and parses key
+ // material. Without an executor the work would run inline on the caller's thread, which the SPI
+ // contract says may be a consumer event loop. Fail at wiring time rather than stalling a channel.
+ Objects.requireNonNull(context.blockingExecutor(),
+ "TlsFactoryInitContext.blockingExecutor() must not be null: FileBasedTlsFactory performs "
+ + "blocking file and key-material loading and must never run it on a consumer thread");
+ this.initContext = context;
+ // Cancel any poll scheduled by a prior initialize() so a second call does not orphan the first:
+ // the field is overwritten below and the old task would otherwise run forever.
+ ScheduledFuture<?> previousPoll = this.pollFuture;
+ if (previousPoll != null) {
+ previousPoll.cancel(false);
+ }
+ // Same reasoning for the metrics: a prior initialize() registered an observable gauge that stays
+ // registered on the meter until close(), so overwriting the field without closing it would leave
+ // an orphaned callback reporting stale per-purpose timestamps forever.
+ TlsReloadMetrics previousMetrics = this.metrics;
+ if (previousMetrics != null) {
+ previousMetrics.close();
+ }
+ this.metrics = TlsReloadMetrics.create(context.openTelemetry(), context.clock());
+ int interval = settings.refreshIntervalSeconds();
+ if (interval > 0 && context.scheduler() != null) {
+ this.pollFuture = context.scheduler().scheduleWithFixedDelay(
+ this::pollSafely, interval, interval, TimeUnit.SECONDS);
+ }
+ log.debug().attr("purposes", registry.keySet()).attr("refreshIntervalSeconds", interval)
+ .log("Initialized FileBasedTlsFactory");
+ return CompletableFuture.completedFuture(null);
+ } catch (Throwable t) {
+ return CompletableFuture.failedFuture(t);
+ }
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(TlsPurpose purpose, Class<T> instanceClass) {
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, TlsEndpoint endpoint, Class<T> instanceClass) {
+ // The default file-based factory serves purpose-scoped material and ignores the endpoint hint.
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, Class<T> instanceClass, Consumer<T> onLoadOrReload) {
+ if (onLoadOrReload == null) {
+ // SPI contract: argument-validation failures complete the returned future exceptionally — this
+ // method never throws on the calling thread.
+ return CompletableFuture.failedFuture(new NullPointerException("onLoadOrReload must not be null"));
+ }
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ synchronized (source) {
+ // FIX F: close() runs releaseAll() under this same source lock, and may have completed after
+ // the outer closed-check but before this task acquired the lock. Re-check here so we never
+ // build+cache+deliver a context (and register a subscription) whose factory-owned reference
+ // would then never be released — that would leak past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ Subscription<T> subscription = new Subscription<>(instanceClass, onLoadOrReload);
+ // Initial delivery happens-before the returned future completes (same thread, ordered).
+ subscription.deliver(instance);
+ source.subscriptions.add(subscription);
+ return Optional.of((TlsHandle<T>) new SubscriptionHandle<>(source, subscription));
+ }
+ });
+ }
+
+ private <T> CompletableFuture<Optional<TlsHandle<T>>> createOneShot(TlsPurpose purpose, Class<T> instanceClass) {
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ synchronized (source) {
+ // FIX F: re-check under the source lock (see createInstance above) so a task racing a
+ // concurrent close()/releaseAll() never builds+retains a context that then leaks past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ retain(instance);
+ return Optional.of((TlsHandle<T>) new OneShotHandle<>(instance));
+ }
+ });
+ }
+
+ /**
+ * Load (or reuse the cached) instance of {@code instanceClass} for the resolved source, recording a
+ * {@code pulsar.tls.reload} attempt for the source's purpose. A resolution failure upstream (an
+ * unconfigured server purpose) is a startup configuration error and is not counted here — only actual
+ * material loads are. Must be called while holding the source monitor.
+ *
+ * <p>Success is counted only for a <em>real</em> (re)load, mirroring the poll path: the first build of a
+ * context class for this source, or a refresh that found changed material. A repeat one-shot acquisition
+ * that re-serves the memoized context (every new connection, on the acquire-per-connection paths) is not a
+ * reload — counting it would inflate {@code pulsar.tls.reload} and keep advancing
+ * {@code pulsar.tls.last_reload_success}, masking exactly the stalled rotation the Monitoring section
+ * alerts on. Failures stay unconditional: an attempt that threw is always worth counting.
+ */
+ private <T> T loadInitialInstance(RegisteredSource source, Class<T> instanceClass) throws Exception {
+ // Hoisted out of the try so the catch can tell whether this call already CONSUMED a rotation before
+ // failing (see the comment on the catch below). Null means currentMaterial() itself threw, which
+ // commits no baseline and so consumes nothing.
+ MaterialSource.RefreshOutcome outcome = null;
+ try {
+ outcome = source.currentMaterial();
+ // Sampled before acquireInstance, which is what populates the memo (both calls run under the
+ // source monitor held by the caller, so no other acquisition can interleave).
+ boolean firstBuild = source.cachedInstance(instanceClass) == null;
+ T instance = source.acquireInstance(instanceClass, outcome.material(), settings);
+ // Rotation fan-out: currentMaterial() CONSUMES the source's change signal (refresh() commits the new
+ // mtime baseline), so whoever refreshes first is the only caller that ever sees changed=true. Without
+ // this, a one-shot acquisition (or an initial subscribing acquisition) that observes a rotation first
+ // leaves every later poll reporting changed=false and the subscribers on this same purpose wedged on
+ // the pre-rotation instance forever — e.g. an https:// client whose FrameworkHttpClientFactory
+ // subscribes to CLIENT_DEFAULT while another path acquires one-shot on it. Deliver the observed
+ // change here, exactly as the poll would have; a delivery failure arms pendingRedeliver so the next
+ // poll retries. No extra metric is recorded — this shares the single recordLoad below.
+ // Also drive the retry when a previous rotation's fan-out failed: the poll is the usual driver,
+ // but it is disabled entirely when refreshIntervalSeconds <= 0, and even when enabled an
+ // acquisition may get here first. Without this, a subscriber wedged by a failed rebuild would
+ // stay on the pre-rotation instance until the files changed again.
+ boolean retryPending = source.pendingRedeliver();
+ boolean delivered = true;
+ if (outcome.changed() || retryPending) {
+ delivered = source.deliverToSubscribers(outcome.material(), settings);
+ }
+ if (outcome.changed() || retryPending || firstBuild) {
+ recordLoad(source.purpose, delivered);
+ }
+ return instance;
+ } catch (Exception e) {
+ recordLoad(source.purpose, false);
+ // The material parsed (the baseline is committed) but building or delivering the context failed.
+ // currentMaterial() has therefore already CONSUMED this rotation's change signal, so every later
+ // poll would report changed=false and — without arming the redeliver flag here — return early,
+ // leaving the subscribers wedged on the pre-rotation instance until the files change again.
+ // deliverToSubscribers arms the flag itself on a partial delivery failure; this covers the case
+ // where the failure happened before it was ever reached.
+ if (outcome != null && outcome.changed()) {
+ source.armRedeliver();
+ }
+ // Keep-last-good (PIP-478): a one-shot (or initial subscribing) acquisition during a
+ // non-atomic rotation window — e.g. the cert file briefly unreadable while it is being replaced —
+ // must not fail when a prior load already built a context of this class. Serve that last-good
+ // instance and WARN; the reload-failure metric was recorded above. Fail only when there is no
+ // last-good to fall back on (a genuine startup misconfiguration, per the fail-fast contract).
+ T cached = source.cachedInstance(instanceClass);
+ if (cached != null) {
+ log.warn().attr("purpose", source.purpose).exception(e)
+ .log("Failed to load TLS material; serving the last-good instance");
+ return cached;
+ }
+ throw e;
+ }
+ }
+
+ private void recordLoad(TlsPurpose purpose, boolean success) {
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.recordLoad(purpose, success);
+ }
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ ScheduledFuture<?> poll = this.pollFuture;
+ if (poll != null) {
+ poll.cancel(false);
+ }
+ for (RegisteredSource source : registry.values()) {
+ source.releaseAll();
+ }
+ RegisteredSource systemDefault = this.systemDefaultSource;
+ if (systemDefault != null) {
+ systemDefault.releaseAll();
+ }
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.close();
+ }
+ }
+
+ /**
+ * Resolve a requested purpose to the {@link RegisteredSource} that owns its material, applying the
+ * role's terminal-resolution rule when nothing is configured for the purpose.
+ *
+ * @throws TlsMaterialUnavailableException when a server-role purpose has no material configured
+ */
+ private RegisteredSource resolve(TlsPurpose purpose) {
+ Objects.requireNonNull(purpose, "purpose must not be null");
+ RegisteredSource source = registry.get(purpose);
+ if (source != null) {
+ return source;
+ }
+ if (purpose.role() == TlsPurpose.Role.CLIENT) {
+ return systemDefaultSource();
+ }
+ throw new TlsMaterialUnavailableException(
+ "No TLS material configured for server purpose " + purpose);
+ }
+
+ private RegisteredSource systemDefaultSource() {
+ RegisteredSource existing = this.systemDefaultSource;
+ if (existing != null) {
+ return existing;
+ }
+ synchronized (this) {
+ if (this.systemDefaultSource == null) {
+ // System default: verify hostnames, OS trust store, no client certificate. A constant
+ // source (no files, never rotates).
+ TlsPolicy defaultPolicy = TlsPolicy.builder().build();
+ this.systemDefaultSource = new RegisteredSource(
+ TlsPurpose.CLIENT_DEFAULT, defaultPolicy, null);
+ }
+ return this.systemDefaultSource;
+ }
+ }
+
+ private void pollSafely() {
+ if (closed) {
+ return;
+ }
+ try {
+ for (RegisteredSource source : registry.values()) {
+ source.poll(settings, metrics);
+ }
+ } catch (Throwable t) {
+ log.warn().exception(t).log("Unexpected error during TLS material poll");
+ }
+ }
+
+ private <R> CompletableFuture<R> runAsync(Callable<R> task) {
+ CompletableFuture<R> future = new CompletableFuture<>();
+ TlsFactoryInitContext context = this.initContext;
+ // initialize() rejects a null blockingExecutor, so the caller-thread fallback is reachable only before
+ // initialize() has run — a direct-construction path (tests, or a component acquiring during its own
+ // startup) that is by definition not on a consumer event loop.
+ Executor executor = context != null ? context.blockingExecutor() : Runnable::run;
+ try {
+ executor.execute(() -> {
+ try {
+ R result = task.call();
+ if (!future.complete(result)) {
+ // The caller cancelled (or otherwise completed) the future while the acquisition was
+ // still running, so nothing will ever receive this handle. The task has already
+ // retained the context on its behalf, and with the finalizer-free OPENSSL_REFCNT
+ // engine an unbalanced retain is a permanent native leak — dispose the orphan here.
+ disposeOrphan(result);
+ }
+ } catch (Throwable t) {
+ future.completeExceptionally(t);
+ }
+ });
+ } catch (Throwable t) {
+ future.completeExceptionally(t);
+ }
+ return future;
+ }
+
+ /**
+ * Release a handle that was built but could not be delivered to its caller. Both acquisition forms
+ * produce an {@code Optional<TlsHandle<?>>}, and disposing it is exactly what the caller would have done:
+ * it drops the one-shot's retained reference, or unregisters the subscription and releases its borrows.
+ */
+ private static void disposeOrphan(Object result) {
+ if (result instanceof Optional<?> optional && optional.orElse(null) instanceof TlsHandle<?> handle) {
+ try {
+ handle.dispose();
+ } catch (Throwable t) {
+ log.warn().exception(t).log("Failed to dispose an undelivered TLS handle");
+ }
+ }
+ }
+
+ private static boolean isSupported(Class<?> instanceClass) {
+ return instanceClass == SslContext.class || instanceClass == SSLContext.class;
+ }
+
+ private static void retain(Object instance) {
+ if (instance != null) {
+ ReferenceCountUtil.retain(instance);
+ }
+ }
+
+ private static void release(Object instance) {
+ if (instance != null) {
+ ReferenceCountUtil.release(instance);
+ }
+ }
+
+ /**
+ * A configured purpose's material source together with the cached, factory-owned context instances
+ * and the active subscriptions. All state is guarded by the instance monitor.
+ */
+ private static final class RegisteredSource {
+ private final TlsPurpose purpose;
+ private final TlsPolicy policy;
+ // Null for the system-default source, whose constant material never rotates.
+ private final MaterialSource source;
+ private final CopyOnWriteArrayList<Subscription<?>> subscriptions = new CopyOnWriteArrayList<>();
+
+ private SslContext nettyContext;
+ private TlsMaterial nettyMaterial;
+ private SSLContext jdkContext;
+ private TlsMaterial jdkMaterial;
+ // Set when a rotation's rebuild/delivery to some subscriber failed, so the next poll re-attempts the
+ // rebuild even if the source now reports changed=false (PIP-478 L1 reload-wedge guard).
+ private boolean pendingRedeliver;
+
+ RegisteredSource(TlsPurpose purpose, TlsPolicy policy, MaterialSource source) {
+ this.purpose = purpose;
+ this.policy = policy;
+ this.source = source;
+ }
+
+ /**
+ * Refresh the material, reporting whether it changed in value. The system-default source has no
+ * backing files, so it never changes — its single context build is counted via the first-build check
+ * in {@link FileBasedTlsFactory#loadInitialInstance}.
+ */
+ synchronized MaterialSource.RefreshOutcome currentMaterial() throws Exception {
+ if (source == null) {
+ return new MaterialSource.RefreshOutcome(TlsMaterial.SYSTEM_DEFAULT, false);
+ }
+ return source.refresh();
+ }
+
+ /**
+ * Return the cached context of the requested class, rebuilding it (and releasing the superseded
+ * one) only when the material changed in value. The returned instance is the factory-owned memo;
+ * callers that hand it to a consumer {@link FileBasedTlsFactory#retain(Object) retain} it.
+ */
+ synchronized <T> T acquireInstance(Class<T> instanceClass, TlsMaterial material,
+ FileBasedTlsFactorySettings settings) throws Exception {
+ if (instanceClass == SslContext.class) {
+ if (nettyContext == null || !material.equals(nettyMaterial)) {
+ SslContext built = purpose.role() == TlsPurpose.Role.SERVER
+ ? TlsContexts.buildNettyServerContext(material, policy, settings.engineProvider(),
+ settings.requireTrustedClientCert())
+ : TlsContexts.buildNettyClientContext(material, policy, settings.engineProvider());
+ release(nettyContext);
+ nettyContext = built;
+ nettyMaterial = material;
+ }
+ return instanceClass.cast(nettyContext);
+ }
+ if (instanceClass == SSLContext.class) {
+ if (jdkContext == null || !material.equals(jdkMaterial)) {
+ jdkContext = TlsContexts.buildJdkContext(material, policy);
+ jdkMaterial = material;
+ }
+ return instanceClass.cast(jdkContext);
+ }
+ throw new IllegalArgumentException("Unsupported instance class " + instanceClass);
+ }
+
+ /**
+ * The last-good cached context of the requested class, or {@code null} if none has been built yet.
+ * Used by the keep-last-good one-shot path when a fresh load fails mid-rotation.
+ */
+ synchronized <T> T cachedInstance(Class<T> instanceClass) {
+ if (instanceClass == SslContext.class && nettyContext != null) {
+ return instanceClass.cast(nettyContext);
+ }
+ if (instanceClass == SSLContext.class && jdkContext != null) {
+ return instanceClass.cast(jdkContext);
+ }
+ return null;
+ }
+
+ synchronized void poll(FileBasedTlsFactorySettings settings, TlsReloadMetrics metrics) {
+ if (source == null || subscriptions.isEmpty()) {
+ return;
+ }
+ MaterialSource.RefreshOutcome outcome;
+ try {
+ outcome = source.refresh();
+ } catch (Exception e) {
+ // Keep-last-good: leave every subscription on its current instance and retry next change.
+ recordLoad(metrics, false);
+ log.warn().attr("purpose", purpose).exception(e)
+ .log("Failed to reload TLS material; keeping the last-good instance");
+ return;
+ }
+ // A poll that finds no change is not a reload — do not count it, so the reload counter and the
+ // last-success gauge reflect real (re)load events only. But if a prior rotation's rebuild/delivery
+ // to some subscriber failed (pendingRedeliver), retry it even when the source now reports
+ // changed=false: otherwise, once the source commits the new baseline, every later poll sees
+ // changed=false and that subscriber stays wedged on the old instance until the next file change
+ // (L1). The retry rebuilds against the current last-good material.
+ if (!outcome.changed() && !pendingRedeliver) {
+ return;
+ }
+ recordLoad(metrics, deliverToSubscribers(outcome.material(), settings));
+ }
+
+ /**
+ * Rebuild and hand {@code material} to every live subscription, reporting whether all succeeded. Called
+ * both by the background poll and by an acquisition that consumed the source's change signal first
+ * (see {@link FileBasedTlsFactory#loadInitialInstance}), so a rotation reaches the subscribers no matter
+ * which caller observed it. Records no metric itself — each caller counts the (re)load once.
+ *
+ * <p><b>Consumer callbacks run while this source's monitor is held</b>, which keeps a rotation's
+ * rebuild-and-publish atomic against a concurrent acquisition. The cost is a reentrancy constraint on
+ * consumers: a reload callback must not call {@code createInstance} for the same purpose and block on
+ * the returned future, because that acquisition needs this same monitor and would deadlock when the
+ * blocking executor runs it on another thread. Consumers are expected to do only a volatile store in
+ * the callback (swap the context they hand to new connections) and never to block in it.
+ */
+ synchronized boolean deliverToSubscribers(TlsMaterial material, FileBasedTlsFactorySettings settings) {
+ boolean allRebuilt = true;
+ for (Subscription<?> subscription : subscriptions) {
+ try {
+ Object rebuilt = acquireInstance(subscription.instanceClass, material, settings);
+ subscription.deliverErased(rebuilt);
+ } catch (Exception e) {
+ allRebuilt = false;
+ log.warn().attr("purpose", purpose).attr("class", subscription.instanceClass.getName())
+ .exception(e).log("Failed to rebuild rotated TLS instance; keeping the last-good one");
+ }
+ }
+ // Re-attempt on the next poll until every subscriber has the rotated instance (L1).
+ pendingRedeliver = !allRebuilt;
+ return allRebuilt;
+ }
+
+ private void recordLoad(TlsReloadMetrics metrics, boolean success) {
+ if (metrics != null) {
+ metrics.recordLoad(purpose, success);
+ }
+ }
+
+ /**
+ * Arm the redeliver retry for a rotation whose change signal was consumed but whose fan-out never
+ * ran (the context build failed first). The next poll — or, when polling is disabled, the next
+ * acquisition — then re-attempts the rebuild even though the source now reports {@code changed=false}.
+ */
+ synchronized void armRedeliver() {
+ pendingRedeliver = true;
+ }
+
+ /** @return whether a rotation still owes its subscribers a rebuilt instance. */
+ synchronized boolean pendingRedeliver() {
+ return pendingRedeliver;
+ }
+
+ synchronized void removeSubscription(Subscription<?> subscription) {
+ if (subscriptions.remove(subscription)) {
+ subscription.releaseCurrent();
+ }
+ }
+
+ synchronized void releaseAll() {
+ for (Subscription<?> subscription : subscriptions) {
+ subscription.releaseCurrent();
+ }
+ subscriptions.clear();
+ release(nettyContext);
+ nettyContext = null;
+ nettyMaterial = null;
+ jdkContext = null;
+ jdkMaterial = null;
+ }
+ }
+
+ /** A live server-side subscription: its instance class, callback, and last-delivered instances. */
+ private static final class Subscription<T> {
+ private final Class<T> instanceClass;
+ private final Consumer<T> callback;
+ // Volatile: written under the source monitor (deliver), but read lock-free by SubscriptionHandle.get()
+ // from arbitrary consumer threads — the handle contract promises the most recent delivery, which
+ // needs the happens-before edge (a stale read can outlive the deferred-release window below).
+ private volatile T current;
+ // Deferred release (PIP-478 use-after-free): the instance superseded by the most recent delivery
+ // is kept alive one extra generation rather than released immediately. Consumers hold a bare volatile
+ // borrow of the delivered instance and later call newHandler/newEngine on it off a different thread;
+ // releasing the superseded Netty/OpenSSL context to refcount 0 on the poll thread the instant the new
+ // one is published would free the native SSL_CTX out from under such an in-flight borrow. Retaining it
+ // for one further rotation gives every reader a full poll interval to finish. Pairs with per-use
+ // pinning at the consumers (see TlsContextAcquisition.withPinnedContext) for the descheduling case.
+ private T previous;
+
+ Subscription(Class<T> instanceClass, Consumer<T> callback) {
+ this.instanceClass = instanceClass;
+ this.callback = callback;
+ }
+
+ void deliver(T instance) {
+ retain(instance);
+ // Release the instance delivered two rotations ago (N-1) on this (N+1th) delivery, not the one
+ // just superseded, so the just-superseded instance survives one more generation for readers.
+ release(previous);
+ previous = current;
+ current = instance;
+ safeInvoke(instance);
+ }
+
+ @SuppressWarnings("unchecked")
+ void deliverErased(Object instance) {
+ deliver((T) instance);
+ }
+
+ T current() {
+ return current;
+ }
+
+ void releaseCurrent() {
+ release(current);
+ current = null;
+ release(previous);
+ previous = null;
+ }
+
+ private void safeInvoke(T instance) {
+ try {
+ callback.accept(instance);
+ } catch (Throwable t) {
+ // A throwing consumer callback must not kill the subscription; later deliveries proceed.
+ log.warn().exception(t).log("TLS reload callback threw; subscription stays live");
+ }
+ }
+ }
+
+ /** A one-shot handle: exposes the built instance and releases its retained reference on dispose. */
+ private static final class OneShotHandle<T> implements TlsHandle<T> {
+ private final T instance;
+ // FIX E: an AtomicBoolean, not a volatile flag — a plain check-then-set lets two concurrent
+ // dispose() callers both pass the guard and over-decrement the cached context's refcount.
+ private final AtomicBoolean disposed = new AtomicBoolean(false);
+
+ OneShotHandle(T instance) {
+ this.instance = instance;
+ }
+
+ @Override
+ public T get() {
+ return instance;
+ }
+
+ @Override
+ public void dispose() {
+ if (disposed.compareAndSet(false, true)) {
+ release(instance);
+ }
+ }
+ }
+
+ /** A subscribing handle: exposes the most-recently-delivered instance and unregisters on dispose. */
+ private static final class SubscriptionHandle<T> implements TlsHandle<T> {
+ private final RegisteredSource source;
+ private final Subscription<T> subscription;
+ private volatile boolean disposed;
Review Comment:
Correct, including the diagnosis: safety comes from `subscriptions.remove()` returning true, not from the flag. Switched to `AtomicBoolean.compareAndSet` for symmetry with `OneShotHandle` in 01c848e5ae0, and recorded that `remove()` is the actual linearization point — so the guarantee no longer depends on which of the two guards you happen to read.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/AuthProvidedMaterialSource.java:
##########
@@ -0,0 +1,214 @@
+/*
+ * 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.common.tls.impl;
+
+import java.io.InputStream;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Supplier;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.client.api.AuthenticationDataProvider;
+import org.apache.pulsar.client.api.KeyStoreParams;
+import org.apache.pulsar.common.util.tls.PemReader;
+
+/**
+ * A {@link MaterialSource} that folds a server component's broker-client {@code Authentication} TLS
+ * material over a file-based base source for the {@code BROKER_CLIENT} purpose (PIP-478). This is the
+ * server-side mirror of the client TLS override hook, preserving the PIP-337 auth-data behavior it
+ * supersedes:
+ * when the broker-client authentication plugin (e.g.
+ * {@code AuthenticationTls}) supplies key material, its in-memory certificate/key <em>override</em> the
+ * configured {@code brokerClient*} file paths, so a proxy or broker presents the right identity to the
+ * broker and forwarded-principal authorization works.
+ *
+ * <p>Precedence per material slot:
+ * <ul>
+ * <li><b>key + certificate chain</b>: the authentication plugin's material wins when it supplies both;
+ * otherwise the base file material is used;</li>
+ * <li><b>trust certificates</b>: the base (file) trust material wins; only when the base has none is the
+ * authentication plugin's trust-store stream consulted.</li>
+ * </ul>
+ *
+ * <p><b>Rotation.</b> {@link #refresh()} re-reads the authentication data on every call (the plugin may
+ * hot-reload its own files) and rebuilds the combined material, signalling a change through
+ * {@link TlsMaterial} value equality — so a rotated auth certificate is picked up independently of whether
+ * the base files changed. A transient authentication failure keeps the last-good combined material.
+ */
+@CustomLog
+final class AuthProvidedMaterialSource implements MaterialSource {
+
+ private final TlsMaterialSource base;
+ private final Supplier<AuthenticationDataProvider> authDataSupplier;
+ private final AtomicBoolean unpinnedAuthMaterialWarned = new AtomicBoolean();
+ private TlsMaterial cached;
+
+ AuthProvidedMaterialSource(TlsMaterialSource base, Supplier<AuthenticationDataProvider> authDataSupplier) {
+ this.base = Objects.requireNonNull(base, "base");
+ this.authDataSupplier = Objects.requireNonNull(authDataSupplier, "authDataSupplier");
+ }
+
+ @Override
+ public RefreshOutcome refresh() throws Exception {
Review Comment:
The observation is right: `refresh()` discards the base source's `changed` flag and re-invokes the supplier every time, and on the pinned-provider path deliberately re-reads the files. With per-connection acquisition that is a parse per connection.
One bound worth noting: context *rebuilds* are still suppressed by `TlsMaterial` value equality, so the cost is the supplier call and the parse — not a rebuild, and not a spurious reload delivery.
On the fix, an auth-data identity check alone will not work: `AuthenticationTls` returns a stable `AuthenticationDataProvider` whose certificate and key rotate internally behind it, so identity is unchanged across a real rotation. The version that works is mtime-stats of the auth data's file paths — the same trick `TlsMaterialSource` now uses (065b304623c) — with no cheap signal for plugins exposing only pre-parsed objects.
**Deliberately deferred**: I would rather land that in the PR that wires the acquisition path, where it can be measured against a real per-connection pattern instead of guessed at. Flagging it there so it is not lost.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [feat][misc] PIP-478: default file-based TLS factory implementation [pulsar]
Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #26271:
URL: https://github.com/apache/pulsar/pull/26271#discussion_r3719671419
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/FileBasedTlsFactory.java:
##########
@@ -0,0 +1,768 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.util.ReferenceCountUtil;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import javax.net.ssl.SSLContext;
+import lombok.CustomLog;
+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.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsEndpoint;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The default, file-based {@link PulsarTlsFactory} (PIP-478).
+ *
+ * <p>Immutable after construction: the complete {@code TlsPurpose -> TlsPolicy} map and the
+ * factory-wide {@link FileBasedTlsFactorySettings} are fixed by the constructor and never mutated. The
+ * owning component (the v5 client builder, or {@code DefaultBrokerTlsFactory} on the server side)
+ * composes the final map before constructing the factory.
+ *
+ * <p>Natively supplies the Netty {@code SslContext} (on the configured engine — JDK or OpenSSL) and the
+ * JDK {@code SSLContext}; returns {@code empty()} for every other class (notably Jetty's
+ * {@code SslContextFactory.Server} and {@code SslContextFactory.Client}), which the framework synthesizes
+ * from the JDK {@code SSLContext}. It also
+ * returns {@code empty()} for the {@code javax.net.ssl.SSLParameters} companion (PIP-478): its engine policy
+ * (protocols, ciphers, client-auth mode, hostname verification) is baked natively into the Netty contexts it
+ * builds, so it exposes no separate baseline for the framework to overlay on those.
+ *
+ * <p>A JDK {@code SSLContext} cannot itself carry that policy — enabled protocols and cipher suites,
+ * algorithm constraints and the endpoint-identification algorithm are all per-engine {@code SSLParameters}
+ * settings — so the JDK context this factory returns is a <em>material carrier</em>: it holds the key and
+ * trust managers (built through the pinned providers) and nothing else. Every consumer of it applies the
+ * engine policy itself from the same {@link TlsPolicy}, which is what {@code JettyTlsFactory} does. A
+ * consumer that instead created engines straight from this {@code SSLContext} would get the provider defaults,
+ * so consumers must not do that.
+ *
+ * <p><b>Purpose resolution.</b> A request resolves the requested purpose directly against the configured
+ * {@code TlsPurpose -> TlsPolicy} map. When nothing is configured for the purpose, a {@code CLIENT}-role
+ * purpose resolves to the system default (OS trust store, no client certificate) and a {@code SERVER}-role
+ * purpose fails the request. A resolved-but-unbuildable request completes the future <em>exceptionally</em>
+ * — never {@code empty()}, which strictly means "unsupported {@code (purpose, class)} combination".
+ *
+ * <p><b>Rotation.</b> One {@link TlsMaterialSource} is shared per configured purpose. Server-side
+ * subscribers are pushed rebuilt instances by a background poll (interval from the settings, on the
+ * framework scheduler); client-side one-shot callers re-stat on each request and pick up rotation
+ * naturally. Because a re-stat consumes the source's change signal, an acquisition that observes a change
+ * first also fans it out to that purpose's subscribers, so a rotation is never swallowed by whoever happened
+ * to look first. A failed rebuild keeps the last-good instance, logs at WARN, and retries on the next
+ * change; a subscriber callback that throws is caught and logged, and the subscription stays live.
+ */
+@CustomLog
+public class FileBasedTlsFactory implements PulsarTlsFactory {
+
+ private final Map<TlsPurpose, RegisteredSource> registry;
+ private final FileBasedTlsFactorySettings settings;
+
+ private volatile TlsFactoryInitContext initContext;
+ private volatile TlsReloadMetrics metrics;
+ private volatile RegisteredSource systemDefaultSource;
+ private volatile ScheduledFuture<?> pollFuture;
+ private volatile boolean closed;
+
+ /**
+ * Construct an immutable file-based factory.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ this(policies, settings, Map.of());
+ }
+
+ /**
+ * Construct an immutable file-based factory that additionally folds an authentication plugin's TLS
+ * material over the configured file policy for the named purposes (the server-side {@code BROKER_CLIENT}
+ * fold — PIP-478). For a purpose present in {@code authMaterialSuppliers}, the supplier's
+ * {@code Authentication} material overrides the file policy's key/cert per
+ * {@link AuthProvidedMaterialSource} (auth-cert-wins); other purposes use the file policy unchanged.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ Objects.requireNonNull(policies, "policies must not be null");
+ this.settings = Objects.requireNonNull(settings, "settings must not be null");
+ Objects.requireNonNull(authMaterialSuppliers, "authMaterialSuppliers must not be null");
+ Map<TlsPurpose, RegisteredSource> built = new LinkedHashMap<>();
+ for (Map.Entry<TlsPurpose, TlsPolicy> entry : policies.entrySet()) {
+ TlsPurpose purpose = Objects.requireNonNull(entry.getKey(), "purpose key must not be null");
+ TlsPolicy policy = Objects.requireNonNull(entry.getValue(), "policy must not be null");
+ TlsMaterialSource fileSource = new TlsMaterialSource(policy);
+ Supplier<AuthenticationDataProvider> authSupplier = authMaterialSuppliers.get(purpose);
+ MaterialSource source = authSupplier == null
+ ? fileSource
+ : new AuthProvidedMaterialSource(fileSource, authSupplier);
+ built.put(purpose, new RegisteredSource(purpose, policy, source));
+ }
+ this.registry = Map.copyOf(built);
+ }
+
+ /**
+ * Adapt a component's broker-client {@link Authentication} to a per-refresh
+ * {@link AuthenticationDataProvider} supplier for use with the {@code BROKER_CLIENT} fold constructor.
+ * The supplier re-reads {@code getAuthData()} on each poll so credential rotation is observed; a checked
+ * {@link PulsarClientException} is rethrown unchecked and handled by the factory's keep-last-good poll.
+ *
+ * @param authentication the broker-client authentication plugin (never {@code null})
+ * @return a supplier of the plugin's current authentication data
+ */
+ public static Supplier<AuthenticationDataProvider> authMaterialSupplier(Authentication authentication) {
+ Objects.requireNonNull(authentication, "authentication must not be null");
+ return () -> {
+ try {
+ return resolveAuthData(authentication);
+ } catch (PulsarClientException e) {
+ throw new RuntimeException("Failed to obtain broker-client authentication TLS material", e);
+ }
+ };
+ }
+
+ // The BROKER_CLIENT TLS fold is host-agnostic — TLS key material does not vary by peer — so the
+ // host-less getAuthData() is exactly what we want; isolate its deprecation here.
+ @SuppressWarnings("deprecation")
+ private static AuthenticationDataProvider resolveAuthData(Authentication authentication)
+ throws PulsarClientException {
+ return authentication.getAuthData();
+ }
+
+ @Override
+ public CompletableFuture<Void> initialize(TlsFactoryInitContext context) {
+ try {
+ Objects.requireNonNull(context, "context must not be null");
+ // Required, not optional: every acquisition path in this factory reads files and parses key
+ // material. Without an executor the work would run inline on the caller's thread, which the SPI
+ // contract says may be a consumer event loop. Fail at wiring time rather than stalling a channel.
+ Objects.requireNonNull(context.blockingExecutor(),
+ "TlsFactoryInitContext.blockingExecutor() must not be null: FileBasedTlsFactory performs "
+ + "blocking file and key-material loading and must never run it on a consumer thread");
+ this.initContext = context;
+ // Cancel any poll scheduled by a prior initialize() so a second call does not orphan the first:
+ // the field is overwritten below and the old task would otherwise run forever.
+ ScheduledFuture<?> previousPoll = this.pollFuture;
+ if (previousPoll != null) {
+ previousPoll.cancel(false);
+ }
+ // Same reasoning for the metrics: a prior initialize() registered an observable gauge that stays
+ // registered on the meter until close(), so overwriting the field without closing it would leave
+ // an orphaned callback reporting stale per-purpose timestamps forever.
+ TlsReloadMetrics previousMetrics = this.metrics;
+ if (previousMetrics != null) {
+ previousMetrics.close();
+ }
+ this.metrics = TlsReloadMetrics.create(context.openTelemetry(), context.clock());
Review Comment:
The failure cannot occur — but you were right to flag it, because the build file says something false. Both are gone in 21a9afb64a5.
`pulsar-common` declares `api(project(":pulsar-tls-factory-api"))`, and that module declares `api(libs.opentelemetry.api)` (it has to — `TlsFactoryInitContext` exposes `OpenTelemetry` on the SPI surface). So the classes are on `pulsar-common`'s compile *and* runtime classpaths transitively: `./gradlew :pulsar-common:dependencies --configuration runtimeClasspath` shows `io.opentelemetry:opentelemetry-api:1.62.0`, propagating at `api` scope to every downstream consumer. The shaded jars publish it as `shadowApi`.
Where you are right: that `compileOnly` line is **redundant**, and its comment claimed it matched `pulsar-tls-factory-api` when that module uses `api`. I confirmed the redundancy by deleting the line — `:pulsar-common:compileJava` still succeeds — so rather than promote it to `implementation` I deleted the declaration and the comment, which removes the thing that made it look like a `compileOnly` risk.
One precision on the mechanism: `initialize()` catches `Throwable` and fails the returned future, so a genuinely missing class would surface as a failed initialization rather than a `NoClassDefFoundError` escaping to the caller. Still fatal to startup — just not the shape described.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/JettyTlsFactory.java:
##########
@@ -0,0 +1,586 @@
+/*
+ * 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.jetty.tls;
+
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.tls.impl.TlsContexts;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * The framework's Jetty integration for the PIP-478 TLS SPI. Both {@link SslContextFactory.Server} and
+ * {@link SslContextFactory.Client} are well-known SPI classes: the framework first asks the
+ * {@link PulsarTlsFactory} to supply one natively (a custom factory may build and own it, reload
+ * included); only when the factory returns {@code empty()} for the Jetty class does the framework
+ * synthesize a <em>vanilla</em> (never subclassed) one from an {@code SSLContext} subscription. The
+ * default {@code FileBasedTlsFactory} returns {@code empty()} for the Jetty classes, so the synthesized
+ * path is the usual one.
+ *
+ * <p><b>Factory-supplied (native) instances.</b> When the factory supplies the Jetty factory directly it
+ * is handed back <em>unstarted</em> (the connector / {@code HttpClient} starts it), is the factory's
+ * same-instance-per-purpose, and the factory owns its reload on material rotation. The framework only
+ * holds the returned {@link TlsHandle} for disposal and never drives {@code setSslContext}/{@code reload}
+ * or overlays consumer configuration on such an instance.
+ *
+ * <p>This deliberately abandons the unsound {@code getSslContext()} override of the superseded PIP-337
+ * {@code JettySslContextFactory}. Instead it uses
+ * Jetty's documented hot-reload API — the same one {@code KeyStoreScanner} uses: an {@code SSLContext}
+ * subscription drives {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each
+ * later delivery (once started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context and re-selects
+ * protocols/ciphers. Existing connections keep their sessions; new connections use the new context.
+ *
+ * <p><b>{@code SSLParameters} companion (PIP-478).</b> Because these are synthesized paths (the factory
+ * returned {@code empty()} for the Jetty class and supplies only the {@code SSLContext}), the framework also
+ * asks the factory for its optional {@code javax.net.ssl.SSLParameters} companion — the engine-level baseline
+ * a bare {@code SSLContext} cannot express — and maps its non-null members onto the Jetty setters: enabled
+ * protocols ({@link SslContextFactory#setIncludeProtocols}) and cipher suites
+ * ({@link SslContextFactory#setIncludeCipherSuites}), and (server side, merge rule 4) the authoritative
+ * client-auth mode ({@link SslContextFactory.Server#setNeedClientAuth} /
+ * {@link SslContextFactory.Server#setWantClientAuth}). The initial companion is overlaid before start (at build
+ * time); on each subsequent <em>rotation</em> delivery it is re-requested <em>asynchronously</em> — the reload
+ * callback composes {@code createInstance(purpose, SSLParameters.class)} with {@code whenComplete} and only then
+ * calls {@code reload(...)}, so engine policy rotates with material (pip-478.md:736) yet the companion is
+ * <b>never joined on the delivery thread</b>. Joining there would self-deadlock a custom factory that dispatches
+ * companion creation to the same single-thread scheduler that runs the poll delivery — the exact hazard
+ * {@code TlsContextAcquisition.SynthesizingSubscription} avoids by composing the companion asynchronously.
+ *
+ * <p>Because those asynchronous re-requests complete on arbitrary threads and may finish out of order, the
+ * synthesized reload mirrors the two ordering guarantees of {@code SynthesizingSubscription} (see
+ * {@code JettyReloadCoordinator}): each delivery captures a strictly increasing <em>generation</em> and applies
+ * its {@code reload(...)} only while that generation is still the latest, so a companion superseded by a newer
+ * rotation is dropped rather than pinning the listener to a stale context/baseline; and the last
+ * successfully-resolved companion is <em>retained</em> (seeded from the build-time baseline) so a transient
+ * companion-fetch failure during rotation reloads with that last-good baseline rather than downgrading engine
+ * policy (protocols/ciphers and, server side, client-auth) to consumer defaults. Consumer defaults are still
+ * re-applied <em>in full</em> first inside every {@code reload(...)} lambda — protocols, cipher suites and, server
+ * side, client-auth are each re-pinned or cleared unconditionally, since the long-lived {@code SslContextFactory}
+ * persists setter state across {@code reload()} — so any companion member legitimately dropped by a newer delivery
+ * reverts to the consumer default rather than staying stuck from the previous companion.
+ * {@code empty()} leaves the consumer's configuration in force, exactly as before.
+ */
+@CustomLog
+public final class JettyTlsFactory {
+
+ static {
+ // DO NOT EDIT - Load Conscrypt provider
+ if (JcaProviders.CONSCRYPT_PROVIDER != null) {
Review Comment:
Agreed — 7316728ac71. Carried over verbatim, and in a new file it reads as a bug. Replaced with `JcaProviders.ensureConscryptRegistered()`, a named no-op whose javadoc states what the call is for, and dropped the "DO NOT EDIT" now that nothing cryptic is left to protect.
##########
pulsar-common/src/test/resources/META-INF/services/java.security.Provider:
##########
@@ -0,0 +1 @@
+org.apache.pulsar.common.util.tls.ServiceLoadableTestProvider
Review Comment:
The visibility is exactly as you describe, but both alternatives defeat the fixture's purpose, so I have kept it and recorded why on the fixture itself (50d91093f0a).
`Security.addProvider` in a `@BeforeClass` would exercise resolution step 1 — the registered provider — when the fixture exists precisely to be reachable through step 2. The assertion is that when *both* can answer a name, the operator-registered instance beats the one `ServiceLoader` constructs through the no-arg constructor; registering it programmatically removes the condition under test. A dedicated source set is a lot of Gradle for an inert fixture.
On blast radius: the fixture registers **zero** services, so it can never satisfy a `getInstance()` call — it is visible only to code enumerating `ServiceLoader<Provider>`, costing one no-op construction.
(Minor: only `JcaProvidersTest` uses it today.)
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/JettyTlsFactory.java:
##########
@@ -0,0 +1,586 @@
+/*
+ * 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.jetty.tls;
+
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.tls.impl.TlsContexts;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * The framework's Jetty integration for the PIP-478 TLS SPI. Both {@link SslContextFactory.Server} and
+ * {@link SslContextFactory.Client} are well-known SPI classes: the framework first asks the
+ * {@link PulsarTlsFactory} to supply one natively (a custom factory may build and own it, reload
+ * included); only when the factory returns {@code empty()} for the Jetty class does the framework
+ * synthesize a <em>vanilla</em> (never subclassed) one from an {@code SSLContext} subscription. The
+ * default {@code FileBasedTlsFactory} returns {@code empty()} for the Jetty classes, so the synthesized
+ * path is the usual one.
+ *
+ * <p><b>Factory-supplied (native) instances.</b> When the factory supplies the Jetty factory directly it
+ * is handed back <em>unstarted</em> (the connector / {@code HttpClient} starts it), is the factory's
+ * same-instance-per-purpose, and the factory owns its reload on material rotation. The framework only
+ * holds the returned {@link TlsHandle} for disposal and never drives {@code setSslContext}/{@code reload}
+ * or overlays consumer configuration on such an instance.
+ *
+ * <p>This deliberately abandons the unsound {@code getSslContext()} override of the superseded PIP-337
+ * {@code JettySslContextFactory}. Instead it uses
+ * Jetty's documented hot-reload API — the same one {@code KeyStoreScanner} uses: an {@code SSLContext}
+ * subscription drives {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each
+ * later delivery (once started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context and re-selects
+ * protocols/ciphers. Existing connections keep their sessions; new connections use the new context.
+ *
+ * <p><b>{@code SSLParameters} companion (PIP-478).</b> Because these are synthesized paths (the factory
+ * returned {@code empty()} for the Jetty class and supplies only the {@code SSLContext}), the framework also
+ * asks the factory for its optional {@code javax.net.ssl.SSLParameters} companion — the engine-level baseline
+ * a bare {@code SSLContext} cannot express — and maps its non-null members onto the Jetty setters: enabled
+ * protocols ({@link SslContextFactory#setIncludeProtocols}) and cipher suites
+ * ({@link SslContextFactory#setIncludeCipherSuites}), and (server side, merge rule 4) the authoritative
+ * client-auth mode ({@link SslContextFactory.Server#setNeedClientAuth} /
+ * {@link SslContextFactory.Server#setWantClientAuth}). The initial companion is overlaid before start (at build
+ * time); on each subsequent <em>rotation</em> delivery it is re-requested <em>asynchronously</em> — the reload
+ * callback composes {@code createInstance(purpose, SSLParameters.class)} with {@code whenComplete} and only then
+ * calls {@code reload(...)}, so engine policy rotates with material (pip-478.md:736) yet the companion is
+ * <b>never joined on the delivery thread</b>. Joining there would self-deadlock a custom factory that dispatches
+ * companion creation to the same single-thread scheduler that runs the poll delivery — the exact hazard
+ * {@code TlsContextAcquisition.SynthesizingSubscription} avoids by composing the companion asynchronously.
+ *
+ * <p>Because those asynchronous re-requests complete on arbitrary threads and may finish out of order, the
+ * synthesized reload mirrors the two ordering guarantees of {@code SynthesizingSubscription} (see
+ * {@code JettyReloadCoordinator}): each delivery captures a strictly increasing <em>generation</em> and applies
+ * its {@code reload(...)} only while that generation is still the latest, so a companion superseded by a newer
+ * rotation is dropped rather than pinning the listener to a stale context/baseline; and the last
+ * successfully-resolved companion is <em>retained</em> (seeded from the build-time baseline) so a transient
+ * companion-fetch failure during rotation reloads with that last-good baseline rather than downgrading engine
+ * policy (protocols/ciphers and, server side, client-auth) to consumer defaults. Consumer defaults are still
+ * re-applied <em>in full</em> first inside every {@code reload(...)} lambda — protocols, cipher suites and, server
+ * side, client-auth are each re-pinned or cleared unconditionally, since the long-lived {@code SslContextFactory}
+ * persists setter state across {@code reload()} — so any companion member legitimately dropped by a newer delivery
+ * reverts to the consumer default rather than staying stuck from the previous companion.
+ * {@code empty()} leaves the consumer's configuration in force, exactly as before.
+ */
+@CustomLog
+public final class JettyTlsFactory {
+
+ static {
+ // DO NOT EDIT - Load Conscrypt provider
+ if (JcaProviders.CONSCRYPT_PROVIDER != null) {
+ }
+ }
+
+ private JettyTlsFactory() {
+ }
+
+ /**
+ * A Jetty server factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the web service stops.
+ *
+ * @param sslContextFactory the (unstarted) Jetty server factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableServerTls(SslContextFactory.Server sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * A Jetty client factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the owning HTTP client
+ * / servlet is destroyed.
+ *
+ * @param sslContextFactory the (unstarted) Jetty client factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableClientTls(SslContextFactory.Client sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * Build a self-reloading {@link SslContextFactory.Server} for a purpose, handed back <em>unstarted</em>
+ * (Jetty starts it with the connector lifecycle) with its initial {@code SSLContext} already set.
+ *
+ * @param factory the TLS factory to subscribe to
+ * @param purpose the server purpose (e.g. {@link TlsPurpose#WEB})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param requireTrustedClientCert whether to require (vs. request) a trusted client certificate
+ * @param allowInsecureConnection whether an untrusted client cert is accepted under optional client auth
+ * @param ciphers enabled cipher suites, or {@code null} for defaults
+ * @param protocols enabled protocols, or {@code null} for defaults
+ * @return the reloading factory and its subscription handle
+ */
+ public static ReloadableServerTls createReloadingServerFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString,
+ boolean requireTrustedClientCert,
+ boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ // Ask the factory first: a custom factory may natively supply the Jetty server factory (a
+ // well-known class). When it does, hand it back unstarted with the factory owning its reload and
+ // configuration; the framework overlays no consumer config on it. The default file-based factory
+ // returns empty() here, so the synthesized, self-reloading fallback below runs (the usual path).
+ Optional<TlsHandle<SslContextFactory.Server>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Server.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Server> handle = nativeFactory.get();
+ return new ReloadableServerTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
+ // Consumer config plus the factory's engine-policy companion (if any), before start. The resolved
+ // companion seeds the coordinator's last-good baseline so a companion-fetch failure on the very first
+ // rotation retains it rather than downgrading to consumer defaults.
+ SSLParameters initialBaseline = configureServerBaseline(sslContextFactory, factory, purpose,
+ sslProviderString, requireTrustedClientCert, allowInsecureConnection, ciphers, protocols);
+
+ // Each rotation re-requests the companion asynchronously (off the delivery thread) and applies it under
+ // a generation guard so an out-of-order companion cannot pin a stale context, retaining the last-good
+ // baseline across a transient companion failure. See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, sslContextFactory,
+ initialBaseline, (newContext, baseline) -> {
+ sslContextFactory.setSslContext(newContext);
+ // Re-apply the consumer defaults first so a companion member dropped by this delivery
+ // (notably client-auth) reverts to the consumer default rather than staying stuck from the
+ // previous companion, then overlay the generation-guarded, last-good companion.
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert,
+ allowInsecureConnection, ciphers, protocols);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery)
+ .join()
+ .orElseThrow(() -> new IllegalStateException(
+ "TLS factory supplied no SSLContext for purpose " + purpose));
+ return new ReloadableServerTls(sslContextFactory, coordinator.bind(subscription));
+ }
+
+ /**
+ * Build an {@link SslContextFactory.Client} for a purpose (used by the proxy's {@code AdminProxyHandler},
+ * whose Jetty {@code HttpClient} outlives broker-client material rotation), handed back
+ * <em>unstarted</em>. Mirroring {@link #createReloadingServerFactory}, the framework first asks the
+ * factory to supply the Jetty client factory natively; a custom factory that does so owns its reload and
+ * endpoint identification, and the framework overlays nothing on it. Otherwise a vanilla, self-reloading
+ * one is synthesized: an {@code SSLContext} subscription drives
+ * {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each later delivery (once
+ * started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context so new connections use
+ * the rotated material. Dispose the returned {@link ReloadableClientTls#subscription()} when the owning
+ * client is destroyed.
+ *
+ * @param factory the TLS factory to acquire from / subscribe to
+ * @param purpose the client purpose (e.g. {@link TlsPurpose#BROKER_CLIENT})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param enableHostnameVerification whether to verify the peer hostname; when {@code false} the
+ * synthesized client's endpoint identification is disabled (a
+ * factory-supplied native client owns this itself and is left untouched)
+ * @return the client factory and the handle backing it
+ */
+ public static ReloadableClientTls createReloadingClientFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString,
+ boolean enableHostnameVerification) {
+ // Ask the factory first: a custom factory may natively supply the Jetty client factory (a well-known
+ // class, mirroring the Server variant) to customize proxy->broker admin TLS. When it does, hand it
+ // back unstarted with the factory owning its reload and its own endpoint identification; the
+ // framework overlays no consumer config on it. The default file-based factory returns empty() here,
+ // so the SSLContext-synthesized, self-reloading fallback below runs (the usual path, including
+ // rotation of the long-lived admin HttpClient's broker-client material).
+ Optional<TlsHandle<SslContextFactory.Client>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Client.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Client> handle = nativeFactory.get();
+ return new ReloadableClientTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Client client = new SslContextFactory.Client();
+ if (StringUtils.isNotBlank(sslProviderString)) {
+ client.setProvider(sslProviderString);
+ }
+ // Pin the {TLSv1.3, TLSv1.2} floor and overlay the factory's engine-policy companion (if any), before
+ // start; the resolved companion seeds the coordinator's last-good baseline (see the Server variant).
+ SSLParameters initialBaseline = configureClientBaseline(client, factory, purpose);
+ // Hostname verification is a consumer (proxy) concern on the synthesized path: disable endpoint
+ // identification when the consumer has it off (a native factory, handled above, owns this itself). This
+ // is a per-consumer setting applied once at build, not part of the per-delivery companion overlay.
+ if (!enableHostnameVerification) {
+ client.setEndpointIdentificationAlgorithm(null);
+ }
+
+ // Rotations re-request the companion asynchronously (off the delivery thread) and apply it under a
+ // generation guard, retaining the last-good baseline across a transient companion failure (client-auth
+ // is a server concept; endpoint identification stays as set at build). See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, client, initialBaseline,
+ (newContext, baseline) -> {
+ client.setSslContext(newContext);
+ // Re-apply the consumer defaults first (the {TLSv1.3, TLSv1.2} floor and an unrestricted cipher
+ // list), then overlay the generation-guarded, last-good companion so a companion member dropped
+ // by this delivery reverts to those defaults rather than staying stuck from the previous one.
+ applyClientConfig(client);
+ if (baseline != null) {
+ applyClientBaseline(client, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery)
+ .join()
+ .orElseThrow(() -> new IllegalStateException(
+ "TLS factory supplied no SSLContext for purpose " + purpose));
+ return new ReloadableClientTls(client, coordinator.bind(subscription));
+ }
+
+ /**
+ * Apply the consumer config, then overlay the factory's engine-policy companion, onto a synthesized server
+ * factory — at build time only (off any event loop; the companion is joined here). Each subsequent rotation
+ * delivery re-requests the companion asynchronously and re-applies it inside the {@code reload(...)} lambda
+ * (see {@link JettyReloadCoordinator}), never joined on the delivery thread.
+ *
+ * @return the resolved companion baseline, or {@code null} when the factory supplied none — used to seed the
+ * coordinator's retained last-good baseline.
+ */
+ private static SSLParameters configureServerBaseline(SslContextFactory.Server sslContextFactory,
+ PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString, boolean requireTrustedClientCert,
+ boolean allowInsecureConnection, Set<String> ciphers,
+ Set<String> protocols) {
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert, allowInsecureConnection,
+ ciphers, protocols);
+ SSLParameters baseline = resolveBaselineParameters(factory, purpose).orElse(null);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ return baseline;
+ }
+
+ /**
+ * Pin the {@code {TLSv1.3, TLSv1.2}} floor, then overlay the factory companion's protocols/ciphers, onto a
+ * synthesized client factory — at build time only (off any event loop; the companion is joined here). Each
+ * subsequent rotation delivery re-requests the companion asynchronously and re-pins the floor + overlays it
+ * inside the {@code reload(...)} lambda (see {@link JettyReloadCoordinator}), never joined on the delivery
+ * thread. Client-auth is a server concept and is not mapped here; endpoint identification is a per-consumer
+ * setting applied once at build.
+ *
+ * @return the resolved companion baseline, or {@code null} when the factory supplied none — used to seed the
+ * coordinator's retained last-good baseline.
+ */
+ private static SSLParameters configureClientBaseline(SslContextFactory.Client client, PulsarTlsFactory factory,
+ TlsPurpose purpose) {
+ applyClientConfig(client);
+ SSLParameters baseline = resolveBaselineParameters(factory, purpose).orElse(null);
+ if (baseline != null) {
+ applyClientBaseline(client, baseline);
+ }
+ return baseline;
+ }
+
+ /**
+ * The synthesized client's consumer defaults, shared by the build-time overlay and every reload lambda so both
+ * agree on what a dropped companion member reverts to: the {@code {TLSv1.3, TLSv1.2}} floor, and an unrestricted
+ * cipher list (an empty include list means "no restriction" in Jetty). Both are cleared/re-pinned unconditionally
+ * because the factory is long-lived and persists setter state across {@code reload()}. The provider and endpoint
+ * identification are per-consumer settings applied once at build, not part of this per-delivery reset.
+ */
+ private static void applyClientConfig(SslContextFactory.Client client) {
+ client.setIncludeProtocols(TlsContexts.DEFAULT_ENABLED_PROTOCOLS.toArray(new String[0]));
+ client.setIncludeCipherSuites();
+ }
+
+ private static void applyServerConfig(SslContextFactory.Server sslContextFactory, String sslProviderString,
+ boolean requireTrustedClientCertOnConnect, boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ if (ciphers != null && !ciphers.isEmpty()) {
+ sslContextFactory.setIncludeCipherSuites(ciphers.toArray(new String[0]));
+ } else {
+ // Clear the include list explicitly (not just rely on the fresh-factory default), for the same reason
+ // needClientAuth is reset below: this method is re-applied on each reload of a long-lived factory, so a
+ // prior companion delivery that pinned cipher suites must revert to the consumer default before a later
+ // companion (or its absence) is overlaid. An empty include list means "no restriction" in Jetty --
+ // SslContextFactory.processIncludeExcludePatterns falls back to the SSLContext's enabled suites.
+ sslContextFactory.setIncludeCipherSuites();
+ }
+ // Pin the enabled protocols even when unconfigured, matching the {TLSv1.3, TLSv1.2} floor the native
+ // Netty path applies rather than deferring to the provider default. A factory-supplied companion,
+ // applied afterwards by applyServerBaseline, still overrides this.
+ if (protocols != null && !protocols.isEmpty()) {
+ sslContextFactory.setIncludeProtocols(protocols.toArray(new String[0]));
+ } else {
+ sslContextFactory.setIncludeProtocols(TlsContexts.DEFAULT_ENABLED_PROTOCOLS.toArray(new String[0]));
+ }
+ if (StringUtils.isNotBlank(sslProviderString)) {
+ sslContextFactory.setProvider(sslProviderString);
+ }
+ if (requireTrustedClientCertOnConnect) {
+ sslContextFactory.setNeedClientAuth(true);
+ sslContextFactory.setTrustAll(false);
+ } else {
+ // PIP-478: optional client auth requests but does not require a client cert. An untrusted
+ // client cert is accepted at the handshake only when tlsAllowInsecureConnection=true, aligning the
+ // web listener with the Netty binary listener's semantics and diverging from the pre-5.0 Jetty
+ // path, which trusted any presented client cert whenever client auth was optional (see PIP-478
+ // Security Considerations).
+ //
+ // The actual enforcement is the trust managers baked into the SSLContext the framework hands to
+ // Jetty via setSslContext (built from the WEB TlsPolicy's allowInsecureConnection: CA-validating
+ // when secure, insecure-trust-all when insecure). Jetty's own setTrustAll only takes effect when
+ // Jetty builds the SSLContext itself, so it is inert on this setSslContext path; we still scope it
+ // to the insecure flag so the two never disagree (defence in depth) rather than leaving the
+ // inherited unconditional setTrustAll(true).
+ // Clear needClientAuth explicitly (not just rely on the fresh-factory default): this method is
+ // re-applied on each reload, so a prior companion delivery that set needClientAuth must be reset to
+ // the consumer default here before a later companion (or its absence) is overlaid.
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(true);
+ sslContextFactory.setTrustAll(allowInsecureConnection);
+ }
+ // https://jetty.org/docs/jetty/12.1/operations-guide/protocols/index.html#ssl-sni
+ // Set to false for backwards compatibility with Jetty 9.x
+ sslContextFactory.setSniRequired(false);
+ }
+
+ /**
+ * Ask the factory to supply a native Jetty {@code jettyClass} for {@code purpose} (one-shot). Jetty's
+ * {@link SslContextFactory.Server} and {@link SslContextFactory.Client} are well-known SPI classes, so a
+ * custom factory MAY build one directly; the default {@code FileBasedTlsFactory} returns
+ * {@link Optional#empty()}, in which case the caller synthesizes the factory from an {@code SSLContext}
+ * subscription. A supplied instance is the factory's own (unstarted, same-instance-per-purpose,
+ * factory-driven reload) — the caller returns it verbatim and keeps the {@link TlsHandle} for disposal.
+ * Resolved at factory-build time (off any event loop), mirroring {@link #resolveBaselineParameters}.
+ */
+ private static <T extends SslContextFactory> Optional<TlsHandle<T>> acquireNativeJettyFactory(
+ PulsarTlsFactory factory, TlsPurpose purpose, Class<T> jettyClass) {
+ return factory.createInstance(purpose, jettyClass).join();
+ }
+
+ /**
+ * Request the factory's optional {@code SSLParameters} companion for a purpose (one-shot) at factory-build
+ * time, joining off any event loop, and return the supplied instance or {@link Optional#empty()} when the
+ * factory supplies none. Rotation deliveries do NOT use this: they re-request the companion asynchronously
+ * inside {@link JettyReloadCoordinator} (never joined on the delivery thread) and unwrap it via
+ * {@link #extractBaseline}.
+ */
+ private static Optional<SSLParameters> resolveBaselineParameters(PulsarTlsFactory factory, TlsPurpose purpose) {
+ return Optional.ofNullable(extractBaseline(factory.createInstance(purpose, SSLParameters.class).join()));
+ }
+
+ /**
+ * Unwrap the factory's {@code SSLParameters} companion from its handle, disposing the handle afterwards (a
+ * companion carries no reference-counted state). Returns {@code null} when the factory supplied none
+ * ({@link Optional#empty()}). Used both by the build-time {@link #resolveBaselineParameters} and by the
+ * asynchronous per-rotation re-request in {@link JettyReloadCoordinator}.
+ */
+ private static SSLParameters extractBaseline(Optional<TlsHandle<SSLParameters>> handle) {
+ if (handle.isEmpty()) {
+ return null;
+ }
+ TlsHandle<SSLParameters> paramsHandle = handle.get();
+ try {
+ return paramsHandle.get();
+ } finally {
+ paramsHandle.dispose();
+ }
+ }
+
+ /**
+ * Overlay a factory-supplied engine baseline onto a synthesized server factory (PIP-478 merge order):
+ * enabled protocols/cipher suites when the companion sets them, and the companion's client-auth mode as
+ * authoritative (rule 4) — {@code needClientAuth} wins over {@code wantClientAuth}, neither means none.
+ */
+ private static void applyServerBaseline(SslContextFactory.Server sslContextFactory, SSLParameters baseline) {
+ if (baseline.getProtocols() != null) {
+ sslContextFactory.setIncludeProtocols(baseline.getProtocols());
+ }
+ if (baseline.getCipherSuites() != null) {
+ sslContextFactory.setIncludeCipherSuites(baseline.getCipherSuites());
+ }
+ if (baseline.getNeedClientAuth()) {
+ sslContextFactory.setNeedClientAuth(true);
+ } else if (baseline.getWantClientAuth()) {
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(true);
+ } else {
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(false);
+ }
+ }
+
+ /**
+ * Overlay a factory-supplied engine baseline onto a synthesized client factory: enabled protocols/cipher
+ * suites only (client-auth is a server concept; SNI/hostname verification remain per-connection).
+ */
+ private static void applyClientBaseline(SslContextFactory.Client client, SSLParameters baseline) {
+ if (baseline.getProtocols() != null) {
+ client.setIncludeProtocols(baseline.getProtocols());
+ }
+ if (baseline.getCipherSuites() != null) {
+ client.setIncludeCipherSuites(baseline.getCipherSuites());
+ }
+ }
+
+ /**
+ * Per-subscription reload coordinator for the synthesized Jetty paths. It ports the two ordering guarantees
+ * of {@code TlsContextAcquisition.SynthesizingSubscription} to Jetty's hot-reload API, which the naive
+ * "compose {@code createInstance(SSLParameters)} then {@code reload}" delivery lacked:
+ *
+ * <ul>
+ * <li><b>Generation guard.</b> Each delivery captures a strictly increasing generation (deliveries are
+ * serial per subscription, per the SPI contract). A rotation's companion re-request is composed
+ * asynchronously and may complete on an arbitrary thread and out of order, so its {@code reload(...)}
+ * is applied — under a lock — only while its generation is still the latest; a companion superseded
+ * by a newer rotation is dropped rather than pinning the listener to a stale context/baseline.</li>
+ * <li><b>Last-good baseline retention.</b> The last successfully-resolved companion is retained (seeded
+ * from the build-time baseline). A transient companion-fetch failure during rotation reloads with that
+ * last-good baseline rather than consumer defaults, so it cannot silently drop protocols/ciphers or
+ * (server side) client-auth. The retained baseline is updated only for a successfully-resolved,
+ * non-superseded companion, under the same lock.</li>
+ * </ul>
+ *
+ * <p>The companion is never joined on the delivery thread (the self-deadlock hazard described on the class
+ * javadoc); only the <em>first</em> delivery — which fires synchronously inside the subscribe call, before the
+ * built factory is even returned — sets the already-overlaid context directly, mirroring
+ * {@code SynthesizingSubscription}'s pre-fetched first delivery. Every later delivery is a rotation and
+ * re-requests the companion, <em>including one that arrives before the connector/client starts</em>; whether
+ * the factory is started only decides how the result is applied (Jetty's {@code reload(...)} once started, the
+ * same setters directly before), so a factory started after such a rotation starts with that rotation's
+ * material AND its companion policy rather than the stale build-time baseline.
+ */
+ private static final class JettyReloadCoordinator {
+
+ private final PulsarTlsFactory factory;
+ private final TlsPurpose purpose;
+ private final SslContextFactory target;
+ // Applies the rotated context + (nullable) companion baseline inside Jetty's reload lambda.
+ private final BiConsumer<SSLContext, SSLParameters> applyReload;
+ // Last successfully-resolved companion, seeded from the pre-fetched build-time baseline. Retained across
+ // a transient companion-fetch failure so a rotation cannot silently downgrade engine policy.
+ private volatile SSLParameters lastBaseline;
+ // One-shot: only the first (synchronous, pre-fetched) delivery reuses the build-time baseline; every
+ // later delivery is a rotation and re-requests the companion, started or not.
+ private final AtomicBoolean firstDelivery = new AtomicBoolean(true);
+ private final AtomicLong deliveryGeneration = new AtomicLong();
+ private long lastPublishedGeneration;
+ // A rotation's companion request is composed asynchronously, so its completion can land after the
+ // owner disposed the subscription (and, on the server path, after Jetty stopped the connector).
+ // Reloading a stopped/abandoned factory then would be a pointless mutation at best.
+ private final AtomicBoolean disposed = new AtomicBoolean();
+
+ JettyReloadCoordinator(PulsarTlsFactory factory, TlsPurpose purpose, SslContextFactory target,
+ SSLParameters initialBaseline, BiConsumer<SSLContext, SSLParameters> applyReload) {
+ this.factory = factory;
+ this.purpose = purpose;
+ this.target = target;
+ this.lastBaseline = initialBaseline;
+ this.applyReload = applyReload;
+ }
+
+ /**
+ * Wrap the backing subscription so disposing it also stops this coordinator. Synchronized on the same
+ * monitor as {@link #publish}, so dispose returns only once any in-flight publish has finished —
+ * setting the flag alone would still let a publisher that had already passed the check reload a
+ * factory its owner has torn down.
+ */
+ TlsHandle<SSLContext> bind(TlsHandle<SSLContext> subscription) {
+ return new TlsHandle<>() {
+ @Override
+ public SSLContext get() {
+ return subscription.get();
+ }
+
+ @Override
+ public void dispose() {
+ synchronized (JettyReloadCoordinator.this) {
+ disposed.set(true);
+ }
+ subscription.dispose();
+ }
+ };
+ }
+
+ // Serial per subscription (SPI contract), so each delivery gets a strictly increasing generation.
+ void onDelivery(SSLContext newContext) {
+ long generation = deliveryGeneration.incrementAndGet();
+ if (firstDelivery.compareAndSet(true, false)) {
+ // The first delivery fires synchronously inside the subscribe call, before the built factory is
+ // returned (let alone started): the build-time companion was already overlaid and seeds
+ // lastBaseline, so only the context is missing — set it directly, mirroring
+ // SynthesizingSubscription's pre-fetched first delivery.
+ target.setSslContext(newContext);
+ return;
+ }
+ // Rotation delivery. Re-request the companion so engine policy rotates WITH the material
+ // (pip-478.md:736), resolved ASYNCHRONOUSLY off this delivery thread and never joined here (the
+ // self-deadlock hazard). This runs for rotations delivered BEFORE start too — those must refresh the
+ // companion as well, otherwise the connector would start with the rotated context but the stale
+ // build-time baseline; only the mechanism used to apply the result differs (see publish). The
+ // generation guard in publish drops a superseded companion; the last-good baseline is maintained
+ // there, never here, so a superseded companion completing late cannot regress it.
+ factory.createInstance(purpose, SSLParameters.class).whenComplete((companion, err) ->
Review Comment:
This is the best catch in the review and it is correct. Fixed in a4832cd40e1.
I traced the same path: `isSupported()` covers only `SslContext` and `SSLContext`, so the `SSLParameters` request returns an already-completed future, the `whenComplete` runs inline on the delivery thread, and that thread is inside `synchronized deliverToSubscribers` — the Jetty reload ran with the source monitor held. "Never joined" was literally true and beside the point. You are also right that this made the framework's own first consumer break the "cheap non-blocking store" contract `deliverToSubscribers` states.
Fixed your way: both builders now take the reload `Executor` and `onDelivery` uses `whenCompleteAsync`, so `publish` never runs on the delivery thread. No callers exist yet, so the signature change was free. The first delivery — synchronous during subscribe, only setting the context — stays inline. A new test asserts the reload runs on the supplied executor and not on the delivery thread; the existing tests pass a same-thread executor so their synchronous assertions stay deterministic.
One qualification for the record: only a delivery — changed material or a pending redeliver — took that path, so a steady-state poll with no rotation did not block. That narrows the exposure without changing the conclusion. And I also looked for the reverse lock order and did not find one (`bind().dispose()` releases the coordinator monitor before taking the source monitor), so I agree there was no deadlock today, only an undocumented load-bearing order.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/JettyTlsFactory.java:
##########
@@ -0,0 +1,586 @@
+/*
+ * 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.jetty.tls;
+
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.tls.impl.TlsContexts;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * The framework's Jetty integration for the PIP-478 TLS SPI. Both {@link SslContextFactory.Server} and
+ * {@link SslContextFactory.Client} are well-known SPI classes: the framework first asks the
+ * {@link PulsarTlsFactory} to supply one natively (a custom factory may build and own it, reload
+ * included); only when the factory returns {@code empty()} for the Jetty class does the framework
+ * synthesize a <em>vanilla</em> (never subclassed) one from an {@code SSLContext} subscription. The
+ * default {@code FileBasedTlsFactory} returns {@code empty()} for the Jetty classes, so the synthesized
+ * path is the usual one.
+ *
+ * <p><b>Factory-supplied (native) instances.</b> When the factory supplies the Jetty factory directly it
+ * is handed back <em>unstarted</em> (the connector / {@code HttpClient} starts it), is the factory's
+ * same-instance-per-purpose, and the factory owns its reload on material rotation. The framework only
+ * holds the returned {@link TlsHandle} for disposal and never drives {@code setSslContext}/{@code reload}
+ * or overlays consumer configuration on such an instance.
+ *
+ * <p>This deliberately abandons the unsound {@code getSslContext()} override of the superseded PIP-337
+ * {@code JettySslContextFactory}. Instead it uses
+ * Jetty's documented hot-reload API — the same one {@code KeyStoreScanner} uses: an {@code SSLContext}
+ * subscription drives {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each
+ * later delivery (once started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context and re-selects
+ * protocols/ciphers. Existing connections keep their sessions; new connections use the new context.
+ *
+ * <p><b>{@code SSLParameters} companion (PIP-478).</b> Because these are synthesized paths (the factory
+ * returned {@code empty()} for the Jetty class and supplies only the {@code SSLContext}), the framework also
+ * asks the factory for its optional {@code javax.net.ssl.SSLParameters} companion — the engine-level baseline
+ * a bare {@code SSLContext} cannot express — and maps its non-null members onto the Jetty setters: enabled
+ * protocols ({@link SslContextFactory#setIncludeProtocols}) and cipher suites
+ * ({@link SslContextFactory#setIncludeCipherSuites}), and (server side, merge rule 4) the authoritative
+ * client-auth mode ({@link SslContextFactory.Server#setNeedClientAuth} /
+ * {@link SslContextFactory.Server#setWantClientAuth}). The initial companion is overlaid before start (at build
+ * time); on each subsequent <em>rotation</em> delivery it is re-requested <em>asynchronously</em> — the reload
+ * callback composes {@code createInstance(purpose, SSLParameters.class)} with {@code whenComplete} and only then
+ * calls {@code reload(...)}, so engine policy rotates with material (pip-478.md:736) yet the companion is
+ * <b>never joined on the delivery thread</b>. Joining there would self-deadlock a custom factory that dispatches
+ * companion creation to the same single-thread scheduler that runs the poll delivery — the exact hazard
+ * {@code TlsContextAcquisition.SynthesizingSubscription} avoids by composing the companion asynchronously.
+ *
+ * <p>Because those asynchronous re-requests complete on arbitrary threads and may finish out of order, the
+ * synthesized reload mirrors the two ordering guarantees of {@code SynthesizingSubscription} (see
+ * {@code JettyReloadCoordinator}): each delivery captures a strictly increasing <em>generation</em> and applies
+ * its {@code reload(...)} only while that generation is still the latest, so a companion superseded by a newer
+ * rotation is dropped rather than pinning the listener to a stale context/baseline; and the last
+ * successfully-resolved companion is <em>retained</em> (seeded from the build-time baseline) so a transient
+ * companion-fetch failure during rotation reloads with that last-good baseline rather than downgrading engine
+ * policy (protocols/ciphers and, server side, client-auth) to consumer defaults. Consumer defaults are still
+ * re-applied <em>in full</em> first inside every {@code reload(...)} lambda — protocols, cipher suites and, server
+ * side, client-auth are each re-pinned or cleared unconditionally, since the long-lived {@code SslContextFactory}
+ * persists setter state across {@code reload()} — so any companion member legitimately dropped by a newer delivery
+ * reverts to the consumer default rather than staying stuck from the previous companion.
+ * {@code empty()} leaves the consumer's configuration in force, exactly as before.
+ */
+@CustomLog
+public final class JettyTlsFactory {
+
+ static {
+ // DO NOT EDIT - Load Conscrypt provider
+ if (JcaProviders.CONSCRYPT_PROVIDER != null) {
+ }
+ }
+
+ private JettyTlsFactory() {
+ }
+
+ /**
+ * A Jetty server factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the web service stops.
+ *
+ * @param sslContextFactory the (unstarted) Jetty server factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableServerTls(SslContextFactory.Server sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * A Jetty client factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the owning HTTP client
+ * / servlet is destroyed.
+ *
+ * @param sslContextFactory the (unstarted) Jetty client factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableClientTls(SslContextFactory.Client sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * Build a self-reloading {@link SslContextFactory.Server} for a purpose, handed back <em>unstarted</em>
+ * (Jetty starts it with the connector lifecycle) with its initial {@code SSLContext} already set.
+ *
+ * @param factory the TLS factory to subscribe to
+ * @param purpose the server purpose (e.g. {@link TlsPurpose#WEB})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param requireTrustedClientCert whether to require (vs. request) a trusted client certificate
+ * @param allowInsecureConnection whether an untrusted client cert is accepted under optional client auth
+ * @param ciphers enabled cipher suites, or {@code null} for defaults
+ * @param protocols enabled protocols, or {@code null} for defaults
+ * @return the reloading factory and its subscription handle
+ */
+ public static ReloadableServerTls createReloadingServerFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString,
+ boolean requireTrustedClientCert,
+ boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ // Ask the factory first: a custom factory may natively supply the Jetty server factory (a
+ // well-known class). When it does, hand it back unstarted with the factory owning its reload and
+ // configuration; the framework overlays no consumer config on it. The default file-based factory
+ // returns empty() here, so the synthesized, self-reloading fallback below runs (the usual path).
+ Optional<TlsHandle<SslContextFactory.Server>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Server.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Server> handle = nativeFactory.get();
+ return new ReloadableServerTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
+ // Consumer config plus the factory's engine-policy companion (if any), before start. The resolved
+ // companion seeds the coordinator's last-good baseline so a companion-fetch failure on the very first
+ // rotation retains it rather than downgrading to consumer defaults.
+ SSLParameters initialBaseline = configureServerBaseline(sslContextFactory, factory, purpose,
+ sslProviderString, requireTrustedClientCert, allowInsecureConnection, ciphers, protocols);
+
+ // Each rotation re-requests the companion asynchronously (off the delivery thread) and applies it under
+ // a generation guard so an out-of-order companion cannot pin a stale context, retaining the last-good
+ // baseline across a transient companion failure. See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, sslContextFactory,
+ initialBaseline, (newContext, baseline) -> {
+ sslContextFactory.setSslContext(newContext);
+ // Re-apply the consumer defaults first so a companion member dropped by this delivery
+ // (notably client-auth) reverts to the consumer default rather than staying stuck from the
+ // previous companion, then overlay the generation-guarded, last-good companion.
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert,
+ allowInsecureConnection, ciphers, protocols);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery)
+ .join()
+ .orElseThrow(() -> new IllegalStateException(
+ "TLS factory supplied no SSLContext for purpose " + purpose));
+ return new ReloadableServerTls(sslContextFactory, coordinator.bind(subscription));
+ }
+
+ /**
+ * Build an {@link SslContextFactory.Client} for a purpose (used by the proxy's {@code AdminProxyHandler},
+ * whose Jetty {@code HttpClient} outlives broker-client material rotation), handed back
+ * <em>unstarted</em>. Mirroring {@link #createReloadingServerFactory}, the framework first asks the
+ * factory to supply the Jetty client factory natively; a custom factory that does so owns its reload and
+ * endpoint identification, and the framework overlays nothing on it. Otherwise a vanilla, self-reloading
+ * one is synthesized: an {@code SSLContext} subscription drives
+ * {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each later delivery (once
+ * started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context so new connections use
+ * the rotated material. Dispose the returned {@link ReloadableClientTls#subscription()} when the owning
+ * client is destroyed.
+ *
+ * @param factory the TLS factory to acquire from / subscribe to
+ * @param purpose the client purpose (e.g. {@link TlsPurpose#BROKER_CLIENT})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param enableHostnameVerification whether to verify the peer hostname; when {@code false} the
+ * synthesized client's endpoint identification is disabled (a
+ * factory-supplied native client owns this itself and is left untouched)
+ * @return the client factory and the handle backing it
+ */
+ public static ReloadableClientTls createReloadingClientFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString,
+ boolean enableHostnameVerification) {
+ // Ask the factory first: a custom factory may natively supply the Jetty client factory (a well-known
+ // class, mirroring the Server variant) to customize proxy->broker admin TLS. When it does, hand it
+ // back unstarted with the factory owning its reload and its own endpoint identification; the
+ // framework overlays no consumer config on it. The default file-based factory returns empty() here,
+ // so the SSLContext-synthesized, self-reloading fallback below runs (the usual path, including
+ // rotation of the long-lived admin HttpClient's broker-client material).
+ Optional<TlsHandle<SslContextFactory.Client>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Client.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Client> handle = nativeFactory.get();
+ return new ReloadableClientTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Client client = new SslContextFactory.Client();
+ if (StringUtils.isNotBlank(sslProviderString)) {
+ client.setProvider(sslProviderString);
+ }
+ // Pin the {TLSv1.3, TLSv1.2} floor and overlay the factory's engine-policy companion (if any), before
+ // start; the resolved companion seeds the coordinator's last-good baseline (see the Server variant).
+ SSLParameters initialBaseline = configureClientBaseline(client, factory, purpose);
+ // Hostname verification is a consumer (proxy) concern on the synthesized path: disable endpoint
+ // identification when the consumer has it off (a native factory, handled above, owns this itself). This
+ // is a per-consumer setting applied once at build, not part of the per-delivery companion overlay.
+ if (!enableHostnameVerification) {
+ client.setEndpointIdentificationAlgorithm(null);
+ }
+
+ // Rotations re-request the companion asynchronously (off the delivery thread) and apply it under a
+ // generation guard, retaining the last-good baseline across a transient companion failure (client-auth
+ // is a server concept; endpoint identification stays as set at build). See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, client, initialBaseline,
+ (newContext, baseline) -> {
+ client.setSslContext(newContext);
+ // Re-apply the consumer defaults first (the {TLSv1.3, TLSv1.2} floor and an unrestricted cipher
+ // list), then overlay the generation-guarded, last-good companion so a companion member dropped
+ // by this delivery reverts to those defaults rather than staying stuck from the previous one.
+ applyClientConfig(client);
+ if (baseline != null) {
+ applyClientBaseline(client, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery)
+ .join()
+ .orElseThrow(() -> new IllegalStateException(
+ "TLS factory supplied no SSLContext for purpose " + purpose));
+ return new ReloadableClientTls(client, coordinator.bind(subscription));
+ }
+
+ /**
+ * Apply the consumer config, then overlay the factory's engine-policy companion, onto a synthesized server
+ * factory — at build time only (off any event loop; the companion is joined here). Each subsequent rotation
+ * delivery re-requests the companion asynchronously and re-applies it inside the {@code reload(...)} lambda
+ * (see {@link JettyReloadCoordinator}), never joined on the delivery thread.
+ *
+ * @return the resolved companion baseline, or {@code null} when the factory supplied none — used to seed the
+ * coordinator's retained last-good baseline.
+ */
+ private static SSLParameters configureServerBaseline(SslContextFactory.Server sslContextFactory,
+ PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString, boolean requireTrustedClientCert,
+ boolean allowInsecureConnection, Set<String> ciphers,
+ Set<String> protocols) {
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert, allowInsecureConnection,
+ ciphers, protocols);
+ SSLParameters baseline = resolveBaselineParameters(factory, purpose).orElse(null);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ return baseline;
+ }
+
+ /**
+ * Pin the {@code {TLSv1.3, TLSv1.2}} floor, then overlay the factory companion's protocols/ciphers, onto a
+ * synthesized client factory — at build time only (off any event loop; the companion is joined here). Each
+ * subsequent rotation delivery re-requests the companion asynchronously and re-pins the floor + overlays it
+ * inside the {@code reload(...)} lambda (see {@link JettyReloadCoordinator}), never joined on the delivery
+ * thread. Client-auth is a server concept and is not mapped here; endpoint identification is a per-consumer
+ * setting applied once at build.
+ *
+ * @return the resolved companion baseline, or {@code null} when the factory supplied none — used to seed the
+ * coordinator's retained last-good baseline.
+ */
+ private static SSLParameters configureClientBaseline(SslContextFactory.Client client, PulsarTlsFactory factory,
+ TlsPurpose purpose) {
+ applyClientConfig(client);
+ SSLParameters baseline = resolveBaselineParameters(factory, purpose).orElse(null);
+ if (baseline != null) {
+ applyClientBaseline(client, baseline);
+ }
+ return baseline;
+ }
+
+ /**
+ * The synthesized client's consumer defaults, shared by the build-time overlay and every reload lambda so both
+ * agree on what a dropped companion member reverts to: the {@code {TLSv1.3, TLSv1.2}} floor, and an unrestricted
+ * cipher list (an empty include list means "no restriction" in Jetty). Both are cleared/re-pinned unconditionally
+ * because the factory is long-lived and persists setter state across {@code reload()}. The provider and endpoint
+ * identification are per-consumer settings applied once at build, not part of this per-delivery reset.
+ */
+ private static void applyClientConfig(SslContextFactory.Client client) {
+ client.setIncludeProtocols(TlsContexts.DEFAULT_ENABLED_PROTOCOLS.toArray(new String[0]));
+ client.setIncludeCipherSuites();
+ }
+
+ private static void applyServerConfig(SslContextFactory.Server sslContextFactory, String sslProviderString,
+ boolean requireTrustedClientCertOnConnect, boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ if (ciphers != null && !ciphers.isEmpty()) {
+ sslContextFactory.setIncludeCipherSuites(ciphers.toArray(new String[0]));
+ } else {
+ // Clear the include list explicitly (not just rely on the fresh-factory default), for the same reason
+ // needClientAuth is reset below: this method is re-applied on each reload of a long-lived factory, so a
+ // prior companion delivery that pinned cipher suites must revert to the consumer default before a later
+ // companion (or its absence) is overlaid. An empty include list means "no restriction" in Jetty --
+ // SslContextFactory.processIncludeExcludePatterns falls back to the SSLContext's enabled suites.
+ sslContextFactory.setIncludeCipherSuites();
+ }
+ // Pin the enabled protocols even when unconfigured, matching the {TLSv1.3, TLSv1.2} floor the native
+ // Netty path applies rather than deferring to the provider default. A factory-supplied companion,
+ // applied afterwards by applyServerBaseline, still overrides this.
+ if (protocols != null && !protocols.isEmpty()) {
+ sslContextFactory.setIncludeProtocols(protocols.toArray(new String[0]));
+ } else {
+ sslContextFactory.setIncludeProtocols(TlsContexts.DEFAULT_ENABLED_PROTOCOLS.toArray(new String[0]));
+ }
+ if (StringUtils.isNotBlank(sslProviderString)) {
+ sslContextFactory.setProvider(sslProviderString);
+ }
+ if (requireTrustedClientCertOnConnect) {
+ sslContextFactory.setNeedClientAuth(true);
+ sslContextFactory.setTrustAll(false);
+ } else {
+ // PIP-478: optional client auth requests but does not require a client cert. An untrusted
+ // client cert is accepted at the handshake only when tlsAllowInsecureConnection=true, aligning the
+ // web listener with the Netty binary listener's semantics and diverging from the pre-5.0 Jetty
+ // path, which trusted any presented client cert whenever client auth was optional (see PIP-478
+ // Security Considerations).
+ //
+ // The actual enforcement is the trust managers baked into the SSLContext the framework hands to
+ // Jetty via setSslContext (built from the WEB TlsPolicy's allowInsecureConnection: CA-validating
+ // when secure, insecure-trust-all when insecure). Jetty's own setTrustAll only takes effect when
+ // Jetty builds the SSLContext itself, so it is inert on this setSslContext path; we still scope it
+ // to the insecure flag so the two never disagree (defence in depth) rather than leaving the
+ // inherited unconditional setTrustAll(true).
+ // Clear needClientAuth explicitly (not just rely on the fresh-factory default): this method is
+ // re-applied on each reload, so a prior companion delivery that set needClientAuth must be reset to
+ // the consumer default here before a later companion (or its absence) is overlaid.
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(true);
+ sslContextFactory.setTrustAll(allowInsecureConnection);
+ }
+ // https://jetty.org/docs/jetty/12.1/operations-guide/protocols/index.html#ssl-sni
+ // Set to false for backwards compatibility with Jetty 9.x
+ sslContextFactory.setSniRequired(false);
+ }
+
+ /**
+ * Ask the factory to supply a native Jetty {@code jettyClass} for {@code purpose} (one-shot). Jetty's
+ * {@link SslContextFactory.Server} and {@link SslContextFactory.Client} are well-known SPI classes, so a
+ * custom factory MAY build one directly; the default {@code FileBasedTlsFactory} returns
+ * {@link Optional#empty()}, in which case the caller synthesizes the factory from an {@code SSLContext}
+ * subscription. A supplied instance is the factory's own (unstarted, same-instance-per-purpose,
+ * factory-driven reload) — the caller returns it verbatim and keeps the {@link TlsHandle} for disposal.
+ * Resolved at factory-build time (off any event loop), mirroring {@link #resolveBaselineParameters}.
+ */
+ private static <T extends SslContextFactory> Optional<TlsHandle<T>> acquireNativeJettyFactory(
+ PulsarTlsFactory factory, TlsPurpose purpose, Class<T> jettyClass) {
+ return factory.createInstance(purpose, jettyClass).join();
+ }
+
+ /**
+ * Request the factory's optional {@code SSLParameters} companion for a purpose (one-shot) at factory-build
+ * time, joining off any event loop, and return the supplied instance or {@link Optional#empty()} when the
+ * factory supplies none. Rotation deliveries do NOT use this: they re-request the companion asynchronously
+ * inside {@link JettyReloadCoordinator} (never joined on the delivery thread) and unwrap it via
+ * {@link #extractBaseline}.
+ */
+ private static Optional<SSLParameters> resolveBaselineParameters(PulsarTlsFactory factory, TlsPurpose purpose) {
+ return Optional.ofNullable(extractBaseline(factory.createInstance(purpose, SSLParameters.class).join()));
+ }
+
+ /**
+ * Unwrap the factory's {@code SSLParameters} companion from its handle, disposing the handle afterwards (a
+ * companion carries no reference-counted state). Returns {@code null} when the factory supplied none
+ * ({@link Optional#empty()}). Used both by the build-time {@link #resolveBaselineParameters} and by the
+ * asynchronous per-rotation re-request in {@link JettyReloadCoordinator}.
+ */
+ private static SSLParameters extractBaseline(Optional<TlsHandle<SSLParameters>> handle) {
+ if (handle.isEmpty()) {
+ return null;
+ }
+ TlsHandle<SSLParameters> paramsHandle = handle.get();
+ try {
+ return paramsHandle.get();
+ } finally {
+ paramsHandle.dispose();
+ }
+ }
+
+ /**
+ * Overlay a factory-supplied engine baseline onto a synthesized server factory (PIP-478 merge order):
+ * enabled protocols/cipher suites when the companion sets them, and the companion's client-auth mode as
+ * authoritative (rule 4) — {@code needClientAuth} wins over {@code wantClientAuth}, neither means none.
+ */
+ private static void applyServerBaseline(SslContextFactory.Server sslContextFactory, SSLParameters baseline) {
+ if (baseline.getProtocols() != null) {
+ sslContextFactory.setIncludeProtocols(baseline.getProtocols());
+ }
+ if (baseline.getCipherSuites() != null) {
+ sslContextFactory.setIncludeCipherSuites(baseline.getCipherSuites());
+ }
+ if (baseline.getNeedClientAuth()) {
+ sslContextFactory.setNeedClientAuth(true);
+ } else if (baseline.getWantClientAuth()) {
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(true);
+ } else {
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(false);
+ }
+ }
+
+ /**
+ * Overlay a factory-supplied engine baseline onto a synthesized client factory: enabled protocols/cipher
+ * suites only (client-auth is a server concept; SNI/hostname verification remain per-connection).
+ */
+ private static void applyClientBaseline(SslContextFactory.Client client, SSLParameters baseline) {
+ if (baseline.getProtocols() != null) {
+ client.setIncludeProtocols(baseline.getProtocols());
+ }
+ if (baseline.getCipherSuites() != null) {
+ client.setIncludeCipherSuites(baseline.getCipherSuites());
+ }
+ }
+
+ /**
+ * Per-subscription reload coordinator for the synthesized Jetty paths. It ports the two ordering guarantees
+ * of {@code TlsContextAcquisition.SynthesizingSubscription} to Jetty's hot-reload API, which the naive
+ * "compose {@code createInstance(SSLParameters)} then {@code reload}" delivery lacked:
+ *
+ * <ul>
+ * <li><b>Generation guard.</b> Each delivery captures a strictly increasing generation (deliveries are
+ * serial per subscription, per the SPI contract). A rotation's companion re-request is composed
+ * asynchronously and may complete on an arbitrary thread and out of order, so its {@code reload(...)}
+ * is applied — under a lock — only while its generation is still the latest; a companion superseded
+ * by a newer rotation is dropped rather than pinning the listener to a stale context/baseline.</li>
+ * <li><b>Last-good baseline retention.</b> The last successfully-resolved companion is retained (seeded
+ * from the build-time baseline). A transient companion-fetch failure during rotation reloads with that
+ * last-good baseline rather than consumer defaults, so it cannot silently drop protocols/ciphers or
+ * (server side) client-auth. The retained baseline is updated only for a successfully-resolved,
+ * non-superseded companion, under the same lock.</li>
+ * </ul>
+ *
+ * <p>The companion is never joined on the delivery thread (the self-deadlock hazard described on the class
+ * javadoc); only the <em>first</em> delivery — which fires synchronously inside the subscribe call, before the
+ * built factory is even returned — sets the already-overlaid context directly, mirroring
+ * {@code SynthesizingSubscription}'s pre-fetched first delivery. Every later delivery is a rotation and
+ * re-requests the companion, <em>including one that arrives before the connector/client starts</em>; whether
+ * the factory is started only decides how the result is applied (Jetty's {@code reload(...)} once started, the
+ * same setters directly before), so a factory started after such a rotation starts with that rotation's
+ * material AND its companion policy rather than the stale build-time baseline.
+ */
+ private static final class JettyReloadCoordinator {
+
+ private final PulsarTlsFactory factory;
+ private final TlsPurpose purpose;
+ private final SslContextFactory target;
+ // Applies the rotated context + (nullable) companion baseline inside Jetty's reload lambda.
+ private final BiConsumer<SSLContext, SSLParameters> applyReload;
+ // Last successfully-resolved companion, seeded from the pre-fetched build-time baseline. Retained across
+ // a transient companion-fetch failure so a rotation cannot silently downgrade engine policy.
+ private volatile SSLParameters lastBaseline;
+ // One-shot: only the first (synchronous, pre-fetched) delivery reuses the build-time baseline; every
+ // later delivery is a rotation and re-requests the companion, started or not.
+ private final AtomicBoolean firstDelivery = new AtomicBoolean(true);
+ private final AtomicLong deliveryGeneration = new AtomicLong();
+ private long lastPublishedGeneration;
+ // A rotation's companion request is composed asynchronously, so its completion can land after the
+ // owner disposed the subscription (and, on the server path, after Jetty stopped the connector).
+ // Reloading a stopped/abandoned factory then would be a pointless mutation at best.
+ private final AtomicBoolean disposed = new AtomicBoolean();
+
+ JettyReloadCoordinator(PulsarTlsFactory factory, TlsPurpose purpose, SslContextFactory target,
+ SSLParameters initialBaseline, BiConsumer<SSLContext, SSLParameters> applyReload) {
+ this.factory = factory;
+ this.purpose = purpose;
+ this.target = target;
+ this.lastBaseline = initialBaseline;
+ this.applyReload = applyReload;
+ }
+
+ /**
+ * Wrap the backing subscription so disposing it also stops this coordinator. Synchronized on the same
+ * monitor as {@link #publish}, so dispose returns only once any in-flight publish has finished —
+ * setting the flag alone would still let a publisher that had already passed the check reload a
+ * factory its owner has torn down.
+ */
+ TlsHandle<SSLContext> bind(TlsHandle<SSLContext> subscription) {
+ return new TlsHandle<>() {
+ @Override
+ public SSLContext get() {
+ return subscription.get();
+ }
+
+ @Override
+ public void dispose() {
+ synchronized (JettyReloadCoordinator.this) {
+ disposed.set(true);
+ }
+ subscription.dispose();
+ }
+ };
+ }
+
+ // Serial per subscription (SPI contract), so each delivery gets a strictly increasing generation.
+ void onDelivery(SSLContext newContext) {
+ long generation = deliveryGeneration.incrementAndGet();
+ if (firstDelivery.compareAndSet(true, false)) {
+ // The first delivery fires synchronously inside the subscribe call, before the built factory is
+ // returned (let alone started): the build-time companion was already overlaid and seeds
+ // lastBaseline, so only the context is missing — set it directly, mirroring
+ // SynthesizingSubscription's pre-fetched first delivery.
+ target.setSslContext(newContext);
+ return;
+ }
+ // Rotation delivery. Re-request the companion so engine policy rotates WITH the material
+ // (pip-478.md:736), resolved ASYNCHRONOUSLY off this delivery thread and never joined here (the
+ // self-deadlock hazard). This runs for rotations delivered BEFORE start too — those must refresh the
+ // companion as well, otherwise the connector would start with the rotated context but the stale
+ // build-time baseline; only the mechanism used to apply the result differs (see publish). The
+ // generation guard in publish drops a superseded companion; the last-good baseline is maintained
+ // there, never here, so a superseded companion completing late cannot regress it.
+ factory.createInstance(purpose, SSLParameters.class).whenComplete((companion, err) ->
+ publish(newContext, err != null ? null : extractBaseline(companion), generation, err == null));
+ }
+
+ // Apply the rotation for `generation`, dropping a result already superseded by a newer delivery.
+ // Synchronized because rotation companions may complete on arbitrary threads and out of order; the guard
+ // keeps the applied context, the reload callback, AND the retained last-good baseline monotonic in
+ // delivery order.
+ private synchronized void publish(SSLContext newContext, SSLParameters baseline, long generation,
+ boolean baselineResolved) {
+ if (generation < lastPublishedGeneration || disposed.get()) {
+ return;
+ }
+ lastPublishedGeneration = generation;
+ if (baselineResolved) {
+ lastBaseline = baseline;
+ } else {
+ // A transient companion-fetch failure must not downgrade engine policy: reload with the last-good
+ // baseline, read under the same guard so a stale companion can never have regressed it.
+ baseline = lastBaseline;
+ }
+ final SSLParameters effectiveBaseline = baseline;
+ try {
+ if (target.isStarted()) {
Review Comment:
Correct — fixed in a4832cd40e1. The silence is what makes it worse than the window suggests: the delivery is counted a successful reload while the listener keeps serving pre-rotation material until the *next* material change. At a 90-day renewal cadence that can outlive the certificate.
Closed by calling `target.reload(...)` unconditionally for rotation deliveries. Jetty's `reload` takes the same internal lock as `doStart`'s `load()`, which is the "same lock Jetty uses" you pointed at, so the check and the apply stop being separable. The existing pre-start rotation test confirms `reload()` on a not-yet-started factory is benign with the pinned Jetty version.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/JettyTlsFactory.java:
##########
@@ -0,0 +1,586 @@
+/*
+ * 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.jetty.tls;
+
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.tls.impl.TlsContexts;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * The framework's Jetty integration for the PIP-478 TLS SPI. Both {@link SslContextFactory.Server} and
+ * {@link SslContextFactory.Client} are well-known SPI classes: the framework first asks the
+ * {@link PulsarTlsFactory} to supply one natively (a custom factory may build and own it, reload
+ * included); only when the factory returns {@code empty()} for the Jetty class does the framework
+ * synthesize a <em>vanilla</em> (never subclassed) one from an {@code SSLContext} subscription. The
+ * default {@code FileBasedTlsFactory} returns {@code empty()} for the Jetty classes, so the synthesized
+ * path is the usual one.
+ *
+ * <p><b>Factory-supplied (native) instances.</b> When the factory supplies the Jetty factory directly it
+ * is handed back <em>unstarted</em> (the connector / {@code HttpClient} starts it), is the factory's
+ * same-instance-per-purpose, and the factory owns its reload on material rotation. The framework only
+ * holds the returned {@link TlsHandle} for disposal and never drives {@code setSslContext}/{@code reload}
+ * or overlays consumer configuration on such an instance.
+ *
+ * <p>This deliberately abandons the unsound {@code getSslContext()} override of the superseded PIP-337
+ * {@code JettySslContextFactory}. Instead it uses
+ * Jetty's documented hot-reload API — the same one {@code KeyStoreScanner} uses: an {@code SSLContext}
+ * subscription drives {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each
+ * later delivery (once started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context and re-selects
+ * protocols/ciphers. Existing connections keep their sessions; new connections use the new context.
+ *
+ * <p><b>{@code SSLParameters} companion (PIP-478).</b> Because these are synthesized paths (the factory
+ * returned {@code empty()} for the Jetty class and supplies only the {@code SSLContext}), the framework also
+ * asks the factory for its optional {@code javax.net.ssl.SSLParameters} companion — the engine-level baseline
+ * a bare {@code SSLContext} cannot express — and maps its non-null members onto the Jetty setters: enabled
+ * protocols ({@link SslContextFactory#setIncludeProtocols}) and cipher suites
+ * ({@link SslContextFactory#setIncludeCipherSuites}), and (server side, merge rule 4) the authoritative
+ * client-auth mode ({@link SslContextFactory.Server#setNeedClientAuth} /
+ * {@link SslContextFactory.Server#setWantClientAuth}). The initial companion is overlaid before start (at build
+ * time); on each subsequent <em>rotation</em> delivery it is re-requested <em>asynchronously</em> — the reload
+ * callback composes {@code createInstance(purpose, SSLParameters.class)} with {@code whenComplete} and only then
+ * calls {@code reload(...)}, so engine policy rotates with material (pip-478.md:736) yet the companion is
+ * <b>never joined on the delivery thread</b>. Joining there would self-deadlock a custom factory that dispatches
+ * companion creation to the same single-thread scheduler that runs the poll delivery — the exact hazard
+ * {@code TlsContextAcquisition.SynthesizingSubscription} avoids by composing the companion asynchronously.
+ *
+ * <p>Because those asynchronous re-requests complete on arbitrary threads and may finish out of order, the
+ * synthesized reload mirrors the two ordering guarantees of {@code SynthesizingSubscription} (see
+ * {@code JettyReloadCoordinator}): each delivery captures a strictly increasing <em>generation</em> and applies
+ * its {@code reload(...)} only while that generation is still the latest, so a companion superseded by a newer
+ * rotation is dropped rather than pinning the listener to a stale context/baseline; and the last
+ * successfully-resolved companion is <em>retained</em> (seeded from the build-time baseline) so a transient
+ * companion-fetch failure during rotation reloads with that last-good baseline rather than downgrading engine
+ * policy (protocols/ciphers and, server side, client-auth) to consumer defaults. Consumer defaults are still
+ * re-applied <em>in full</em> first inside every {@code reload(...)} lambda — protocols, cipher suites and, server
+ * side, client-auth are each re-pinned or cleared unconditionally, since the long-lived {@code SslContextFactory}
+ * persists setter state across {@code reload()} — so any companion member legitimately dropped by a newer delivery
+ * reverts to the consumer default rather than staying stuck from the previous companion.
+ * {@code empty()} leaves the consumer's configuration in force, exactly as before.
+ */
+@CustomLog
+public final class JettyTlsFactory {
+
+ static {
+ // DO NOT EDIT - Load Conscrypt provider
+ if (JcaProviders.CONSCRYPT_PROVIDER != null) {
+ }
+ }
+
+ private JettyTlsFactory() {
+ }
+
+ /**
+ * A Jetty server factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the web service stops.
+ *
+ * @param sslContextFactory the (unstarted) Jetty server factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableServerTls(SslContextFactory.Server sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * A Jetty client factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the owning HTTP client
+ * / servlet is destroyed.
+ *
+ * @param sslContextFactory the (unstarted) Jetty client factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableClientTls(SslContextFactory.Client sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * Build a self-reloading {@link SslContextFactory.Server} for a purpose, handed back <em>unstarted</em>
+ * (Jetty starts it with the connector lifecycle) with its initial {@code SSLContext} already set.
+ *
+ * @param factory the TLS factory to subscribe to
+ * @param purpose the server purpose (e.g. {@link TlsPurpose#WEB})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param requireTrustedClientCert whether to require (vs. request) a trusted client certificate
+ * @param allowInsecureConnection whether an untrusted client cert is accepted under optional client auth
+ * @param ciphers enabled cipher suites, or {@code null} for defaults
+ * @param protocols enabled protocols, or {@code null} for defaults
+ * @return the reloading factory and its subscription handle
+ */
+ public static ReloadableServerTls createReloadingServerFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString,
+ boolean requireTrustedClientCert,
+ boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ // Ask the factory first: a custom factory may natively supply the Jetty server factory (a
+ // well-known class). When it does, hand it back unstarted with the factory owning its reload and
+ // configuration; the framework overlays no consumer config on it. The default file-based factory
+ // returns empty() here, so the synthesized, self-reloading fallback below runs (the usual path).
+ Optional<TlsHandle<SslContextFactory.Server>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Server.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Server> handle = nativeFactory.get();
+ return new ReloadableServerTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
+ // Consumer config plus the factory's engine-policy companion (if any), before start. The resolved
+ // companion seeds the coordinator's last-good baseline so a companion-fetch failure on the very first
+ // rotation retains it rather than downgrading to consumer defaults.
+ SSLParameters initialBaseline = configureServerBaseline(sslContextFactory, factory, purpose,
+ sslProviderString, requireTrustedClientCert, allowInsecureConnection, ciphers, protocols);
+
+ // Each rotation re-requests the companion asynchronously (off the delivery thread) and applies it under
+ // a generation guard so an out-of-order companion cannot pin a stale context, retaining the last-good
+ // baseline across a transient companion failure. See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, sslContextFactory,
+ initialBaseline, (newContext, baseline) -> {
+ sslContextFactory.setSslContext(newContext);
+ // Re-apply the consumer defaults first so a companion member dropped by this delivery
+ // (notably client-auth) reverts to the consumer default rather than staying stuck from the
+ // previous companion, then overlay the generation-guarded, last-good companion.
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert,
+ allowInsecureConnection, ciphers, protocols);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery)
+ .join()
Review Comment:
Both correct — fixed in a4832cd40e1.
The deadlock shape is real: the default factory dispatches supported acquisitions to `initContext.blockingExecutor()`, so a builder called from that executor waits on work queued behind itself — and the websocket proxy and functions worker are exactly the components with the dedicated `initContext` overload. The constraint is now stated on both public builders rather than left as convention.
The joins are also centralized so `CompletionException` is unwrapped: a misconfigured purpose now surfaces as "No TLS material configured for server purpose WEB" rather than wrapped.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [feat][misc] PIP-478: default file-based TLS factory implementation [pulsar]
Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #26271:
URL: https://github.com/apache/pulsar/pull/26271#discussion_r3719670593
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/TlsMaterial.java:
##########
@@ -0,0 +1,108 @@
+/*
+ * 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.common.tls.impl;
+
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+import java.util.List;
+
+/**
+ * The loaded TLS material for one {@code TlsPurpose}: the private key, its certificate chain, and the
+ * trust certificates (PIP-478, internal to the default {@code FileBasedTlsFactory}).
+ *
+ * <p>This is a value type with structural {@code equals}/{@code hashCode} (a record). The default
+ * factory uses value equality to detect real rotations: a {@code TlsMaterialSource} that re-reads its
+ * files but finds identical content produces an {@code equal} instance, which suppresses spurious
+ * context rebuilds and reload callbacks (a file touched without content change fires nothing).
+ *
+ * <p>Role-neutral: the policy flags (insecure, hostname verification, client-auth requirement) and the
+ * protocols/ciphers are fixed at construction and live on the owning {@code TlsPolicy}/factory
+ * settings, not here — only the crypto material rotates.
+ *
+ * <p><b>Multi-identity keystores.</b> PEM material describes exactly one identity, carried in
+ * {@link #privateKey()}/{@link #keyCertChain()}. A keystore may hold several key entries (e.g. an RSA and
+ * an EC identity, or client identities issued by different accepted CAs); those are carried in full in
+ * {@link #keyEntries()} so the context builders can hand the <em>whole</em> set to a
+ * {@code KeyManagerFactory} and let JSSE select an alias by the peer's requested key type / acceptable
+ * issuers. For keystore material {@code privateKey}/{@code keyCertChain} mirror the first entry (so
+ * {@link #hasKeyMaterial()} and the value-equality rotation check remain meaningful), but the builders
+ * prefer {@code keyEntries} whenever it is non-empty.
+ *
+ * @param privateKey the private key (client key for mTLS, server key on the server side), or
+ * {@code null} when none is configured
+ * @param keyCertChain the certificate chain matching {@link #privateKey()} (never {@code null})
+ * @param trustCerts the trusted CA certificates, or empty to use the platform default trust store
+ * @param keyEntries every key entry of a keystore identity (empty for PEM/single-identity material)
+ */
+record TlsMaterial(PrivateKey privateKey, List<X509Certificate> keyCertChain, List<X509Certificate> trustCerts,
Review Comment:
Fair — it is an implicit contract on a provider-supplied object, on the one axis whose point is that the provider is swappable. Test added in a9e50fe6e1d.
It asserts against `BC` rather than `BCFIPS`: the two cannot share a classpath (mismatched jar signers), which is what the separate bcfips test module exists for. They share the encoding-equality implementation, so the property under test is the same.
Two bounds for the record: for the file-backed source the file-stamp baseline short-circuits before equality is consulted, so identity-equals keys would only bite on a touch-without-content change; and the failure mode is rebuild churn plus a misleading `pulsar.tls.reload` count, not incorrect TLS.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/TlsMaterialSource.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.common.tls.impl;
+
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.attribute.FileTime;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.PrivateKey;
+import java.security.Provider;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.common.util.tls.PemReader;
+import org.apache.pulsar.tls.TlsPolicy;
+
+/**
+ * Loads, watches and caches ONE material set (the crypto for a single {@code TlsPurpose}) from a
+ * {@link TlsPolicy} for the default {@code FileBasedTlsFactory} (PIP-478).
+ *
+ * <p>This collapses the old branch's {@code FileBasedClient/ServerTlsMaterialSource} split into a
+ * single, role-neutral class: the difference was only the value builder and a few flags, while the
+ * watch/cache machinery was duplicated verbatim.
+ *
+ * <p><b>Keystore-over-PEM per-field precedence.</b> For each of the three material slots (trust
+ * certs, private key, key certificate chain) the keystore location wins when set, otherwise the PEM
+ * location is used. PEM material is loaded via {@link PemReader}; keystores (PKCS12/JKS) are read
+ * with the raw {@link KeyStore} API and an alias walk.
+ *
+ * <p><b>Rotation detection (fixed mtime baseline).</b> Change detection snapshots the modification
+ * times of every configured file, and — unlike the old {@code FileModifiedTimeUpdater}-based scheme,
+ * which advanced the baseline <em>before</em> the load and so never retried a failed rotation until the
+ * next mtime change — commits the new baseline <strong>only after a successful load</strong>. A load
+ * that throws (a half-written or invalid rotated file, the canonical incident) leaves both the baseline
+ * and the last-good material untouched, so the next poll observes the same change again and retries.
+ * When mtimes advanced but the loaded material is byte-for-byte {@link TlsMaterial#equals(Object)
+ * equal} to the cached one (a file touched without content change), the baseline is committed but no
+ * change is signalled.
+ *
+ * <p><b>Fail-closed trust and identity.</b> A configured keystore truststore that holds zero certificates
+ * is rejected rather than loaded as an empty trust list: downstream, an empty trust list is
+ * indistinguishable from "no truststore configured" and both context builders then install the platform
+ * default trust manager, silently trusting every public CA. v4's {@code KeyStoreSSLContext} initialised the
+ * {@code TrustManagerFactory} with the explicit store and rejected every peer. The same applies to the
+ * identity axis: a keystore with no usable key entry, or a PEM certificate without its private key, fails
+ * the load instead of degrading to "no identity presented", which would surface only as a much later
+ * handshake failure. The PEM trust axis is deliberately NOT hardened (v4 fell back to the platform trust
+ * store for an empty trust file and deployments rely on that), and a PEM key without a certificate is a
+ * WARN, not a failure, for the same v4-parity reason.
+ *
+ * <p>Not thread-safe on its own; the owning factory serialises access under its per-source monitor.
+ */
+@CustomLog
+final class TlsMaterialSource implements MaterialSource {
+
+ /** Sentinel modification time recorded for a path that is currently missing or unreadable. */
+ private static final FileTime MISSING = FileTime.fromMillis(Long.MIN_VALUE);
+
+ private final TlsPolicy policy;
+ private final List<String> watchedPaths;
+ // Resolved once: the policy's jcaProvider (KeyStore/CertificateFactory/KeyFactory axis), or null when the
+ // policy pins none (the JVM provider search order). Resolving here keeps the ServiceLoader walk off the
+ // per-load path and fails loudly at factory init for an unresolvable name.
+ private final Provider jcaProvider;
+
+ private Map<String, FileTime> baseline;
+ private TlsMaterial cached;
+
+ TlsMaterialSource(TlsPolicy policy) {
+ this.policy = Objects.requireNonNull(policy, "policy must not be null");
+ this.watchedPaths = watchedPathsFor(policy);
+ this.jcaProvider = JcaProviders.resolveNamedProvider(policy.jcaProvider());
+ }
+
+ TlsPolicy policy() {
+ return policy;
+ }
+
+ /**
+ * @return the resolved JCA (material) provider, or {@code null} when the policy pins none. Package-private
+ * so the {@code BROKER_CLIENT} auth overlay parses its material through the same provider.
+ */
+ Provider jcaProvider() {
+ return jcaProvider;
+ }
+
+ /**
+ * Re-stat the configured files, reloading the material when they changed since the last successful
+ * load. Returns the current (possibly rebuilt) material together with whether it changed in value.
+ *
+ * @return the refresh outcome
+ * @throws Exception if the material could not be loaded (the last-good material and baseline are
+ * left untouched so the next call retries)
+ */
+ @Override
+ public MaterialSource.RefreshOutcome refresh() throws Exception {
+ Map<String, FileTime> snapshot = snapshotModificationTimes();
+ if (cached != null && snapshot.equals(baseline)) {
+ return new MaterialSource.RefreshOutcome(cached, false);
+ }
+ TlsMaterial loaded = load();
+ boolean changed = cached == null || !loaded.equals(cached);
+ // Commit the baseline only after a successful load (keep-last-good + retry-on-next-change).
+ baseline = snapshot;
+ if (changed) {
+ cached = loaded;
+ }
+ return new MaterialSource.RefreshOutcome(cached, changed);
+ }
+
+ private TlsMaterial load() throws Exception {
+ List<X509Certificate> trustCerts = loadTrustCerts();
+ // Keystore identity: load the whole store and carry every key entry, so a multi-identity keystore
+ // (e.g. RSA + EC) preserves JSSE alias selection at context build. The single privateKey/keyCertChain
+ // mirror the first entry, keeping hasKeyMaterial() and the value-equality rotation check meaningful.
+ if (StringUtils.isNotBlank(policy.keyStorePath())) {
+ KeyStore keyStore = TlsKeyStoreLoader.loadKeyStore(policy.keyStoreType(), policy.keyStorePath(),
+ policy.keyStorePassword(), jcaProvider);
+ List<TlsMaterial.KeyEntry> entries =
+ TlsKeyStoreLoader.extractKeyEntries(keyStore, policy.keyStorePassword());
+ validateKeyStoreIdentity(entries);
+ TlsMaterial.KeyEntry first = entries.get(0);
+ return new TlsMaterial(first.privateKey(), first.chain(), trustCerts, entries);
+ }
+ validatePemIdentity();
+ return new TlsMaterial(loadPemPrivateKey(), loadPemCertificateChain(), trustCerts);
+ }
+
+ /**
+ * Reject a keystore that holds no usable key entry. v4 handed such a store to
+ * {@code KeyManagerFactory.init}, which initialised fine but produced a key manager with no aliases — a
+ * certain, undiagnosed handshake failure for a server and a silently identity-less client. Failing the
+ * load is a deliberate tightening: the only deployments it can break already presented no identity.
+ *
+ * @param entries the key entries extracted from the configured keystore
+ * @throws KeyStoreException if the keystore carries no usable key entry
+ */
+ private void validateKeyStoreIdentity(List<TlsMaterial.KeyEntry> entries) throws KeyStoreException {
+ if (entries.isEmpty()) {
+ throw new KeyStoreException("Configured keystore '" + policy.keyStorePath()
+ + "' holds no usable key entry (a private key with an X.509 certificate chain); no TLS "
+ + "identity would be presented. Fix the keystore or its password, or unset keyStorePath.");
+ }
+ }
+
+ /**
+ * Reject a half-configured PEM identity that would be silently dropped. A certificate without its key
+ * yields {@link TlsMaterial#hasKeyMaterial()} {@code == false}, so the identity is omitted from the built
+ * context and the misconfiguration only surfaces as a handshake/authentication failure much later. The
+ * check is deliberately <em>asymmetric</em>: a key without a certificate is what v4 silently tolerated, so
+ * it stays a WARN rather than a new startup failure. Enforced here rather than in {@code TlsPolicy.Builder}
+ * so custom {@code PulsarTlsFactory} implementations that build their own policies are not constrained by
+ * this default factory's requirement.
+ */
+ private void validatePemIdentity() {
+ boolean hasCert = StringUtils.isNotBlank(policy.certificateFilePath());
+ boolean hasKey = StringUtils.isNotBlank(policy.keyFilePath());
+ if (hasCert && !hasKey) {
+ throw new IllegalArgumentException("TlsPolicy sets certificateFilePath='" + policy.certificateFilePath()
+ + "' but leaves keyFilePath unset; a certificate without its private key yields no usable TLS "
+ + "identity. Set keyFilePath, or unset certificateFilePath.");
+ }
+ if (hasKey && !hasCert) {
+ log.warn().attr("keyFilePath", policy.keyFilePath())
+ .log("TlsPolicy sets keyFilePath but no certificateFilePath; no TLS identity will be presented");
+ }
+ }
+
+ private List<X509Certificate> loadTrustCerts() throws Exception {
+ if (StringUtils.isNotBlank(policy.trustStorePath())) {
+ List<X509Certificate> trustCerts = TlsKeyStoreLoader.extractTrustCerts(
+ TlsKeyStoreLoader.loadKeyStore(policy.trustStoreType(), policy.trustStorePath(),
+ policy.trustStorePassword(), jcaProvider));
+ if (trustCerts.isEmpty()) {
+ // An empty trust list is indistinguishable from "no truststore configured" downstream, and both
+ // context builders then install the platform default trust manager — silently trusting every
+ // public CA. v4 initialised the TrustManagerFactory with the explicit store and rejected every peer.
+ throw new KeyStoreException("Configured truststore '" + policy.trustStorePath()
Review Comment:
Agreed, and thanks for enumerating them — these are startup failures on upgrade and nobody should meet them first as a stack trace. All three are now in the PIP's upgrade section (9d3ea3c2c99), so the text exists before the migration PR needs it, including why the empty-truststore case is the security-relevant one and that the PEM trust axis is deliberately left untightened for 4.x parity.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/TlsMaterialSource.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.common.tls.impl;
+
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.attribute.FileTime;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.PrivateKey;
+import java.security.Provider;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.common.util.tls.PemReader;
+import org.apache.pulsar.tls.TlsPolicy;
+
+/**
+ * Loads, watches and caches ONE material set (the crypto for a single {@code TlsPurpose}) from a
+ * {@link TlsPolicy} for the default {@code FileBasedTlsFactory} (PIP-478).
+ *
+ * <p>This collapses the old branch's {@code FileBasedClient/ServerTlsMaterialSource} split into a
+ * single, role-neutral class: the difference was only the value builder and a few flags, while the
+ * watch/cache machinery was duplicated verbatim.
+ *
+ * <p><b>Keystore-over-PEM per-field precedence.</b> For each of the three material slots (trust
+ * certs, private key, key certificate chain) the keystore location wins when set, otherwise the PEM
+ * location is used. PEM material is loaded via {@link PemReader}; keystores (PKCS12/JKS) are read
+ * with the raw {@link KeyStore} API and an alias walk.
+ *
+ * <p><b>Rotation detection (fixed mtime baseline).</b> Change detection snapshots the modification
+ * times of every configured file, and — unlike the old {@code FileModifiedTimeUpdater}-based scheme,
+ * which advanced the baseline <em>before</em> the load and so never retried a failed rotation until the
+ * next mtime change — commits the new baseline <strong>only after a successful load</strong>. A load
+ * that throws (a half-written or invalid rotated file, the canonical incident) leaves both the baseline
+ * and the last-good material untouched, so the next poll observes the same change again and retries.
+ * When mtimes advanced but the loaded material is byte-for-byte {@link TlsMaterial#equals(Object)
+ * equal} to the cached one (a file touched without content change), the baseline is committed but no
+ * change is signalled.
+ *
+ * <p><b>Fail-closed trust and identity.</b> A configured keystore truststore that holds zero certificates
+ * is rejected rather than loaded as an empty trust list: downstream, an empty trust list is
+ * indistinguishable from "no truststore configured" and both context builders then install the platform
+ * default trust manager, silently trusting every public CA. v4's {@code KeyStoreSSLContext} initialised the
+ * {@code TrustManagerFactory} with the explicit store and rejected every peer. The same applies to the
+ * identity axis: a keystore with no usable key entry, or a PEM certificate without its private key, fails
+ * the load instead of degrading to "no identity presented", which would surface only as a much later
+ * handshake failure. The PEM trust axis is deliberately NOT hardened (v4 fell back to the platform trust
+ * store for an empty trust file and deployments rely on that), and a PEM key without a certificate is a
+ * WARN, not a failure, for the same v4-parity reason.
+ *
+ * <p>Not thread-safe on its own; the owning factory serialises access under its per-source monitor.
+ */
+@CustomLog
+final class TlsMaterialSource implements MaterialSource {
+
+ /** Sentinel modification time recorded for a path that is currently missing or unreadable. */
+ private static final FileTime MISSING = FileTime.fromMillis(Long.MIN_VALUE);
+
+ private final TlsPolicy policy;
+ private final List<String> watchedPaths;
+ // Resolved once: the policy's jcaProvider (KeyStore/CertificateFactory/KeyFactory axis), or null when the
+ // policy pins none (the JVM provider search order). Resolving here keeps the ServiceLoader walk off the
+ // per-load path and fails loudly at factory init for an unresolvable name.
+ private final Provider jcaProvider;
+
+ private Map<String, FileTime> baseline;
+ private TlsMaterial cached;
+
+ TlsMaterialSource(TlsPolicy policy) {
+ this.policy = Objects.requireNonNull(policy, "policy must not be null");
+ this.watchedPaths = watchedPathsFor(policy);
+ this.jcaProvider = JcaProviders.resolveNamedProvider(policy.jcaProvider());
+ }
+
+ TlsPolicy policy() {
+ return policy;
+ }
+
+ /**
+ * @return the resolved JCA (material) provider, or {@code null} when the policy pins none. Package-private
+ * so the {@code BROKER_CLIENT} auth overlay parses its material through the same provider.
+ */
+ Provider jcaProvider() {
+ return jcaProvider;
+ }
+
+ /**
+ * Re-stat the configured files, reloading the material when they changed since the last successful
+ * load. Returns the current (possibly rebuilt) material together with whether it changed in value.
+ *
+ * @return the refresh outcome
+ * @throws Exception if the material could not be loaded (the last-good material and baseline are
+ * left untouched so the next call retries)
+ */
+ @Override
+ public MaterialSource.RefreshOutcome refresh() throws Exception {
+ Map<String, FileTime> snapshot = snapshotModificationTimes();
Review Comment:
Taken in 065b304623c, and extended. `Files.readAttributes(BasicFileAttributes.class)` returns mtime, size and `fileKey` in the same single stat, so the snapshot now carries all three: size catches a different-length replacement, and `fileKey` (the inode) catches write-to-temp-and-rename — which is how most certificate tooling rotates, and which same-length rotations would otherwise defeat, since size alone would miss a renewed certificate with the same key size. A null `fileKey` is part of the snapshot value, so filesystems that supply none degrade to mtime-plus-size.
Two keep-last-good tests had to change, and the reason is the point of the fix: both faked "nothing changed" by restoring only the mtime of a file whose contents they had replaced. The new snapshot sees through that. They now restore the content as well.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/TlsContexts.java:
##########
@@ -0,0 +1,494 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.ApplicationProtocolConfig;
+import io.netty.handler.ssl.ClientAuth;
+import io.netty.handler.ssl.IdentityCipherSuiteFilter;
+import io.netty.handler.ssl.JdkSslContext;
+import io.netty.handler.ssl.SslContext;
+import io.netty.handler.ssl.SslContextBuilder;
+import io.netty.handler.ssl.SslProvider;
+import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
+import java.security.GeneralSecurityException;
+import java.security.KeyStoreException;
+import java.security.Provider;
+import java.util.Arrays;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import lombok.CustomLog;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.common.util.tls.JdkSslContexts;
+import org.apache.pulsar.tls.TlsPolicy;
+
+/**
+ * Builds the well-known TLS instance classes from loaded {@link TlsMaterial} and a {@link TlsPolicy}
+ * for the default {@code FileBasedTlsFactory}, and synthesizes the richer objects from a JDK
+ * {@code SSLContext} for the framework fallback (PIP-478).
+ *
+ * <p>This class owns TLS context assembly end-to-end, composing the focused low-level primitives rather
+ * than a general-purpose helper: it consumes already-parsed in-memory {@link TlsMaterial} (PEM and keystore
+ * parsing lives in the material sources), builds the JDK {@code SSLContext} through {@link JdkSslContexts},
+ * and assembles the Netty {@link SslContext} objects inline through {@link SslContextBuilder}. The Netty
+ * contexts are built here rather than delegated because two per-context settings must be baked at build time
+ * from the in-memory material:
+ * <ul>
+ * <li><b>Client hostname verification</b> — set via
+ * {@link SslContextBuilder#endpointIdentificationAlgorithm(String)} to {@code "HTTPS"} when the
+ * policy enables it. It cannot be left to a per-{@code SSLEngine} override: Netty's OpenSSL
+ * backend fixes the endpoint-identification algorithm at build time.</li>
+ * <li><b>Server insecure trust</b> — {@code policy.allowInsecureConnection()} on a
+ * server context installs {@link InsecureTrustManagerFactory#INSTANCE} so an untrusted client
+ * certificate still completes the handshake and remains available for TLS authentication, while
+ * client-auth stays {@link ClientAuth#REQUIRE}/{@link ClientAuth#OPTIONAL} (never
+ * {@link ClientAuth#NONE}, per {@code tlsRequireTrustedClientCert} semantics).</li>
+ * </ul>
+ */
+@CustomLog
+public final class TlsContexts {
+
+ /**
+ * The default enabled TLS protocol set, applied whenever the effective protocol list is empty — a policy
+ * with no {@code protocols()}, or a synthesized context whose factory companion set none. This preserves
+ * the {@code {TLSv1.3, TLSv1.2}} floor {@code DefaultPulsarSslFactory} forces at engine build:
+ * without it the PIP-478 path would silently defer to the JVM/provider default protocol set, a
+ * security-relevant drift on upgrade.
+ */
+ public static final List<String> DEFAULT_ENABLED_PROTOCOLS = List.of("TLSv1.3", "TLSv1.2");
+
+ // WARN-once dedup for the insecure (trust-all) mode, keyed by policy value so a rotation's context rebuilds
+ // (and both the Netty and JDK builds of the same policy) log at most once.
+ private static final Set<TlsPolicy> INSECURE_WARNED = ConcurrentHashMap.newKeySet();
Review Comment:
Correct — fixed in 03443372293. The password retention is the part that matters more than the unboundedness: only insecure-mode policies enter, so a fixed-config broker adds one or two entries, but pinning a `TlsPolicy` pins its keystore and truststore passwords for the process lifetime.
Now keyed by `policy.hashCode()` and capped. Past the cap it warns every time rather than going quiet — losing the signal that peer verification is off would be worse than a repeated warning. A collision costs at most one suppressed warning.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/util/tls/JcaProviders.java:
##########
@@ -0,0 +1,474 @@
+/*
+ * 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.common.util.tls;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.security.NoSuchAlgorithmException;
+import java.security.Provider;
+import java.security.Security;
+import java.util.Iterator;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.ServiceConfigurationError;
+import java.util.ServiceLoader;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+
+/**
+ * Resolves the JCA/JCE security providers Pulsar relies on: a named provider for the PIP-478
+ * {@code jsseProvider} / {@code jcaProvider} axes, the Bouncy Castle provider (FIPS or non-FIPS), and the
+ * optional Conscrypt (OpenSSL) provider. This is the single provider-resolution primitive extracted from the
+ * {@code SecurityUtility} grab-bag (PIP-478).
+ *
+ * <p><b>Bouncy Castle is resolved lazily and is optional.</b> Loading this class must not require it: the
+ * class exists mainly to resolve <em>named</em> providers for the two TLS provider axes, which every TLS
+ * policy does, whereas Bouncy Castle is needed only by the code that actually asks for it (message
+ * encryption, and a deployment that pins {@code jcaProvider=BC}/{@code BCFIPS}). The provider is therefore
+ * looked up on first use through {@link #bouncyCastleProvider()} — which reports absence as
+ * {@link Optional#empty()} rather than failing — and only a caller that genuinely needs it, via
+ * {@link #requireBouncyCastleProvider()}, turns absence into an error. Resolving it does install it
+ * process-wide via {@code Security.addProvider}, as before.
+ *
+ * <p>Conscrypt, by contrast, is resolved during class initialization ({@link #CONSCRYPT_PROVIDER}) and
+ * installed process-wide when present; it reports absence as {@code null} and never fails class loading.
+ */
+@CustomLog
+public final class JcaProviders {
+
+ public static final String BC_FIPS_PROVIDER_CLASS = "org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider";
+ public static final String BC_NON_FIPS_PROVIDER_CLASS = "org.bouncycastle.jce.provider.BouncyCastleProvider";
+ public static final String BC_JSSE_PROVIDER_CLASS = "org.bouncycastle.jsse.provider.BouncyCastleJsseProvider";
+ public static final String CONSCRYPT_PROVIDER_CLASS = "org.conscrypt.OpenSSLProvider";
+ public static final Provider CONSCRYPT_PROVIDER = loadConscryptProvider();
+
+ // Security.getProvider("BC") / Security.getProvider("BCFIPS").
+ // also used to get Factories. e.g. CertificateFactory.getInstance("X.509", "BCFIPS")
+ public static final String BC_FIPS = "BCFIPS";
+ public static final String BC = "BC";
+
+ /**
+ * The name BouncyCastle's JSSE provider registers under — the same in FIPS and non-FIPS mode, because
+ * the mode is a constructor argument rather than part of the provider identity.
+ */
+ public static final String BC_JSSE = "BCJSSE";
+
+ private JcaProviders() {
+ }
+
+ /**
+ * A resolved Bouncy Castle provider together with which of the two artifacts it came from. The flavour
+ * travels with the provider because callers that care (FIPS-approved-only algorithm choices) would
+ * otherwise have to re-derive it from the provider's class name, and because the answer is fixed once
+ * the provider is resolved.
+ *
+ * @param provider the resolved, process-wide registered provider
+ * @param fips whether it is the FIPS-certified artifact ({@code bc-fips}, registered as
+ * {@code BCFIPS}) rather than the general-purpose one ({@code bcprov}, registered as
+ * {@code BC})
+ */
+ public record ResolvedBouncyCastleProvider(Provider provider, boolean fips) {
+ public ResolvedBouncyCastleProvider {
+ Objects.requireNonNull(provider, "provider must not be null");
+ }
+ }
+
+ /**
+ * Lazily resolves Bouncy Castle on first access, so that merely loading {@link JcaProviders} — which
+ * every named-provider resolution does — never requires Bouncy Castle to be on the classpath.
+ */
+ private static final class BouncyCastleHolder {
+ private static final ResolvedBouncyCastleProvider RESOLVED = loadBouncyCastleProvider();
+ }
+
+ /**
+ * The Bouncy Castle provider, installed process-wide on first resolution:
+ * <ol>
+ * <li>an already-registered {@code BC} or {@code BCFIPS} provider, if any;</li>
+ * <li>otherwise loaded from the classpath (non-FIPS preferred, FIPS as fallback) and registered via
+ * {@code Security.addProvider}.</li>
+ * </ol>
+ *
+ * @return the resolved provider and its flavour, or {@link Optional#empty()} when Bouncy Castle is not
+ * available. Callers that cannot proceed without it should use
+ * {@link #requireBouncyCastleProvider()}, so the failure names them rather than surfacing as a
+ * class-initialization error somewhere unrelated.
+ */
+ public static Optional<ResolvedBouncyCastleProvider> bouncyCastleProvider() {
+ return Optional.ofNullable(BouncyCastleHolder.RESOLVED);
+ }
+
+ /**
+ * As {@link #bouncyCastleProvider()}, for callers whose functionality genuinely requires Bouncy Castle.
+ *
+ * @return the resolved provider and its flavour
+ * @throws IllegalStateException when Bouncy Castle is not on the classpath
+ */
+ public static ResolvedBouncyCastleProvider requireBouncyCastleProvider() {
+ return bouncyCastleProvider().orElseThrow(() -> new IllegalStateException(
+ "No Bouncy Castle provider is available: neither an already-registered " + BC + "/" + BC_FIPS
+ + " provider nor " + BC_NON_FIPS_PROVIDER_CLASS + " / " + BC_FIPS_PROVIDER_CLASS
+ + " on the classpath. Add the bcprov (or bc-fips) dependency to use this feature."));
+ }
+
+ private static ResolvedBouncyCastleProvider loadBouncyCastleProvider() {
+ Provider installed = Security.getProvider(BC);
+ if (installed == null) {
+ installed = Security.getProvider(BC_FIPS);
+ }
+ if (installed != null) {
+ log.debug().attr("provider", installed.getName()).log("Already instantiated Bouncy Castle provider");
+ return toResolvedProvider(installed);
+ }
+ // Not installed, try to load from the classpath. Absence is not an error here — it is only an error
+ // for a caller that needs Bouncy Castle, which requireBouncyCastleProvider() reports.
+ try {
+ return toResolvedProvider(getBCProviderFromClassPath());
+ } catch (Exception e) {
+ log.debug().exception(e)
+ .log("No Bouncy Castle provider (FIPS or non-FIPS) on the classpath");
+ return null;
+ }
+ }
+
+ /**
+ * Lazily resolves BouncyCastle's JSSE provider on first access, registering it from the classpath when
+ * the operator has not installed it themselves.
+ */
+ private static final class BouncyCastleJsseHolder {
+ private static final ResolvedBouncyCastleProvider RESOLVED = loadBouncyCastleJsseProvider();
+ }
+
+ /**
+ * BouncyCastle's JSSE provider ({@value #BC_JSSE}), the provider a FIPS TLS deployment pins as
+ * {@code jsseProvider}.
+ *
+ * <p>Unlike every other provider this class resolves, {@value #BC_JSSE} cannot be discovered: {@code bctls}
+ * ships no {@code META-INF/services/java.security.Provider} entry, so an unregistered one is invisible to
+ * {@link ServiceLoader}. And it cannot simply be default-constructed either, because its FIPS mode is a
+ * constructor argument fixed at construction — the provider registers under the same name either way, so
+ * a no-arg instance would quietly be the non-FIPS one. This resolves it explicitly instead:
+ *
+ * <ol>
+ * <li>an instance the operator already registered wins, whatever mode they built it in;</li>
+ * <li>otherwise, when {@code bctls} is on the classpath, it is constructed and registered here — in
+ * FIPS mode bound to the FIPS JCA provider when {@link #bouncyCastleProvider()} resolved that one,
+ * and in the default mode otherwise, so the TLS stack follows whichever BouncyCastle artifact the
+ * deployment actually ships;</li>
+ * <li>otherwise it is absent, and pinning {@code jsseProvider=BCJSSE} fails loudly.</li>
+ * </ol>
+ *
+ * @return the resolved provider and whether it is in FIPS mode, or {@link Optional#empty()} when
+ * {@code bctls} is not on the classpath
+ */
+ public static Optional<ResolvedBouncyCastleProvider> bouncyCastleJsseProvider() {
+ return Optional.ofNullable(BouncyCastleJsseHolder.RESOLVED);
+ }
+
+ private static ResolvedBouncyCastleProvider loadBouncyCastleJsseProvider() {
+ Provider registered = Security.getProvider(BC_JSSE);
+ if (registered != null) {
+ log.debug().attr("provider", BC_JSSE).log("Already instantiated BouncyCastle JSSE provider");
+ return new ResolvedBouncyCastleProvider(registered, isJsseFipsMode(registered));
+ }
+ Class<?> providerClass;
+ try {
+ providerClass = Class.forName(BC_JSSE_PROVIDER_CLASS);
+ } catch (ClassNotFoundException e) {
+ log.debug().attr("class", BC_JSSE_PROVIDER_CLASS)
+ .log("No BouncyCastle JSSE provider on the classpath");
+ return null;
+ }
+ // Resolving the JCA provider first also installs it, which the FIPS configuration below needs: the
+ // JSSE provider looks its crypto provider up by name while constructing.
+ String config = jsseProviderConfig(bouncyCastleProvider().orElse(null));
+ try {
+ Provider provider = config == null
+ ? (Provider) providerClass.getDeclaredConstructor().newInstance()
+ : (Provider) providerClass.getDeclaredConstructor(String.class).newInstance(config);
+ Security.addProvider(provider);
+ boolean fips = isJsseFipsMode(provider);
+ log.info().attr("provider", provider.getName()).attr("fips", fips)
+ .log("Registered the BouncyCastle JSSE provider");
+ return new ResolvedBouncyCastleProvider(provider, fips);
+ } catch (ReflectiveOperationException | RuntimeException e) {
+ log.warn().attr("class", BC_JSSE_PROVIDER_CLASS).attr("config", config).exception(e)
+ .log("Failed to register the BouncyCastle JSSE provider");
+ return null;
+ }
+ }
+
+ /**
+ * The constructor argument for a self-registered {@value #BC_JSSE}: {@code "fips:<name>"} binds it to a
+ * FIPS JCA provider and turns FIPS mode on, while {@code null} selects the no-arg (default, non-FIPS)
+ * constructor. FIPS mode is chosen only when the resolved BouncyCastle JCA provider is itself the FIPS
+ * artifact — pairing a FIPS JSSE provider with a non-validated crypto provider would be FIPS-shaped
+ * rather than FIPS-compliant, which is exactly what the two provider axes exist to prevent.
+ *
+ * @param jcaProvider the resolved BouncyCastle JCA provider, or {@code null} when there is none
+ * @return the constructor argument, or {@code null} to use the no-arg constructor
+ */
+ @VisibleForTesting
+ static String jsseProviderConfig(ResolvedBouncyCastleProvider jcaProvider) {
+ if (jcaProvider == null || !jcaProvider.fips()) {
+ return null;
+ }
+ return "fips:" + jcaProvider.provider().getName();
+ }
+
+ /** Query a JSSE provider's FIPS mode reflectively, so this class never needs {@code bctls} to compile. */
+ private static boolean isJsseFipsMode(Provider provider) {
+ try {
+ return Boolean.TRUE.equals(provider.getClass().getMethod("isFipsMode").invoke(provider));
+ } catch (ReflectiveOperationException | RuntimeException e) {
+ log.debug().attr("provider", provider.getName()).exception(e)
+ .log("Provider exposes no isFipsMode(); assuming non-FIPS");
+ return false;
+ }
+ }
+
+ /**
+ * Classify a resolved provider. Both the registered name and the implementation class are checked: the
+ * FIPS artifact registers as {@code BCFIPS}, and matching the class as well keeps the classification
+ * right for a provider registered under a non-standard name.
+ */
+ private static ResolvedBouncyCastleProvider toResolvedProvider(Provider provider) {
+ boolean fips = BC_FIPS.equals(provider.getName())
+ || BC_FIPS_PROVIDER_CLASS.equals(provider.getClass().getCanonicalName());
+ return new ResolvedBouncyCastleProvider(provider, fips);
+ }
+
+ private static Provider loadConscryptProvider() {
+ Class<?> conscryptClazz;
+
+ try {
+ conscryptClazz = Class.forName("org.conscrypt.Conscrypt");
+ conscryptClazz.getMethod("checkAvailability").invoke(null);
+ } catch (Throwable e) {
+ if (e instanceof ClassNotFoundException) {
+ log.debug("Conscrypt isn't available in the classpath. Using JDK default security provider.");
+ } else if (e.getCause() instanceof UnsatisfiedLinkError) {
+ log.debug().attr("os", System.getProperty("os.name")).attr("arch", System.getProperty("os.arch"))
+ .log("Conscrypt isn't available. Using JDK default security provider");
+ } else {
+ log.debug().attr("cause", e.getCause()).attr("reason", e.getMessage())
+ .log("Conscrypt isn't available. Using JDK default security provider");
+ }
+ return null;
+ }
+
+ Provider provider;
+ try {
+ provider = (Provider) Class.forName(CONSCRYPT_PROVIDER_CLASS).getDeclaredConstructor().newInstance();
+ } catch (ReflectiveOperationException e) {
+ log.debug().attr("class", CONSCRYPT_PROVIDER_CLASS).exception(e)
+ .log("Unable to get security provider");
+ return null;
+ }
+
+ // Unlike the PIP-337 loader this one installs NO custom hostname verifier, so Conscrypt keeps its
+ // built-in default: standard RFC 2818 (SAN-based) verification, matching PIP-478's removal of the
+ // deprecated CN-based matching. The bug-1015 workaround in processConscryptTrustManager propagates
+ // whatever Conscrypt's DEFAULT verifier is onto each TrustManager.
+ //
+ // CAVEAT while both TLS stacks coexist: Conscrypt.setDefaultHostnameVerifier is process-global, and
+ // SecurityUtility's static initializer (still the wired PIP-337 path) sets it to the CN-tolerant
+ // TlsHostnameVerifier. Whenever that class has been loaded, the "default" propagated above is that
+ // relaxed verifier, not Conscrypt's own. Nothing routes through this class yet so no deployment is
+ // affected today; the PR that turns SAN-only hostname verification on by default must neutralize that
+ // global (or land together with SecurityUtility's removal) for the SAN-only guarantee to hold on a
+ // Conscrypt-pinned deployment.
+
+ Security.addProvider(provider);
+ log.debug().attr("provider", provider.getName()).attr("class", CONSCRYPT_PROVIDER_CLASS)
+ .log("Added security provider");
+ return provider;
+ }
+
+ /**
+ * Get Bouncy Castle provider from classpath, and call Security.addProvider.
+ * Throw Exception if failed.
+ */
+ private static Provider getBCProviderFromClassPath() throws Exception {
+ Class<?> clazz;
+ try {
+ // prefer non FIPS, for backward compatibility concern.
+ clazz = Class.forName(BC_NON_FIPS_PROVIDER_CLASS);
+ } catch (ClassNotFoundException cnf) {
+ log.warn().attr("nonFipsClass", BC_NON_FIPS_PROVIDER_CLASS).attr("fipsClass", BC_FIPS_PROVIDER_CLASS)
+ .log("Not able to get Bouncy Castle provider, try to get FIPS provider");
+ // attempt to use the FIPS provider.
+ clazz = Class.forName(BC_FIPS_PROVIDER_CLASS);
+ }
+
+ Provider provider = (Provider) clazz.getDeclaredConstructor().newInstance();
+ Security.addProvider(provider);
+ log.debug().attr("provider", provider.getName())
+ .log("Found and Instantiated Bouncy Castle provider in classpath");
+ return provider;
+ }
+
+ /**
+ * Resolve a named {@link Provider} — e.g. the JSSE (SSLContext) provider named by the PIP-478
+ * {@code jsseProvider} field. Resolution prefers a provider the operator has already registered in the
+ * JVM ({@link Security#getProvider(String)}), falls back to the {@link ServiceLoader} mechanism on the
+ * application (thread-context) class loader ({@code META-INF/services/java.security.Provider}) matching
+ * by {@link Provider#getName()}, and fails loudly when the name resolves to nothing (the fail-fast
+ * contract — a misconfigured provider surfaces at client build / server start rather than silently
+ * defaulting).
+ *
+ * <p><b>Why the registered provider wins.</b> The two steps differ in <em>which instance</em> answers a
+ * name: {@code ServiceLoader} constructs a fresh instance through the provider's <em>no-arg</em>
+ * constructor, whereas {@link Security#getProvider(String)} returns the instance the operator installed.
+ * Preferring the latter makes an explicit {@code java.security} registration authoritative, which is
+ * what configuring one means — the operator's instance may carry provider-level configuration, and it is
+ * the object actually present in the JVM's provider list. It matters concretely for any provider that
+ * ships a {@code META-INF/services/java.security.Provider} entry <em>and</em> whose configuration is
+ * constructor-supplied; {@code bcprov} ships such an entry, so before this ordering a pinned
+ * {@code jcaProvider=BC} resolved to a fresh provider rather than the registered one.
+ *
+ * <p>Note that BouncyCastle's JSSE provider is <em>not</em> affected either way: {@code bctls} ships no
+ * services entry, so {@code BCJSSE} is never {@code ServiceLoader}-discoverable and must be registered
+ * by the operator to be resolvable at all. That is the only way its FIPS mode — a constructor argument,
+ * {@code new BouncyCastleJsseProvider("fips:BCFIPS")}, with the provider registering under the plain
+ * name {@code BCJSSE} either way — can reach Pulsar.
+ *
+ * <p>Unlike {@link #resolveProvider(String)} (which falls back to the default provider), this never
+ * returns {@code null} for a non-blank name: an unresolvable name is a configuration error.
+ *
+ * @param providerName the {@code java.security.Provider} name (blank/{@code null} returns {@code null})
+ * @return the resolved provider, or {@code null} when {@code providerName} is blank
+ * @throws IllegalArgumentException if a non-blank name resolves to no installed provider
+ */
+ public static Provider resolveNamedProvider(String providerName) {
+ if (StringUtils.isBlank(providerName)) {
+ return null;
+ }
+ String name = providerName.trim();
+ // 1. A provider the operator registered in the JVM wins — it carries their configuration (see above).
+ Provider registered = Security.getProvider(name);
+ if (registered != null) {
+ log.debug().attr("provider", name).log("Resolved JCA provider via Security.getProvider");
+ return registered;
+ }
+ // 2. ServiceLoader on the application class loader (META-INF/services/java.security.Provider).
+ ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+ if (classLoader == null) {
+ classLoader = JcaProviders.class.getClassLoader();
+ }
+ // Iterate defensively: a single broken META-INF/services/java.security.Provider entry (an unrelated
+ // provider whose class fails to load) throws ServiceConfigurationError from hasNext()/next(). Skipping
+ // it — rather than aborting the whole loop — lets a good provider still resolve here, and otherwise
+ // still falls through to the Security.getProvider fallback (step 2) rather than failing early.
+ Iterator<Provider> it = ServiceLoader.load(Provider.class, classLoader).iterator();
Review Comment:
All three fair — ccc22400913 — and the third is a real leftover: I reordered resolution so `Security.getProvider` is step 1, and that comment still described the old order.
On (1), you spotted the constraint yourself: matching is by `Provider.getName()`, which only exists on the instance, so `ServiceLoader.stream()` cannot avoid construction here. Documented rather than pretended away.
On (2), it is deliberate — resolution should not mutate global provider state, and every consumer hands the resolved object straight to `getInstance(algorithm, provider)` — but you are right that it deserves stating given how much the javadoc says about which instance answers a name. It now records that a `ServiceLoader`-resolved provider is not registered and so differs from what a later `Security.getProvider` would return.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/util/tls/JcaProviders.java:
##########
@@ -0,0 +1,474 @@
+/*
+ * 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.common.util.tls;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.security.NoSuchAlgorithmException;
+import java.security.Provider;
+import java.security.Security;
+import java.util.Iterator;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.ServiceConfigurationError;
+import java.util.ServiceLoader;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+
+/**
+ * Resolves the JCA/JCE security providers Pulsar relies on: a named provider for the PIP-478
+ * {@code jsseProvider} / {@code jcaProvider} axes, the Bouncy Castle provider (FIPS or non-FIPS), and the
+ * optional Conscrypt (OpenSSL) provider. This is the single provider-resolution primitive extracted from the
+ * {@code SecurityUtility} grab-bag (PIP-478).
+ *
+ * <p><b>Bouncy Castle is resolved lazily and is optional.</b> Loading this class must not require it: the
+ * class exists mainly to resolve <em>named</em> providers for the two TLS provider axes, which every TLS
+ * policy does, whereas Bouncy Castle is needed only by the code that actually asks for it (message
+ * encryption, and a deployment that pins {@code jcaProvider=BC}/{@code BCFIPS}). The provider is therefore
+ * looked up on first use through {@link #bouncyCastleProvider()} — which reports absence as
+ * {@link Optional#empty()} rather than failing — and only a caller that genuinely needs it, via
+ * {@link #requireBouncyCastleProvider()}, turns absence into an error. Resolving it does install it
+ * process-wide via {@code Security.addProvider}, as before.
+ *
+ * <p>Conscrypt, by contrast, is resolved during class initialization ({@link #CONSCRYPT_PROVIDER}) and
+ * installed process-wide when present; it reports absence as {@code null} and never fails class loading.
+ */
+@CustomLog
+public final class JcaProviders {
+
+ public static final String BC_FIPS_PROVIDER_CLASS = "org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider";
+ public static final String BC_NON_FIPS_PROVIDER_CLASS = "org.bouncycastle.jce.provider.BouncyCastleProvider";
+ public static final String BC_JSSE_PROVIDER_CLASS = "org.bouncycastle.jsse.provider.BouncyCastleJsseProvider";
+ public static final String CONSCRYPT_PROVIDER_CLASS = "org.conscrypt.OpenSSLProvider";
+ public static final Provider CONSCRYPT_PROVIDER = loadConscryptProvider();
+
+ // Security.getProvider("BC") / Security.getProvider("BCFIPS").
+ // also used to get Factories. e.g. CertificateFactory.getInstance("X.509", "BCFIPS")
+ public static final String BC_FIPS = "BCFIPS";
+ public static final String BC = "BC";
+
+ /**
+ * The name BouncyCastle's JSSE provider registers under — the same in FIPS and non-FIPS mode, because
+ * the mode is a constructor argument rather than part of the provider identity.
+ */
+ public static final String BC_JSSE = "BCJSSE";
+
+ private JcaProviders() {
+ }
+
+ /**
+ * A resolved Bouncy Castle provider together with which of the two artifacts it came from. The flavour
+ * travels with the provider because callers that care (FIPS-approved-only algorithm choices) would
+ * otherwise have to re-derive it from the provider's class name, and because the answer is fixed once
+ * the provider is resolved.
+ *
+ * @param provider the resolved, process-wide registered provider
+ * @param fips whether it is the FIPS-certified artifact ({@code bc-fips}, registered as
+ * {@code BCFIPS}) rather than the general-purpose one ({@code bcprov}, registered as
+ * {@code BC})
+ */
+ public record ResolvedBouncyCastleProvider(Provider provider, boolean fips) {
+ public ResolvedBouncyCastleProvider {
+ Objects.requireNonNull(provider, "provider must not be null");
+ }
+ }
+
+ /**
+ * Lazily resolves Bouncy Castle on first access, so that merely loading {@link JcaProviders} — which
+ * every named-provider resolution does — never requires Bouncy Castle to be on the classpath.
+ */
+ private static final class BouncyCastleHolder {
+ private static final ResolvedBouncyCastleProvider RESOLVED = loadBouncyCastleProvider();
+ }
+
+ /**
+ * The Bouncy Castle provider, installed process-wide on first resolution:
+ * <ol>
+ * <li>an already-registered {@code BC} or {@code BCFIPS} provider, if any;</li>
+ * <li>otherwise loaded from the classpath (non-FIPS preferred, FIPS as fallback) and registered via
+ * {@code Security.addProvider}.</li>
+ * </ol>
+ *
+ * @return the resolved provider and its flavour, or {@link Optional#empty()} when Bouncy Castle is not
+ * available. Callers that cannot proceed without it should use
+ * {@link #requireBouncyCastleProvider()}, so the failure names them rather than surfacing as a
+ * class-initialization error somewhere unrelated.
+ */
+ public static Optional<ResolvedBouncyCastleProvider> bouncyCastleProvider() {
+ return Optional.ofNullable(BouncyCastleHolder.RESOLVED);
+ }
+
+ /**
+ * As {@link #bouncyCastleProvider()}, for callers whose functionality genuinely requires Bouncy Castle.
+ *
+ * @return the resolved provider and its flavour
+ * @throws IllegalStateException when Bouncy Castle is not on the classpath
+ */
+ public static ResolvedBouncyCastleProvider requireBouncyCastleProvider() {
+ return bouncyCastleProvider().orElseThrow(() -> new IllegalStateException(
+ "No Bouncy Castle provider is available: neither an already-registered " + BC + "/" + BC_FIPS
+ + " provider nor " + BC_NON_FIPS_PROVIDER_CLASS + " / " + BC_FIPS_PROVIDER_CLASS
+ + " on the classpath. Add the bcprov (or bc-fips) dependency to use this feature."));
+ }
+
+ private static ResolvedBouncyCastleProvider loadBouncyCastleProvider() {
+ Provider installed = Security.getProvider(BC);
+ if (installed == null) {
+ installed = Security.getProvider(BC_FIPS);
+ }
+ if (installed != null) {
+ log.debug().attr("provider", installed.getName()).log("Already instantiated Bouncy Castle provider");
+ return toResolvedProvider(installed);
+ }
+ // Not installed, try to load from the classpath. Absence is not an error here — it is only an error
+ // for a caller that needs Bouncy Castle, which requireBouncyCastleProvider() reports.
+ try {
+ return toResolvedProvider(getBCProviderFromClassPath());
+ } catch (Exception e) {
+ log.debug().exception(e)
+ .log("No Bouncy Castle provider (FIPS or non-FIPS) on the classpath");
+ return null;
+ }
+ }
+
+ /**
+ * Lazily resolves BouncyCastle's JSSE provider on first access, registering it from the classpath when
+ * the operator has not installed it themselves.
+ */
+ private static final class BouncyCastleJsseHolder {
+ private static final ResolvedBouncyCastleProvider RESOLVED = loadBouncyCastleJsseProvider();
+ }
+
+ /**
+ * BouncyCastle's JSSE provider ({@value #BC_JSSE}), the provider a FIPS TLS deployment pins as
+ * {@code jsseProvider}.
+ *
+ * <p>Unlike every other provider this class resolves, {@value #BC_JSSE} cannot be discovered: {@code bctls}
+ * ships no {@code META-INF/services/java.security.Provider} entry, so an unregistered one is invisible to
+ * {@link ServiceLoader}. And it cannot simply be default-constructed either, because its FIPS mode is a
+ * constructor argument fixed at construction — the provider registers under the same name either way, so
+ * a no-arg instance would quietly be the non-FIPS one. This resolves it explicitly instead:
+ *
+ * <ol>
+ * <li>an instance the operator already registered wins, whatever mode they built it in;</li>
+ * <li>otherwise, when {@code bctls} is on the classpath, it is constructed and registered here — in
+ * FIPS mode bound to the FIPS JCA provider when {@link #bouncyCastleProvider()} resolved that one,
+ * and in the default mode otherwise, so the TLS stack follows whichever BouncyCastle artifact the
+ * deployment actually ships;</li>
+ * <li>otherwise it is absent, and pinning {@code jsseProvider=BCJSSE} fails loudly.</li>
+ * </ol>
+ *
+ * @return the resolved provider and whether it is in FIPS mode, or {@link Optional#empty()} when
+ * {@code bctls} is not on the classpath
+ */
+ public static Optional<ResolvedBouncyCastleProvider> bouncyCastleJsseProvider() {
+ return Optional.ofNullable(BouncyCastleJsseHolder.RESOLVED);
+ }
+
+ private static ResolvedBouncyCastleProvider loadBouncyCastleJsseProvider() {
+ Provider registered = Security.getProvider(BC_JSSE);
+ if (registered != null) {
+ log.debug().attr("provider", BC_JSSE).log("Already instantiated BouncyCastle JSSE provider");
+ return new ResolvedBouncyCastleProvider(registered, isJsseFipsMode(registered));
+ }
+ Class<?> providerClass;
+ try {
+ providerClass = Class.forName(BC_JSSE_PROVIDER_CLASS);
+ } catch (ClassNotFoundException e) {
+ log.debug().attr("class", BC_JSSE_PROVIDER_CLASS)
+ .log("No BouncyCastle JSSE provider on the classpath");
+ return null;
+ }
+ // Resolving the JCA provider first also installs it, which the FIPS configuration below needs: the
+ // JSSE provider looks its crypto provider up by name while constructing.
+ String config = jsseProviderConfig(bouncyCastleProvider().orElse(null));
+ try {
+ Provider provider = config == null
+ ? (Provider) providerClass.getDeclaredConstructor().newInstance()
+ : (Provider) providerClass.getDeclaredConstructor(String.class).newInstance(config);
+ Security.addProvider(provider);
+ boolean fips = isJsseFipsMode(provider);
+ log.info().attr("provider", provider.getName()).attr("fips", fips)
+ .log("Registered the BouncyCastle JSSE provider");
+ return new ResolvedBouncyCastleProvider(provider, fips);
+ } catch (ReflectiveOperationException | RuntimeException e) {
+ log.warn().attr("class", BC_JSSE_PROVIDER_CLASS).attr("config", config).exception(e)
+ .log("Failed to register the BouncyCastle JSSE provider");
+ return null;
+ }
+ }
+
+ /**
+ * The constructor argument for a self-registered {@value #BC_JSSE}: {@code "fips:<name>"} binds it to a
+ * FIPS JCA provider and turns FIPS mode on, while {@code null} selects the no-arg (default, non-FIPS)
+ * constructor. FIPS mode is chosen only when the resolved BouncyCastle JCA provider is itself the FIPS
+ * artifact — pairing a FIPS JSSE provider with a non-validated crypto provider would be FIPS-shaped
+ * rather than FIPS-compliant, which is exactly what the two provider axes exist to prevent.
+ *
+ * @param jcaProvider the resolved BouncyCastle JCA provider, or {@code null} when there is none
+ * @return the constructor argument, or {@code null} to use the no-arg constructor
+ */
+ @VisibleForTesting
+ static String jsseProviderConfig(ResolvedBouncyCastleProvider jcaProvider) {
+ if (jcaProvider == null || !jcaProvider.fips()) {
+ return null;
+ }
+ return "fips:" + jcaProvider.provider().getName();
+ }
+
+ /** Query a JSSE provider's FIPS mode reflectively, so this class never needs {@code bctls} to compile. */
+ private static boolean isJsseFipsMode(Provider provider) {
+ try {
+ return Boolean.TRUE.equals(provider.getClass().getMethod("isFipsMode").invoke(provider));
+ } catch (ReflectiveOperationException | RuntimeException e) {
+ log.debug().attr("provider", provider.getName()).exception(e)
+ .log("Provider exposes no isFipsMode(); assuming non-FIPS");
+ return false;
+ }
+ }
+
+ /**
+ * Classify a resolved provider. Both the registered name and the implementation class are checked: the
+ * FIPS artifact registers as {@code BCFIPS}, and matching the class as well keeps the classification
+ * right for a provider registered under a non-standard name.
+ */
+ private static ResolvedBouncyCastleProvider toResolvedProvider(Provider provider) {
+ boolean fips = BC_FIPS.equals(provider.getName())
+ || BC_FIPS_PROVIDER_CLASS.equals(provider.getClass().getCanonicalName());
+ return new ResolvedBouncyCastleProvider(provider, fips);
+ }
+
+ private static Provider loadConscryptProvider() {
+ Class<?> conscryptClazz;
+
+ try {
+ conscryptClazz = Class.forName("org.conscrypt.Conscrypt");
+ conscryptClazz.getMethod("checkAvailability").invoke(null);
+ } catch (Throwable e) {
+ if (e instanceof ClassNotFoundException) {
+ log.debug("Conscrypt isn't available in the classpath. Using JDK default security provider.");
+ } else if (e.getCause() instanceof UnsatisfiedLinkError) {
+ log.debug().attr("os", System.getProperty("os.name")).attr("arch", System.getProperty("os.arch"))
+ .log("Conscrypt isn't available. Using JDK default security provider");
+ } else {
+ log.debug().attr("cause", e.getCause()).attr("reason", e.getMessage())
+ .log("Conscrypt isn't available. Using JDK default security provider");
+ }
+ return null;
+ }
+
+ Provider provider;
+ try {
+ provider = (Provider) Class.forName(CONSCRYPT_PROVIDER_CLASS).getDeclaredConstructor().newInstance();
+ } catch (ReflectiveOperationException e) {
+ log.debug().attr("class", CONSCRYPT_PROVIDER_CLASS).exception(e)
+ .log("Unable to get security provider");
+ return null;
+ }
+
+ // Unlike the PIP-337 loader this one installs NO custom hostname verifier, so Conscrypt keeps its
+ // built-in default: standard RFC 2818 (SAN-based) verification, matching PIP-478's removal of the
+ // deprecated CN-based matching. The bug-1015 workaround in processConscryptTrustManager propagates
+ // whatever Conscrypt's DEFAULT verifier is onto each TrustManager.
+ //
+ // CAVEAT while both TLS stacks coexist: Conscrypt.setDefaultHostnameVerifier is process-global, and
+ // SecurityUtility's static initializer (still the wired PIP-337 path) sets it to the CN-tolerant
+ // TlsHostnameVerifier. Whenever that class has been loaded, the "default" propagated above is that
+ // relaxed verifier, not Conscrypt's own. Nothing routes through this class yet so no deployment is
+ // affected today; the PR that turns SAN-only hostname verification on by default must neutralize that
+ // global (or land together with SecurityUtility's removal) for the SAN-only guarantee to hold on a
Review Comment:
Agreed, and the process point is what convinces me — a cross-PR constraint recorded only as a comment in a file the constrained PR may never open is not durable.
I have not filed the issue from this session; it will be opened and linked from PIP-478 with the following substance: `Conscrypt.setDefaultHostnameVerifier` is process-global; `SecurityUtility`'s static initializer (still the wired PIP-337 path) sets it to the CN-tolerant `TlsHostnameVerifier`; `JcaProviders` propagates Conscrypt's *default* verifier onto each trust manager, so whenever `SecurityUtility` has been class-loaded the "default" is the relaxed verifier and the SAN-only guarantee silently does not hold. The PR that turns SAN-only verification on by default must neutralize that global, or land together with `SecurityUtility`'s removal.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [feat][misc] PIP-478: default file-based TLS factory implementation [pulsar]
Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on PR #26271:
URL: https://github.com/apache/pulsar/pull/26271#issuecomment-5190365457
Thanks — this is a careful review, and it found two things that two prior multi-model review passes on this branch missed: the coordinator's `whenComplete` running inline under the source monitor (the default factory never returns an incomplete `SSLParameters` future), and the `isStarted()` TOCTOU that drops a rotation silently.
Every comment has an inline reply. 17 of the 19 are addressed in 15 commits, one per comment where that made sense.
**Behaviour changes**
- `WEB` purpose honours `webServiceTlsProvider` / `webServiceTlsProtocols` / `webServiceTlsCiphers`, falling back to the binary-listener keys — a3d135b77aa
- Jetty reload moved off the delivery thread onto a supplied executor — a4832cd40e1
- Jetty apply became an unconditional `reload(...)`, closing the start race — a4832cd40e1
- Synchronous builders document the blocking-executor constraint and unwrap `CompletionException` — a4832cd40e1
- Material poll runs on the blocking executor, not the framework scheduler — 49ef9ebefe7
- Re-entrant acquisition fails loudly instead of deadlocking — 373d462b405
- Hostname verification pinned off on server-role policies — 984fd9d72d2
- Rotation detection uses size and file identity, not mtime alone — 065b304623c
- Insecure-mode warn set no longer retains policies (and their passwords) — 03443372293
**Hygiene, docs and tests**
- Redundant `compileOnly opentelemetry-api` and its incorrect comment deleted — 21a9afb64a5
- `JcaProviders` resolution javadoc corrected and completed — ccc22400913
- Named class-initialization call replaces the empty `if` — 7316728ac71
- `SubscriptionHandle.dispose` matches `OneShotHandle`'s guard — 01c848e5ae0
- Factory-wide client-auth documented as deliberate PIP-337 parity — 0aa644b9d76
- The three fail-closed material tightenings documented for the upgrade notes — 9d3ea3c2c99
- BouncyCastle key value-equality pinned by a test — a9e50fe6e1d
- Test-provider visibility rationale recorded — 50d91093f0a
**Not code changes here, deliberately**
- The auth-overlay re-parse: an auth-data identity check would miss plugin-internal rotation, so the workable form is mtime-stats of the plugin's file paths. Better landed in the PR that decides the acquisition pattern, where it can be measured rather than guessed.
- The Conscrypt global-verifier constraint: getting a tracking issue linked from PIP-478, as you suggested.
**One I am pushing back on**
`opentelemetry-api` is on the runtime classpath transitively via `pulsar-tls-factory-api`'s `api` declaration, so the `NoClassDefFoundError` cannot occur. But the `compileOnly` line that prompted the question was redundant and its comment was wrong, so both are deleted — details in that thread.
Two points on the `webServiceTls*` comment describe master's existing behaviour rather than a regression this series introduces; evidence in that thread, along with an error of ours in the PIP text that your comment flushed out.
**Verification.** 1270 tests, 0 failures across `pulsar-common` and `pulsar-broker-common`, plus `assemble rat spotlessCheck checkstyleMain checkstyleTest checkBinaryLicense`. Full CI matrix running.
One ask: the review body mentions a summary and "the one issue I'd call major" in a conversation comment, but I don't see one on the PR — could you re-post it? I don't want to answer around it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [feat][misc] PIP-478: default file-based TLS factory implementation [pulsar]
Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #26271:
URL: https://github.com/apache/pulsar/pull/26271#discussion_r3730663389
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/tls/DefaultBrokerTlsFactory.java:
##########
@@ -0,0 +1,240 @@
+/*
+ * 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.broker.tls;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.client.api.Authentication;
+import org.apache.pulsar.client.api.AuthenticationDataProvider;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactory;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactorySettings;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The broker's default {@code PulsarTlsFactory}: a thin {@link FileBasedTlsFactory} whose purpose→
+ * policy map is composed from a {@link ServiceConfiguration} (PIP-478).
+ *
+ * <p>It lives in {@code pulsar-broker-common} — which owns the Jetty integration and the broker
+ * configuration — so that neither the SPI module nor {@code pulsar-common} carries broker-config
+ * knowledge. The class only <em>composes</em> the map; wiring it into the broker/proxy/web services is
+ * a later stage.
+ */
+public class DefaultBrokerTlsFactory extends FileBasedTlsFactory {
+
+ /**
+ * Construct the broker factory from an already-composed purpose→policy map.
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ super(policies, settings);
+ }
+
+ /**
+ * Construct a broker factory that additionally folds the broker-client authentication's TLS material
+ * over the {@link TlsPurpose#BROKER_CLIENT} file policy (PIP-478).
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ super(policies, settings, authMaterialSuppliers);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}.
+ *
+ * @param conf the broker service configuration
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf) {
+ return fromServiceConfiguration(conf, null);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}, optionally folding the
+ * broker's broker-client {@link Authentication} TLS material over the {@link TlsPurpose#BROKER_CLIENT}
+ * file policy (PIP-478) for the broker's own outbound (broker-to-broker / replication) connections.
+ *
+ * <p>The broker's server material is registered for the {@link TlsPurpose#BROKER},
+ * {@link TlsPurpose#PROXY} and {@link TlsPurpose#WEB} purposes; the broker's outbound
+ * (broker-to-broker) material for {@link TlsPurpose#BROKER_CLIENT}. When {@code brokerClientAuth} is
+ * supplied and a broker-client authentication plugin is configured, its in-memory cert/key override the
+ * {@code brokerClient*} file paths (auth-cert-wins), so the broker presents the right identity to its
+ * peers — the server-side mirror of the client TLS override hook.
+ *
+ * @param conf the broker service configuration
+ * @param brokerClientAuth the broker's broker-client authentication, or {@code null} for no fold
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf,
+ Authentication brokerClientAuth) {
+ Map<TlsPurpose, TlsPolicy> policies = new LinkedHashMap<>();
+ TlsPolicy serverPolicy = serverPolicy(conf);
+ policies.put(TlsPurpose.BROKER, serverPolicy);
+ policies.put(TlsPurpose.PROXY, serverPolicy);
+ policies.put(TlsPurpose.WEB, webPolicy(conf));
+ policies.put(TlsPurpose.BROKER_CLIENT, brokerClientPolicy(conf));
+
+ FileBasedTlsFactorySettings settings = FileBasedTlsFactorySettings.builder()
+ .requireTrustedClientCert(conf.isTlsRequireTrustedClientCertOnConnect())
+ .refreshIntervalSeconds(refreshIntervalSeconds(conf))
+ // Engine selection (JDK vs. OpenSSL) mapped from the broker's tlsProvider field: an explicit
+ // engine literal is honored verbatim, a JSSE provider name selects no engine, and an unset
+ // value takes the native engine as OPENSSL_REFCNT when tcnative is available (see
+ // TlsFactorySupport.engineProvider).
+ .engineProvider(TlsFactorySupport.engineProvider(conf.getTlsProvider()))
+ .build();
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authSuppliers =
+ (brokerClientAuth != null && StringUtils.isNotBlank(conf.getBrokerClientAuthenticationPlugin()))
+ ? Map.of(TlsPurpose.BROKER_CLIENT, FileBasedTlsFactory.authMaterialSupplier(brokerClientAuth))
+ : Map.of();
+ return new DefaultBrokerTlsFactory(policies, settings, authSuppliers);
+ }
+
+ /**
+ * The {@link TlsPurpose#WEB} policy. The web listener has its own provider/protocol/cipher keys, and
+ * they take precedence over the binary-listener ones when set — {@code webServiceTlsProvider},
+ * {@code webServiceTlsProtocols}, {@code webServiceTlsCiphers} — falling back to {@code tlsProvider},
+ * {@code tlsProtocols}, {@code tlsCiphers} when they are not. Material (PEM or keystore) and the
+ * insecure flag are shared with the binary listener, as they are today.
+ *
+ * <p>Note the fallback is what makes the precedence safe to apply now: {@code webServiceTlsProvider}
+ * ships a non-blank default of {@code Conscrypt}, so it always wins over {@code tlsProvider} unless an
+ * operator blanks it. That matches the key's documented meaning — it names the JSSE (SSLContext)
+ * provider for the Jetty web listener — and Conscrypt is shipped in the server distribution. On a
+ * platform where the Conscrypt native library cannot load, the provider is not registered and pinning
+ * it fails loudly at startup rather than silently ignoring the configuration.
+ */
+ @VisibleForTesting
+ static TlsPolicy webPolicy(ServiceConfiguration conf) {
+ return serverPolicy(conf,
+ firstNonBlank(conf.getWebServiceTlsProvider(), conf.getTlsProvider()),
+ firstNonEmpty(conf.getWebServiceTlsProtocols(), conf.getTlsProtocols()),
+ firstNonEmpty(conf.getWebServiceTlsCiphers(), conf.getTlsCiphers()));
+ }
+
+ @VisibleForTesting
+ static TlsPolicy serverPolicy(ServiceConfiguration conf) {
+ return serverPolicy(conf, conf.getTlsProvider(), conf.getTlsProtocols(), conf.getTlsCiphers());
+ }
+
+ private static String firstNonBlank(String preferred, String fallback) {
+ return StringUtils.isNotBlank(preferred) ? preferred : fallback;
+ }
+
+ private static Set<String> firstNonEmpty(Set<String> preferred, Set<String> fallback) {
+ return preferred != null && !preferred.isEmpty() ? preferred : fallback;
+ }
+
+ private static TlsPolicy serverPolicy(ServiceConfiguration conf, String provider, Set<String> protocols,
+ Set<String> ciphers) {
+ // enableHostnameVerification is pinned OFF on server-role policies rather than mapped from
+ // tlsHostnameVerificationEnabled, which is the broker's OUTBOUND setting ("whether the hostname is
+ // validated when the broker creates a TLS connection with other brokers") and belongs on
+ // brokerClientPolicy() alone. It is inert either way today — only the client context builders read
+ // the flag — but a server policy carrying it would invite a future consumer to enable endpoint
+ // identification on a server engine, i.e. verify the CLIENT's hostname. It has to be set
+ // explicitly: TlsPolicy.Builder defaults the flag to true (secure-by-default for clients), so
+ // simply omitting it would leave every server policy claiming hostname verification is on.
+ TlsPolicy.Builder builder = TlsPolicy.builder()
+ .allowInsecureConnection(conf.isTlsAllowInsecureConnection())
+ .enableHostnameVerification(false)
Review Comment:
Thanks — the configuration is respected, but on the other policy: `tlsHostnameVerificationEnabled` is mapped at line 196, onto the `TlsPurpose.BROKER_CLIENT` policy.
I'd rather not take the suggestion as written. `serverPolicy(...)` composes the three **server-role** purposes — `BROKER`, `PROXY`, `WEB` — and on those `enableHostnameVerification` means *verify the peer's hostname*, where the peer is the connecting **client**. The key is the broker's outbound setting: `ServiceConfiguration:2077` documents it as "whether the hostname is validated when the broker creates a TLS connection with other brokers", and all 13 existing uses in the tree configure an outbound client (`BrokerService`'s four `brokerClient*` blocks, `PulsarService`, `NamespaceService`, `WebSocketService`, `CompactorTool`, `ProxyConnection`, `DirectProxyHandler`, `AdminProxyHandler`). Nothing feeds it into a server-side SSL context today, so mapping it here would also change behaviour relative to the PIP-337 path this mirrors.
That said, your reading of the diff was reasonable and the tests were the reason: the only coverage asserted the negative half — server policies keep the flag off — and never asserted the config actually arrives anywhere. From the diff it does look dropped.
Fixed in 0763bf33a3d: `brokerClientPolicy` is `@VisibleForTesting`, and the test now asserts both halves — the flag reaches `BROKER_CLIENT` in both positions, and stays off on the server-role policies. Mutation-verified both ways: applying your suggested line fails the test, and so does dropping the mapping at line 196. The comment at the pin now names the honoring site too.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [feat][misc] PIP-478: default file-based TLS factory implementation [pulsar]
Posted by "david-streamlio (via GitHub)" <gi...@apache.org>.
david-streamlio commented on code in PR #26271:
URL: https://github.com/apache/pulsar/pull/26271#discussion_r3724181500
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/FileBasedTlsFactory.java:
##########
@@ -0,0 +1,835 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.util.ReferenceCountUtil;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import javax.net.ssl.SSLContext;
+import lombok.CustomLog;
+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.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsEndpoint;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The default, file-based {@link PulsarTlsFactory} (PIP-478).
+ *
+ * <p>Immutable after construction: the complete {@code TlsPurpose -> TlsPolicy} map and the
+ * factory-wide {@link FileBasedTlsFactorySettings} are fixed by the constructor and never mutated. The
+ * owning component (the v5 client builder, or {@code DefaultBrokerTlsFactory} on the server side)
+ * composes the final map before constructing the factory.
+ *
+ * <p>Natively supplies the Netty {@code SslContext} (on the configured engine — JDK or OpenSSL) and the
+ * JDK {@code SSLContext}; returns {@code empty()} for every other class (notably Jetty's
+ * {@code SslContextFactory.Server} and {@code SslContextFactory.Client}), which the framework synthesizes
+ * from the JDK {@code SSLContext}. It also
+ * returns {@code empty()} for the {@code javax.net.ssl.SSLParameters} companion (PIP-478): its engine policy
+ * (protocols, ciphers, client-auth mode, hostname verification) is baked natively into the Netty contexts it
+ * builds, so it exposes no separate baseline for the framework to overlay on those.
+ *
+ * <p>A JDK {@code SSLContext} cannot itself carry that policy — enabled protocols and cipher suites,
+ * algorithm constraints and the endpoint-identification algorithm are all per-engine {@code SSLParameters}
+ * settings — so the JDK context this factory returns is a <em>material carrier</em>: it holds the key and
+ * trust managers (built through the pinned providers) and nothing else. Every consumer of it applies the
+ * engine policy itself from the same {@link TlsPolicy}, which is what {@code JettyTlsFactory} does. A
+ * consumer that instead created engines straight from this {@code SSLContext} would get the provider defaults,
+ * so consumers must not do that.
+ *
+ * <p><b>Purpose resolution.</b> A request resolves the requested purpose directly against the configured
+ * {@code TlsPurpose -> TlsPolicy} map. When nothing is configured for the purpose, a {@code CLIENT}-role
+ * purpose resolves to the system default (OS trust store, no client certificate) and a {@code SERVER}-role
+ * purpose fails the request. A resolved-but-unbuildable request completes the future <em>exceptionally</em>
+ * — never {@code empty()}, which strictly means "unsupported {@code (purpose, class)} combination".
+ *
+ * <p><b>Rotation.</b> One {@link TlsMaterialSource} is shared per configured purpose. Server-side
+ * subscribers are pushed rebuilt instances by a background poll (interval from the settings, on the
+ * framework scheduler); client-side one-shot callers re-stat on each request and pick up rotation
+ * naturally. Because a re-stat consumes the source's change signal, an acquisition that observes a change
+ * first also fans it out to that purpose's subscribers, so a rotation is never swallowed by whoever happened
+ * to look first. A failed rebuild keeps the last-good instance, logs at WARN, and retries on the next
+ * change; a subscriber callback that throws is caught and logged, and the subscription stays live.
+ */
+@CustomLog
+public class FileBasedTlsFactory implements PulsarTlsFactory {
+
+ private final Map<TlsPurpose, RegisteredSource> registry;
+ private final FileBasedTlsFactorySettings settings;
+
+ private volatile TlsFactoryInitContext initContext;
+ private volatile TlsReloadMetrics metrics;
+ private volatile RegisteredSource systemDefaultSource;
+ private volatile ScheduledFuture<?> pollFuture;
+ private volatile boolean closed;
+ // Stands in for scheduleWithFixedDelay's no-overlap guarantee once the poll body is dispatched.
+ private final AtomicBoolean pollInFlight = new AtomicBoolean();
+
+ /**
+ * Construct an immutable file-based factory.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ this(policies, settings, Map.of());
+ }
+
+ /**
+ * Construct an immutable file-based factory that additionally folds an authentication plugin's TLS
+ * material over the configured file policy for the named purposes (the server-side {@code BROKER_CLIENT}
+ * fold — PIP-478). For a purpose present in {@code authMaterialSuppliers}, the supplier's
+ * {@code Authentication} material overrides the file policy's key/cert per
+ * {@link AuthProvidedMaterialSource} (auth-cert-wins); other purposes use the file policy unchanged.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ Objects.requireNonNull(policies, "policies must not be null");
+ this.settings = Objects.requireNonNull(settings, "settings must not be null");
+ Objects.requireNonNull(authMaterialSuppliers, "authMaterialSuppliers must not be null");
+ Map<TlsPurpose, RegisteredSource> built = new LinkedHashMap<>();
+ for (Map.Entry<TlsPurpose, TlsPolicy> entry : policies.entrySet()) {
+ TlsPurpose purpose = Objects.requireNonNull(entry.getKey(), "purpose key must not be null");
+ TlsPolicy policy = Objects.requireNonNull(entry.getValue(), "policy must not be null");
+ TlsMaterialSource fileSource = new TlsMaterialSource(policy);
+ Supplier<AuthenticationDataProvider> authSupplier = authMaterialSuppliers.get(purpose);
+ MaterialSource source = authSupplier == null
+ ? fileSource
+ : new AuthProvidedMaterialSource(fileSource, authSupplier);
+ built.put(purpose, new RegisteredSource(purpose, policy, source));
+ }
+ this.registry = Map.copyOf(built);
+ }
+
+ /**
+ * Adapt a component's broker-client {@link Authentication} to a per-refresh
+ * {@link AuthenticationDataProvider} supplier for use with the {@code BROKER_CLIENT} fold constructor.
+ * The supplier re-reads {@code getAuthData()} on each poll so credential rotation is observed; a checked
+ * {@link PulsarClientException} is rethrown unchecked and handled by the factory's keep-last-good poll.
+ *
+ * @param authentication the broker-client authentication plugin (never {@code null})
+ * @return a supplier of the plugin's current authentication data
+ */
+ public static Supplier<AuthenticationDataProvider> authMaterialSupplier(Authentication authentication) {
+ Objects.requireNonNull(authentication, "authentication must not be null");
+ return () -> {
+ try {
+ return resolveAuthData(authentication);
+ } catch (PulsarClientException e) {
+ throw new RuntimeException("Failed to obtain broker-client authentication TLS material", e);
+ }
+ };
+ }
+
+ // The BROKER_CLIENT TLS fold is host-agnostic — TLS key material does not vary by peer — so the
+ // host-less getAuthData() is exactly what we want; isolate its deprecation here.
+ @SuppressWarnings("deprecation")
+ private static AuthenticationDataProvider resolveAuthData(Authentication authentication)
+ throws PulsarClientException {
+ return authentication.getAuthData();
+ }
+
+ @Override
+ public CompletableFuture<Void> initialize(TlsFactoryInitContext context) {
+ try {
+ Objects.requireNonNull(context, "context must not be null");
+ // Required, not optional: every acquisition path in this factory reads files and parses key
+ // material. Without an executor the work would run inline on the caller's thread, which the SPI
+ // contract says may be a consumer event loop. Fail at wiring time rather than stalling a channel.
+ Objects.requireNonNull(context.blockingExecutor(),
+ "TlsFactoryInitContext.blockingExecutor() must not be null: FileBasedTlsFactory performs "
+ + "blocking file and key-material loading and must never run it on a consumer thread");
+ this.initContext = context;
+ // Cancel any poll scheduled by a prior initialize() so a second call does not orphan the first:
+ // the field is overwritten below and the old task would otherwise run forever.
+ ScheduledFuture<?> previousPoll = this.pollFuture;
+ if (previousPoll != null) {
+ previousPoll.cancel(false);
+ }
+ // Same reasoning for the metrics: a prior initialize() registered an observable gauge that stays
+ // registered on the meter until close(), so overwriting the field without closing it would leave
+ // an orphaned callback reporting stale per-purpose timestamps forever.
+ TlsReloadMetrics previousMetrics = this.metrics;
+ if (previousMetrics != null) {
+ previousMetrics.close();
+ }
+ this.metrics = TlsReloadMetrics.create(context.openTelemetry(), context.clock());
+ int interval = settings.refreshIntervalSeconds();
+ if (interval > 0 && context.scheduler() != null) {
+ // The scheduler only TRIGGERS the poll; the work runs on the blocking executor. The poll
+ // stats files, parses PEM/keystores and rebuilds contexts, which is exactly the work this
+ // method refuses to run without a blocking executor a few lines above — running it on a
+ // shared framework scheduler thread would occupy that thread for the duration, and with
+ // material on slow or network-backed storage that is not bounded by anything.
+ this.pollFuture = context.scheduler().scheduleWithFixedDelay(
+ this::triggerPoll, interval, interval, TimeUnit.SECONDS);
+ }
+ log.debug().attr("purposes", registry.keySet()).attr("refreshIntervalSeconds", interval)
+ .log("Initialized FileBasedTlsFactory");
+ return CompletableFuture.completedFuture(null);
+ } catch (Throwable t) {
+ return CompletableFuture.failedFuture(t);
+ }
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(TlsPurpose purpose, Class<T> instanceClass) {
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, TlsEndpoint endpoint, Class<T> instanceClass) {
+ // The default file-based factory serves purpose-scoped material and ignores the endpoint hint.
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, Class<T> instanceClass, Consumer<T> onLoadOrReload) {
+ if (onLoadOrReload == null) {
+ // SPI contract: argument-validation failures complete the returned future exceptionally — this
+ // method never throws on the calling thread.
+ return CompletableFuture.failedFuture(new NullPointerException("onLoadOrReload must not be null"));
+ }
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ rejectReentrantAcquisition(source, purpose);
+ synchronized (source) {
+ // FIX F: close() runs releaseAll() under this same source lock, and may have completed after
+ // the outer closed-check but before this task acquired the lock. Re-check here so we never
+ // build+cache+deliver a context (and register a subscription) whose factory-owned reference
+ // would then never be released — that would leak past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ Subscription<T> subscription = new Subscription<>(instanceClass, onLoadOrReload);
+ // Initial delivery happens-before the returned future completes (same thread, ordered).
+ subscription.deliver(instance);
+ source.subscriptions.add(subscription);
+ return Optional.of((TlsHandle<T>) new SubscriptionHandle<>(source, subscription));
+ }
+ });
+ }
+
+ private <T> CompletableFuture<Optional<TlsHandle<T>>> createOneShot(TlsPurpose purpose, Class<T> instanceClass) {
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ rejectReentrantAcquisition(source, purpose);
+ synchronized (source) {
+ // FIX F: re-check under the source lock (see createInstance above) so a task racing a
+ // concurrent close()/releaseAll() never builds+retains a context that then leaks past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ retain(instance);
+ return Optional.of((TlsHandle<T>) new OneShotHandle<>(instance));
+ }
+ });
+ }
+
+ /**
+ * Load (or reuse the cached) instance of {@code instanceClass} for the resolved source, recording a
+ * {@code pulsar.tls.reload} attempt for the source's purpose. A resolution failure upstream (an
+ * unconfigured server purpose) is a startup configuration error and is not counted here — only actual
+ * material loads are. Must be called while holding the source monitor.
+ *
+ * <p>Success is counted only for a <em>real</em> (re)load, mirroring the poll path: the first build of a
+ * context class for this source, or a refresh that found changed material. A repeat one-shot acquisition
+ * that re-serves the memoized context (every new connection, on the acquire-per-connection paths) is not a
+ * reload — counting it would inflate {@code pulsar.tls.reload} and keep advancing
+ * {@code pulsar.tls.last_reload_success}, masking exactly the stalled rotation the Monitoring section
+ * alerts on. Failures stay unconditional: an attempt that threw is always worth counting.
+ */
+ private <T> T loadInitialInstance(RegisteredSource source, Class<T> instanceClass) throws Exception {
+ // Hoisted out of the try so the catch can tell whether this call already CONSUMED a rotation before
+ // failing (see the comment on the catch below). Null means currentMaterial() itself threw, which
+ // commits no baseline and so consumes nothing.
+ MaterialSource.RefreshOutcome outcome = null;
+ try {
+ outcome = source.currentMaterial();
+ // Sampled before acquireInstance, which is what populates the memo (both calls run under the
+ // source monitor held by the caller, so no other acquisition can interleave).
+ boolean firstBuild = source.cachedInstance(instanceClass) == null;
+ T instance = source.acquireInstance(instanceClass, outcome.material(), settings);
+ // Rotation fan-out: currentMaterial() CONSUMES the source's change signal (refresh() commits the new
+ // mtime baseline), so whoever refreshes first is the only caller that ever sees changed=true. Without
+ // this, a one-shot acquisition (or an initial subscribing acquisition) that observes a rotation first
+ // leaves every later poll reporting changed=false and the subscribers on this same purpose wedged on
+ // the pre-rotation instance forever — e.g. an https:// client whose FrameworkHttpClientFactory
+ // subscribes to CLIENT_DEFAULT while another path acquires one-shot on it. Deliver the observed
+ // change here, exactly as the poll would have; a delivery failure arms pendingRedeliver so the next
+ // poll retries. No extra metric is recorded — this shares the single recordLoad below.
+ // Also drive the retry when a previous rotation's fan-out failed: the poll is the usual driver,
+ // but it is disabled entirely when refreshIntervalSeconds <= 0, and even when enabled an
+ // acquisition may get here first. Without this, a subscriber wedged by a failed rebuild would
+ // stay on the pre-rotation instance until the files changed again.
+ boolean retryPending = source.pendingRedeliver();
+ boolean delivered = true;
+ if (outcome.changed() || retryPending) {
+ delivered = source.deliverToSubscribers(outcome.material(), settings);
+ }
+ if (outcome.changed() || retryPending || firstBuild) {
+ recordLoad(source.purpose, delivered);
+ }
+ return instance;
+ } catch (Exception e) {
+ recordLoad(source.purpose, false);
+ // The material parsed (the baseline is committed) but building or delivering the context failed.
+ // currentMaterial() has therefore already CONSUMED this rotation's change signal, so every later
+ // poll would report changed=false and — without arming the redeliver flag here — return early,
+ // leaving the subscribers wedged on the pre-rotation instance until the files change again.
+ // deliverToSubscribers arms the flag itself on a partial delivery failure; this covers the case
+ // where the failure happened before it was ever reached.
+ if (outcome != null && outcome.changed()) {
+ source.armRedeliver();
+ }
+ // Keep-last-good (PIP-478): a one-shot (or initial subscribing) acquisition during a
+ // non-atomic rotation window — e.g. the cert file briefly unreadable while it is being replaced —
+ // must not fail when a prior load already built a context of this class. Serve that last-good
+ // instance and WARN; the reload-failure metric was recorded above. Fail only when there is no
+ // last-good to fall back on (a genuine startup misconfiguration, per the fail-fast contract).
+ T cached = source.cachedInstance(instanceClass);
+ if (cached != null) {
+ log.warn().attr("purpose", source.purpose).exception(e)
+ .log("Failed to load TLS material; serving the last-good instance");
+ return cached;
+ }
+ throw e;
+ }
+ }
+
+ private void recordLoad(TlsPurpose purpose, boolean success) {
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.recordLoad(purpose, success);
+ }
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ ScheduledFuture<?> poll = this.pollFuture;
+ if (poll != null) {
+ poll.cancel(false);
+ }
+ for (RegisteredSource source : registry.values()) {
+ source.releaseAll();
+ }
+ RegisteredSource systemDefault = this.systemDefaultSource;
+ if (systemDefault != null) {
+ systemDefault.releaseAll();
+ }
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.close();
+ }
+ }
+
+ /**
+ * Resolve a requested purpose to the {@link RegisteredSource} that owns its material, applying the
+ * role's terminal-resolution rule when nothing is configured for the purpose.
+ *
+ * @throws TlsMaterialUnavailableException when a server-role purpose has no material configured
+ */
+ private RegisteredSource resolve(TlsPurpose purpose) {
+ Objects.requireNonNull(purpose, "purpose must not be null");
+ RegisteredSource source = registry.get(purpose);
+ if (source != null) {
+ return source;
+ }
+ if (purpose.role() == TlsPurpose.Role.CLIENT) {
+ return systemDefaultSource();
+ }
+ throw new TlsMaterialUnavailableException(
+ "No TLS material configured for server purpose " + purpose);
+ }
+
+ private RegisteredSource systemDefaultSource() {
+ RegisteredSource existing = this.systemDefaultSource;
+ if (existing != null) {
+ return existing;
+ }
+ synchronized (this) {
+ if (this.systemDefaultSource == null) {
+ // System default: verify hostnames, OS trust store, no client certificate. A constant
+ // source (no files, never rotates).
+ TlsPolicy defaultPolicy = TlsPolicy.builder().build();
+ this.systemDefaultSource = new RegisteredSource(
+ TlsPurpose.CLIENT_DEFAULT, defaultPolicy, null);
+ }
+ return this.systemDefaultSource;
+ }
+ }
+
+ /**
+ * Hand the poll to the blocking executor, preserving {@code scheduleWithFixedDelay}'s no-overlap
+ * property: dispatching breaks the scheduler's own guarantee that one run finishes before the next is
+ * scheduled, so an in-flight flag stands in for it. A poll slower than the interval therefore skips
+ * ticks rather than queueing them up behind itself.
+ */
+ private void triggerPoll() {
+ if (closed || !pollInFlight.compareAndSet(false, true)) {
+ return;
+ }
+ try {
+ pollExecutor().execute(() -> {
+ try {
+ pollSafely();
+ } finally {
+ pollInFlight.set(false);
+ }
+ });
+ } catch (Throwable t) {
+ // Rejected (executor shutting down, queue full): clear the flag so a later tick can retry.
+ pollInFlight.set(false);
+ log.debug().exception(t).log("Could not dispatch the TLS material poll");
+ }
+ }
+
+ private Executor pollExecutor() {
+ TlsFactoryInitContext context = this.initContext;
+ return context != null ? context.blockingExecutor() : Runnable::run;
+ }
+
+ private void pollSafely() {
+ if (closed) {
+ return;
+ }
+ try {
+ for (RegisteredSource source : registry.values()) {
+ source.poll(settings, metrics);
+ }
+ } catch (Throwable t) {
+ log.warn().exception(t).log("Unexpected error during TLS material poll");
+ }
+ }
+
+ private <R> CompletableFuture<R> runAsync(Callable<R> task) {
+ CompletableFuture<R> future = new CompletableFuture<>();
+ TlsFactoryInitContext context = this.initContext;
+ // initialize() rejects a null blockingExecutor, so the caller-thread fallback is reachable only before
+ // initialize() has run — a direct-construction path (tests, or a component acquiring during its own
+ // startup) that is by definition not on a consumer event loop.
+ Executor executor = context != null ? context.blockingExecutor() : Runnable::run;
+ try {
+ executor.execute(() -> {
+ try {
+ R result = task.call();
+ if (!future.complete(result)) {
+ // The caller cancelled (or otherwise completed) the future while the acquisition was
+ // still running, so nothing will ever receive this handle. The task has already
+ // retained the context on its behalf, and with the finalizer-free OPENSSL_REFCNT
+ // engine an unbalanced retain is a permanent native leak — dispose the orphan here.
+ disposeOrphan(result);
+ }
+ } catch (Throwable t) {
+ future.completeExceptionally(t);
+ }
+ });
+ } catch (Throwable t) {
+ future.completeExceptionally(t);
+ }
+ return future;
+ }
+
+ /**
+ * Release a handle that was built but could not be delivered to its caller. Both acquisition forms
+ * produce an {@code Optional<TlsHandle<?>>}, and disposing it is exactly what the caller would have done:
+ * it drops the one-shot's retained reference, or unregisters the subscription and releases its borrows.
+ */
+ private static void disposeOrphan(Object result) {
+ if (result instanceof Optional<?> optional && optional.orElse(null) instanceof TlsHandle<?> handle) {
+ try {
+ handle.dispose();
+ } catch (Throwable t) {
+ log.warn().exception(t).log("Failed to dispose an undelivered TLS handle");
+ }
+ }
+ }
+
+ private static boolean isSupported(Class<?> instanceClass) {
+ return instanceClass == SslContext.class || instanceClass == SSLContext.class;
+ }
+
+ /**
+ * Fail an acquisition that re-enters the factory from inside a reload callback for the same purpose.
+ *
+ * <p>Consumer callbacks run while the source monitor is held (see
+ * {@link RegisteredSource#deliverToSubscribers}), so a callback that acquires the same purpose and
+ * blocks on the returned future deadlocks: the acquisition task needs the monitor its own caller is
+ * holding. The contract has always said not to do that, but a documented constraint that fails as a
+ * hang is a poor contract — this turns it into an immediate, self-describing error.
+ *
+ * <p>Only same-purpose re-entry is caught, because that is the case that cannot succeed. A callback
+ * acquiring a DIFFERENT purpose takes a different monitor and is merely inadvisable.
+ */
+ private static void rejectReentrantAcquisition(RegisteredSource source, TlsPurpose purpose) {
+ if (Thread.holdsLock(source)) {
+ throw new IllegalStateException("Re-entrant TLS acquisition for purpose " + purpose
+ + ": a reload callback must not call createInstance(...) for the purpose it is being "
+ + "delivered for and block on the result — the callback already holds that purpose's "
+ + "monitor, so the acquisition could never complete. Do the work outside the callback; "
+ + "the callback contract is a cheap, non-blocking store.");
+ }
+ }
Review Comment:
Follow-on from the call-site comment: the Javadoc here describes the contract precisely and correctly — "the acquisition task needs the monitor its own caller is holding" — but the method can never observe that state from where it is called, because it is called *after* the hop to the blocking executor.
Suggest turning it into a factory for the exception so the callers can use it pre-dispatch and return a failed future (the SPI contract forbids throwing synchronously from `createInstance`, so a `throw` on the caller thread isn't an option):
```java
private static IllegalStateException reentrantAcquisition(TlsPurpose purpose) {
return new IllegalStateException("Re-entrant TLS acquisition for purpose " + purpose
+ ": a reload callback must not call createInstance(...) for the purpose it is being "
+ "delivered for and block on the result — the callback already holds that purpose's "
+ "monitor, so the acquisition could never complete. Do the work outside the callback; "
+ "the callback contract is a cheap, non-blocking store.");
}
```
The message itself is good — it names the constraint and the remedy. It just needs to be reachable.
The `SubscriptionHandle` Javadoc at line 657 ("`rejectReentrantAcquisition` fails such an acquisition immediately with...") makes the same claim and should stay accurate once this is fixed.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/FileBasedTlsFactory.java:
##########
@@ -0,0 +1,835 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.util.ReferenceCountUtil;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import javax.net.ssl.SSLContext;
+import lombok.CustomLog;
+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.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsEndpoint;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The default, file-based {@link PulsarTlsFactory} (PIP-478).
+ *
+ * <p>Immutable after construction: the complete {@code TlsPurpose -> TlsPolicy} map and the
+ * factory-wide {@link FileBasedTlsFactorySettings} are fixed by the constructor and never mutated. The
+ * owning component (the v5 client builder, or {@code DefaultBrokerTlsFactory} on the server side)
+ * composes the final map before constructing the factory.
+ *
+ * <p>Natively supplies the Netty {@code SslContext} (on the configured engine — JDK or OpenSSL) and the
+ * JDK {@code SSLContext}; returns {@code empty()} for every other class (notably Jetty's
+ * {@code SslContextFactory.Server} and {@code SslContextFactory.Client}), which the framework synthesizes
+ * from the JDK {@code SSLContext}. It also
+ * returns {@code empty()} for the {@code javax.net.ssl.SSLParameters} companion (PIP-478): its engine policy
+ * (protocols, ciphers, client-auth mode, hostname verification) is baked natively into the Netty contexts it
+ * builds, so it exposes no separate baseline for the framework to overlay on those.
+ *
+ * <p>A JDK {@code SSLContext} cannot itself carry that policy — enabled protocols and cipher suites,
+ * algorithm constraints and the endpoint-identification algorithm are all per-engine {@code SSLParameters}
+ * settings — so the JDK context this factory returns is a <em>material carrier</em>: it holds the key and
+ * trust managers (built through the pinned providers) and nothing else. Every consumer of it applies the
+ * engine policy itself from the same {@link TlsPolicy}, which is what {@code JettyTlsFactory} does. A
+ * consumer that instead created engines straight from this {@code SSLContext} would get the provider defaults,
+ * so consumers must not do that.
+ *
+ * <p><b>Purpose resolution.</b> A request resolves the requested purpose directly against the configured
+ * {@code TlsPurpose -> TlsPolicy} map. When nothing is configured for the purpose, a {@code CLIENT}-role
+ * purpose resolves to the system default (OS trust store, no client certificate) and a {@code SERVER}-role
+ * purpose fails the request. A resolved-but-unbuildable request completes the future <em>exceptionally</em>
+ * — never {@code empty()}, which strictly means "unsupported {@code (purpose, class)} combination".
+ *
+ * <p><b>Rotation.</b> One {@link TlsMaterialSource} is shared per configured purpose. Server-side
+ * subscribers are pushed rebuilt instances by a background poll (interval from the settings, on the
+ * framework scheduler); client-side one-shot callers re-stat on each request and pick up rotation
+ * naturally. Because a re-stat consumes the source's change signal, an acquisition that observes a change
+ * first also fans it out to that purpose's subscribers, so a rotation is never swallowed by whoever happened
+ * to look first. A failed rebuild keeps the last-good instance, logs at WARN, and retries on the next
+ * change; a subscriber callback that throws is caught and logged, and the subscription stays live.
+ */
+@CustomLog
+public class FileBasedTlsFactory implements PulsarTlsFactory {
+
+ private final Map<TlsPurpose, RegisteredSource> registry;
+ private final FileBasedTlsFactorySettings settings;
+
+ private volatile TlsFactoryInitContext initContext;
+ private volatile TlsReloadMetrics metrics;
+ private volatile RegisteredSource systemDefaultSource;
+ private volatile ScheduledFuture<?> pollFuture;
+ private volatile boolean closed;
+ // Stands in for scheduleWithFixedDelay's no-overlap guarantee once the poll body is dispatched.
+ private final AtomicBoolean pollInFlight = new AtomicBoolean();
+
+ /**
+ * Construct an immutable file-based factory.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ this(policies, settings, Map.of());
+ }
+
+ /**
+ * Construct an immutable file-based factory that additionally folds an authentication plugin's TLS
+ * material over the configured file policy for the named purposes (the server-side {@code BROKER_CLIENT}
+ * fold — PIP-478). For a purpose present in {@code authMaterialSuppliers}, the supplier's
+ * {@code Authentication} material overrides the file policy's key/cert per
+ * {@link AuthProvidedMaterialSource} (auth-cert-wins); other purposes use the file policy unchanged.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ Objects.requireNonNull(policies, "policies must not be null");
+ this.settings = Objects.requireNonNull(settings, "settings must not be null");
+ Objects.requireNonNull(authMaterialSuppliers, "authMaterialSuppliers must not be null");
+ Map<TlsPurpose, RegisteredSource> built = new LinkedHashMap<>();
+ for (Map.Entry<TlsPurpose, TlsPolicy> entry : policies.entrySet()) {
+ TlsPurpose purpose = Objects.requireNonNull(entry.getKey(), "purpose key must not be null");
+ TlsPolicy policy = Objects.requireNonNull(entry.getValue(), "policy must not be null");
+ TlsMaterialSource fileSource = new TlsMaterialSource(policy);
+ Supplier<AuthenticationDataProvider> authSupplier = authMaterialSuppliers.get(purpose);
+ MaterialSource source = authSupplier == null
+ ? fileSource
+ : new AuthProvidedMaterialSource(fileSource, authSupplier);
+ built.put(purpose, new RegisteredSource(purpose, policy, source));
+ }
+ this.registry = Map.copyOf(built);
+ }
+
+ /**
+ * Adapt a component's broker-client {@link Authentication} to a per-refresh
+ * {@link AuthenticationDataProvider} supplier for use with the {@code BROKER_CLIENT} fold constructor.
+ * The supplier re-reads {@code getAuthData()} on each poll so credential rotation is observed; a checked
+ * {@link PulsarClientException} is rethrown unchecked and handled by the factory's keep-last-good poll.
+ *
+ * @param authentication the broker-client authentication plugin (never {@code null})
+ * @return a supplier of the plugin's current authentication data
+ */
+ public static Supplier<AuthenticationDataProvider> authMaterialSupplier(Authentication authentication) {
+ Objects.requireNonNull(authentication, "authentication must not be null");
+ return () -> {
+ try {
+ return resolveAuthData(authentication);
+ } catch (PulsarClientException e) {
+ throw new RuntimeException("Failed to obtain broker-client authentication TLS material", e);
+ }
+ };
+ }
+
+ // The BROKER_CLIENT TLS fold is host-agnostic — TLS key material does not vary by peer — so the
+ // host-less getAuthData() is exactly what we want; isolate its deprecation here.
+ @SuppressWarnings("deprecation")
+ private static AuthenticationDataProvider resolveAuthData(Authentication authentication)
+ throws PulsarClientException {
+ return authentication.getAuthData();
+ }
+
+ @Override
+ public CompletableFuture<Void> initialize(TlsFactoryInitContext context) {
+ try {
+ Objects.requireNonNull(context, "context must not be null");
+ // Required, not optional: every acquisition path in this factory reads files and parses key
+ // material. Without an executor the work would run inline on the caller's thread, which the SPI
+ // contract says may be a consumer event loop. Fail at wiring time rather than stalling a channel.
+ Objects.requireNonNull(context.blockingExecutor(),
+ "TlsFactoryInitContext.blockingExecutor() must not be null: FileBasedTlsFactory performs "
+ + "blocking file and key-material loading and must never run it on a consumer thread");
+ this.initContext = context;
+ // Cancel any poll scheduled by a prior initialize() so a second call does not orphan the first:
+ // the field is overwritten below and the old task would otherwise run forever.
+ ScheduledFuture<?> previousPoll = this.pollFuture;
+ if (previousPoll != null) {
+ previousPoll.cancel(false);
+ }
+ // Same reasoning for the metrics: a prior initialize() registered an observable gauge that stays
+ // registered on the meter until close(), so overwriting the field without closing it would leave
+ // an orphaned callback reporting stale per-purpose timestamps forever.
+ TlsReloadMetrics previousMetrics = this.metrics;
+ if (previousMetrics != null) {
+ previousMetrics.close();
+ }
+ this.metrics = TlsReloadMetrics.create(context.openTelemetry(), context.clock());
+ int interval = settings.refreshIntervalSeconds();
+ if (interval > 0 && context.scheduler() != null) {
+ // The scheduler only TRIGGERS the poll; the work runs on the blocking executor. The poll
+ // stats files, parses PEM/keystores and rebuilds contexts, which is exactly the work this
+ // method refuses to run without a blocking executor a few lines above — running it on a
+ // shared framework scheduler thread would occupy that thread for the duration, and with
+ // material on slow or network-backed storage that is not bounded by anything.
+ this.pollFuture = context.scheduler().scheduleWithFixedDelay(
+ this::triggerPoll, interval, interval, TimeUnit.SECONDS);
+ }
+ log.debug().attr("purposes", registry.keySet()).attr("refreshIntervalSeconds", interval)
+ .log("Initialized FileBasedTlsFactory");
+ return CompletableFuture.completedFuture(null);
+ } catch (Throwable t) {
+ return CompletableFuture.failedFuture(t);
+ }
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(TlsPurpose purpose, Class<T> instanceClass) {
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, TlsEndpoint endpoint, Class<T> instanceClass) {
+ // The default file-based factory serves purpose-scoped material and ignores the endpoint hint.
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, Class<T> instanceClass, Consumer<T> onLoadOrReload) {
+ if (onLoadOrReload == null) {
+ // SPI contract: argument-validation failures complete the returned future exceptionally — this
+ // method never throws on the calling thread.
+ return CompletableFuture.failedFuture(new NullPointerException("onLoadOrReload must not be null"));
+ }
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ rejectReentrantAcquisition(source, purpose);
Review Comment:
**Major — this guard sits inside the task that the deadlock prevents from running, so the original hang is unchanged.**
`rejectReentrantAcquisition(source, purpose)` is called *inside* the `runAsync` lambda, and `runAsync` (line 458) does `executor.execute(() -> task.call())` on `context.blockingExecutor()`. So the guard only ever evaluates after the hop to the executor:
- **Single-threaded `blockingExecutor`** (the realistic config): the reload callback is itself running on that pool thread, holding the source monitor. The nested `createInstance` queues its task *behind* the callback. The task never starts, so `Thread.holdsLock` is never evaluated at all, and the callback blocks forever on the future.
- **Multi-threaded `blockingExecutor`**: the task does start, but on a different thread from the one holding the monitor — `holdsLock(source)` returns `false`, the guard passes, and the task then blocks on `synchronized (source)` at line 240. Same deadlock, one frame later.
I verified this rather than reasoning about it. Taking `reentrantAcquisitionFromAReloadCallbackFailsLoudlyInsteadOfDeadlocking` (FileBasedTlsFactoryTest:719) verbatim — same body, same assertions — and initializing with `Executors.newSingleThreadExecutor()` instead of `directExecutor`, with `.get(5, SECONDS)` in place of `.join()` so it terminates:
```
PROBE callback ran on : tls-blocking
PROBE nested outcome : java.util.concurrent.TimeoutException
java.lang.AssertionError:
Expecting a throwable with root cause being an instance of:
java.lang.IllegalStateException
but current throwable has no cause.
Throwable that failed the check:
java.util.concurrent.TimeoutException
at FileBasedTlsFactory$Subscription.safeInvoke(FileBasedTlsFactory.java:767)
at FileBasedTlsFactory$Subscription.deliver(FileBasedTlsFactory.java:746)
at FileBasedTlsFactory.lambda$createInstance$1(FileBasedTlsFactory.java:251)
at FileBasedTlsFactory.lambda$runAsync$4(FileBasedTlsFactory.java:468)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(...)
```
No `IllegalStateException` — the acquisition simply never completes. The shipped test passes only because `factory(...)` initializes with `directExecutor = Runnable::run` (lines 95/114), which collapses `runAsync` back onto the callback thread; that is the single configuration in which `holdsLock(source)` can be true.
The check has to happen on the caller's thread, before dispatch:
```suggestion
RegisteredSource source = resolve(purpose);
if (Thread.holdsLock(source)) {
return CompletableFuture.failedFuture(reentrantAcquisition(purpose));
}
return runAsync(() -> {
```
(`resolve(purpose)` moving to the caller thread is fine — it's a registry lookup. Same change is needed in `createOneShot` at line 265-267.)
##########
pulsar-broker-common/src/test/java/org/apache/pulsar/jetty/tls/JettyTlsFactoryTest.java:
##########
@@ -0,0 +1,1341 @@
+/*
+ * 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.jetty.tls;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import com.google.common.io.Resources;
+import io.opentelemetry.api.OpenTelemetry;
+import java.io.File;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.net.Socket;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.FileTime;
+import java.security.KeyStore;
+import java.security.Principal;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+import java.time.Clock;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLParameters;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509ExtendedKeyManager;
+import org.apache.commons.io.FileUtils;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactory;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactorySettings;
+import org.apache.pulsar.common.util.tls.JdkSslContexts;
+import org.apache.pulsar.common.util.tls.PemReader;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.awaitility.Awaitility;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class JettyTlsFactoryTest {
+
+ /**
+ * Reload executor for tests: same-thread, so a delivery's reload has completed by the time the call
+ * that triggered it returns and the assertions below stay deterministic. That publish genuinely runs
+ * OFF the delivery thread when a real executor is supplied has its own test
+ * ({@link #rotationReloadRunsOnTheSuppliedExecutorNotTheDeliveryThread()}).
+ */
+ private static final Executor SAME_THREAD = Runnable::run;
+
+ private static final String CA = resource("certificate-authority/certs/ca.cert.pem");
+ private static final String BROKER_CERT = resource("certificate-authority/server-keys/broker.cert.pem");
+ private static final String BROKER_KEY = resource("certificate-authority/server-keys/broker.key-pk8.pem");
+ private static final String PROXY_CERT = resource("certificate-authority/server-keys/proxy.cert.pem");
+ private static final String PROXY_KEY = resource("certificate-authority/server-keys/proxy.key-pk8.pem");
+ // Client certificates (clientAuth EKU) trusted by the shared CA above.
+ private static final String TRUSTED_CLIENT_CERT = resource("certificate-authority/client-keys/admin.cert.pem");
+ private static final String TRUSTED_CLIENT_KEY = resource("certificate-authority/client-keys/admin.key-pk8.pem");
+ private static final String USER1_CLIENT_CERT = resource("certificate-authority/client-keys/user1.cert.pem");
+ private static final String USER1_CLIENT_KEY = resource("certificate-authority/client-keys/user1.key-pk8.pem");
+ // A self-signed client certificate NOT signed by the shared CA (from a separate my-ca root).
+ private static final String UNTRUSTED_CLIENT_CERT = resource("ssl/my-ca/client-ca.pem");
+ private static final String UNTRUSTED_CLIENT_KEY = resource("ssl/my-ca/client-key.pem");
+
+ private ScheduledExecutorService scheduler;
+ private Path tempDir;
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ scheduler = Executors.newSingleThreadScheduledExecutor();
+ tempDir = Files.createTempDirectory("pip478-jetty-");
+ Files.copy(Paths.get(CA), tempDir.resolve("ca.pem"), StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(BROKER_CERT), tempDir.resolve("cert.pem"), StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(BROKER_KEY), tempDir.resolve("key.pem"), StandardCopyOption.REPLACE_EXISTING);
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown() throws Exception {
+ scheduler.shutdownNow();
+ if (tempDir != null) {
+ FileUtils.deleteDirectory(tempDir.toFile());
+ }
+ }
+
+ @Test
+ public void reloadingServerFactoryServesRotatedCertificateToNewConnections() throws Exception {
+ FileBasedTlsFactory factory = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().refreshIntervalSeconds(1).build());
+ factory.initialize(initContext()).join();
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+
+ Server server = new Server();
+ ServerConnector connector = new ServerConnector(server, reloadable.sslContextFactory());
+ connector.setPort(0);
+ server.setConnectors(new ServerConnector[] {connector});
+ server.start();
+ try {
+ SSLContext clientContext = JdkSslContexts.createSslContext(false,
+ PemReader.loadCertificatesFromPemFile(CA), null, null);
+ int port = connector.getLocalPort();
+
+ BigInteger initialSerial = serverCertSerial(clientContext, port);
+ assertThat(initialSerial).isEqualTo(certSerial(BROKER_CERT));
+
+ // Rotate the server material to a different (proxy) certificate signed by the same CA.
+ Files.copy(Paths.get(PROXY_CERT), tempDir.resolve("cert.pem"), StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(PROXY_KEY), tempDir.resolve("key.pem"), StandardCopyOption.REPLACE_EXISTING);
+ long later = System.currentTimeMillis() + 5000;
+ Files.setLastModifiedTime(tempDir.resolve("cert.pem"), FileTime.fromMillis(later));
+ Files.setLastModifiedTime(tempDir.resolve("key.pem"), FileTime.fromMillis(later));
+
+ BigInteger proxySerial = certSerial(PROXY_CERT);
+ Awaitility.await().atMost(Duration.ofSeconds(15))
+ .until(() -> serverCertSerial(clientContext, port).equals(proxySerial));
+ assertThat(serverCertSerial(clientContext, port))
+ .as("new connections use the rotated certificate")
+ .isEqualTo(proxySerial).isNotEqualTo(initialSerial);
+ } finally {
+ reloadable.subscription().dispose();
+ server.stop();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478: a self-reloading {@link SslContextFactory.Client} presents rotated client-certificate
+ * material to new connections while the factory stays alive (mirrors the server rotation test).
+ */
+ @Test
+ public void reloadingClientFactoryPresentsRotatedClientCertOnNewConnections() throws Exception {
+ // Distinct filenames from the server rotation test's cert.pem/key.pem; these hold a client-auth
+ // certificate (the broker/proxy server certs carry a serverAuth-only EKU and cannot be presented as
+ // a client identity).
+ Path clientCert = tempDir.resolve("clientcert.pem");
+ Path clientKey = tempDir.resolve("clientkey.pem");
+ Files.copy(Paths.get(TRUSTED_CLIENT_CERT), clientCert, StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(TRUSTED_CLIENT_KEY), clientKey, StandardCopyOption.REPLACE_EXISTING);
+
+ FileBasedTlsFactory factory = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.BROKER_CLIENT, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ clientCert.toString(), clientKey.toString())),
+ FileBasedTlsFactorySettings.builder().refreshIntervalSeconds(1).build());
+ factory.initialize(initContext()).join();
+
+ JettyTlsFactory.ReloadableClientTls reloadable = JettyTlsFactory.createReloadingClientFactory(
+ factory, TlsPurpose.BROKER_CLIENT, SAME_THREAD, null, true);
+ SslContextFactory.Client clientFactory = reloadable.sslContextFactory();
+ clientFactory.start();
+ try {
+ assertThat(presentedClientCertSerial(clientFactory)).isEqualTo(certSerial(TRUSTED_CLIENT_CERT));
+
+ // Rotate the client identity to a different client certificate signed by the same CA.
+ Files.copy(Paths.get(USER1_CLIENT_CERT), clientCert, StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(USER1_CLIENT_KEY), clientKey, StandardCopyOption.REPLACE_EXISTING);
+ long later = System.currentTimeMillis() + 5000;
+ Files.setLastModifiedTime(clientCert, FileTime.fromMillis(later));
+ Files.setLastModifiedTime(clientKey, FileTime.fromMillis(later));
+
+ BigInteger rotatedSerial = certSerial(USER1_CLIENT_CERT);
+ Awaitility.await().atMost(Duration.ofSeconds(15))
+ .until(() -> presentedClientCertSerial(clientFactory).equals(rotatedSerial));
+ assertThat(presentedClientCertSerial(clientFactory))
+ .as("new connections present the rotated client certificate")
+ .isEqualTo(rotatedSerial).isNotEqualTo(certSerial(TRUSTED_CLIENT_CERT));
+ } finally {
+ clientFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ // Handshake the reloading client factory's current context against a client-auth-requiring server and
+ // return the serial of the client certificate the server observed.
+ private BigInteger presentedClientCertSerial(SslContextFactory.Client clientFactory) throws Exception {
+ SSLContext serverContext = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ try (SSLServerSocket serverSocket =
+ (SSLServerSocket) serverContext.getServerSocketFactory().createServerSocket(0)) {
+ serverSocket.setNeedClientAuth(true);
+ // TLSv1.2 so client auth completes symmetrically within the handshake (avoids the TLS 1.3
+ // post-handshake close race where the server closes before the client flushes its Finished).
+ serverSocket.setEnabledProtocols(new String[] {"TLSv1.2"});
+ serverSocket.setSoTimeout(15000);
+ int port = serverSocket.getLocalPort();
+ CompletableFuture<BigInteger> serverSaw = new CompletableFuture<>();
+ Thread serverThread = new Thread(() -> {
+ try (SSLSocket accepted = (SSLSocket) serverSocket.accept()) {
+ accepted.setSoTimeout(15000);
+ accepted.startHandshake();
+ X509Certificate peer = (X509Certificate) accepted.getSession().getPeerCertificates()[0];
+ serverSaw.complete(peer.getSerialNumber());
+ } catch (Throwable t) {
+ serverSaw.completeExceptionally(t);
+ }
+ });
+ serverThread.setDaemon(true);
+ serverThread.start();
+
+ SSLContext clientContext = clientFactory.getSslContext();
+ try (SSLSocket clientSocket =
+ (SSLSocket) clientContext.getSocketFactory().createSocket("localhost", port)) {
+ clientSocket.setEnabledProtocols(new String[] {"TLSv1.2"});
+ clientSocket.setSoTimeout(15000);
+ clientSocket.startHandshake();
+ }
+ return serverSaw.get(15, TimeUnit.SECONDS);
+ }
+ }
+
+ /**
+ * PIP-478: under optional client auth ({@code requireTrustedClientCert=false}), an <em>untrusted</em>
+ * client certificate is rejected at the web listener's handshake when {@code allowInsecureConnection=false}
+ * and accepted when it is true; a trusted client certificate is accepted in both cases.
+ */
+ @Test
+ public void optionalClientAuthScopesTrustAllToInsecureFlag() throws Exception {
+ // Secure (insecure=false): untrusted client cert is rejected, trusted client cert is accepted. The
+ // server aborts the handshake, surfaced to the client either as an SSLHandshakeException or, once the
+ // server has already sent its close/alert, as a broken-pipe SocketException — both are handshake
+ // failures.
+ try (JettyServer secure = startWebServer(false)) {
+ assertThatThrownBy(() -> handshakeWithClientCert(secure.port, UNTRUSTED_CLIENT_CERT, UNTRUSTED_CLIENT_KEY))
+ .as("an untrusted client cert must be rejected when insecure=false")
+ .isInstanceOf(IOException.class);
+ handshakeWithClientCert(secure.port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY);
+ }
+ // Insecure (insecure=true): both untrusted and trusted client certs are accepted (trust-all).
+ try (JettyServer insecure = startWebServer(true)) {
+ handshakeWithClientCert(insecure.port, UNTRUSTED_CLIENT_CERT, UNTRUSTED_CLIENT_KEY);
+ handshakeWithClientCert(insecure.port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY);
+ }
+ }
+
+ /**
+ * PIP-478: a factory that supplies its {@code SSLContext} together with an {@code SSLParameters} companion
+ * drives the synthesized server {@link SslContextFactory.Server} — its enabled protocols/ciphers and its
+ * client-auth mode are mapped from the companion, the latter authoritatively (merge rule 4).
+ */
+ @Test
+ public void serverFactoryMapsCompanionProtocolsAndClientAuth() throws Exception {
+ SSLParameters companion = new SSLParameters();
+ companion.setProtocols(new String[] {"TLSv1.2"});
+ companion.setCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});
+ companion.setNeedClientAuth(true);
+
+ FileBasedTlsFactory delegate = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().build());
+ CompanionFactory factory = new CompanionFactory(delegate, companion);
+ factory.initialize(initContext()).join();
+
+ // Consumer config asks for no protocol/cipher restriction and only optional client auth; the companion
+ // overrides all three.
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ try {
+ assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+ assertThat(sslContextFactory.getIncludeCipherSuites())
+ .containsExactly("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
+ assertThat(sslContextFactory.getNeedClientAuth()).isTrue();
+ } finally {
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * T4: the companion's protocol restriction and {@code needClientAuth} are not just mapped onto the
+ * synthesized Jetty {@link SslContextFactory.Server} getters — they decide a real handshake against a live
+ * server. A trusted client certificate over the allowed protocol succeeds; a client presenting no
+ * certificate is rejected (needClientAuth); a client offering only a disallowed protocol is rejected.
+ */
+ @Test
+ public void serverCompanionNeedClientAuthAndProtocolEnforcedAtHandshake() throws Exception {
+ SSLParameters companion = new SSLParameters();
+ companion.setProtocols(new String[] {"TLSv1.2"});
+ companion.setNeedClientAuth(true);
+
+ FileBasedTlsFactory delegate = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().build());
+ CompanionFactory factory = new CompanionFactory(delegate, companion);
+ factory.initialize(initContext()).join();
+
+ // Consumer config asks for no protocol restriction and only optional client auth; the companion wins.
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ Server server = new Server();
+ ServerConnector connector = new ServerConnector(server, reloadable.sslContextFactory());
+ connector.setPort(0);
+ server.setConnectors(new ServerConnector[] {connector});
+ server.start();
+ int port = connector.getLocalPort();
+ try {
+ // A trusted client certificate over the allowed protocol completes the handshake.
+ handshakeWithClientCert(port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY);
+ // The companion's needClientAuth rejects a client that presents no certificate.
+ assertThatThrownBy(() -> handshakeWithoutClientCert(port))
+ .as("needClientAuth from the companion rejects a client with no certificate")
+ .isInstanceOf(IOException.class);
+ // The companion's TLSv1.2-only restriction rejects a client offering only TLSv1.3.
+ assertThatThrownBy(() -> handshakeWithClientCert(port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY,
+ "TLSv1.3"))
+ .as("a TLSv1.3-only client cannot handshake with the companion-pinned TLSv1.2 server")
+ .isInstanceOf(IOException.class);
+ } finally {
+ reloadable.subscription().dispose();
+ server.stop();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 (pip-478.md:736): the {@code SSLParameters} companion is re-requested on <em>every</em>
+ * {@code SSLContext} delivery, not just at build time — so engine policy (here the server client-auth mode)
+ * rotates with material. A companion that flips {@code needClientAuth} on rotation must be reflected in the
+ * synthesized Jetty {@link SslContextFactory.Server} after the reload, and dropping the companion must
+ * revert client-auth to the consumer default rather than leaving the prior value stuck.
+ *
+ * <p>The companion is resolved on the <em>same single-thread scheduler</em> that runs the poll deliveries
+ * (see {@link CompanionFactory}'s executor): this reproduces the self-deadlock hazard a synchronous
+ * {@code join} on the delivery thread would hit. The reload path re-requests the companion asynchronously,
+ * so the rotation still applies (the assertions are awaited rather than read synchronously).
+ */
+ @Test
+ public void serverCompanionClientAuthRotatesWithMaterialOnReload() throws Exception {
+ // Build-time companion: no client auth. This overrides the consumer default (optional client auth).
+ SSLParameters noClientAuth = new SSLParameters();
+ noClientAuth.setNeedClientAuth(false);
+
+ FileBasedTlsFactory delegate = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().refreshIntervalSeconds(1).build());
+ // Dispatch companion creation onto the shared scheduler (the delivery thread), so a join inside the
+ // reload callback would deadlock; the async re-request must keep the rotation working.
+ CompanionFactory factory = new CompanionFactory(delegate, noClientAuth, scheduler);
+ factory.initialize(initContext()).join();
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ // Start standalone (no full Jetty server needed) so the reload path (isStarted()) runs on delivery.
+ sslContextFactory.start();
+ try {
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("the build-time companion (needClientAuth=false) is authoritative")
+ .isFalse();
+
+ // Flip the companion to require client auth, then rotate material to trigger an SSLContext delivery.
+ SSLParameters needClientAuth = new SSLParameters();
+ needClientAuth.setNeedClientAuth(true);
+ factory.setCompanion(needClientAuth);
+ rotateWebMaterial();
+
+ // The reload re-requests the companion and re-applies it under Jetty's lock, so the new
+ // needClientAuth takes effect on the synthesized factory.
+ Awaitility.await().atMost(Duration.ofSeconds(15)).until(sslContextFactory::getNeedClientAuth);
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("the companion is re-requested on delivery, so client-auth rotates with material")
+ .isTrue();
+
+ // Drop the companion entirely and rotate again: client-auth must revert to the consumer default
+ // (optional client auth => wantClientAuth, needClientAuth cleared) instead of staying stuck at need.
+ factory.setCompanion(null);
+ rotateWebMaterial();
+ Awaitility.await().atMost(Duration.ofSeconds(15)).until(() -> !sslContextFactory.getNeedClientAuth());
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("dropping the companion reverts needClientAuth to the consumer default")
+ .isFalse();
+ assertThat(sslContextFactory.getWantClientAuth())
+ .as("the consumer default (optional client auth) is restored")
+ .isTrue();
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 generation guard: two rotation companions that complete OUT OF ORDER must leave the NEWER
+ * rotation's context and baseline applied, never regressing to the older one. Each rotation captures a
+ * strictly increasing delivery generation; when the older rotation's companion completes last, its
+ * reload is dropped because a newer generation has already been published (mirroring
+ * {@code TlsContextAcquisition.SynthesizingSubscription}'s generation-guarded {@code publish}). Without the
+ * guard the stale companion would pin the synthesized {@link SslContextFactory.Server} to the older
+ * context/baseline until the next rotation.
+ */
+ @Test
+ public void serverRotationOutOfOrderCompanionKeepsNewerContextAndBaseline() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext contextA = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext contextB = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ ScriptableFactory factory = new ScriptableFactory(initial, null);
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ // Start standalone so the reload path (isStarted()) runs on each rotation delivery.
+ sslContextFactory.start();
+ try {
+ factory.deferCompanions();
+ // Two rotations: A (older, generation N) then B (newer, generation N+1).
+ factory.deliver(contextA);
+ factory.deliver(contextB);
+
+ SSLParameters baselineA = new SSLParameters();
+ baselineA.setProtocols(new String[] {"TLSv1.2"});
+ SSLParameters baselineB = new SSLParameters();
+ baselineB.setProtocols(new String[] {"TLSv1.3"});
+
+ // Complete the NEWER rotation's companion first, then the older one; the generation guard must
+ // drop the stale (older) result so the newer context/baseline stays applied.
+ factory.completeCompanion(1, baselineB);
+ factory.completeCompanion(0, baselineA);
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(sslContextFactory.getIncludeProtocols())
+ .as("the newer rotation's baseline wins despite the older companion completing last")
+ .containsExactly("TLSv1.3");
+ assertThat(sslContextFactory.getSslContext())
+ .as("the newer rotation's context stays pinned")
+ .isSameAs(contextB);
+ });
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 last-good retention: a rotation whose companion re-request fails transiently must retain the
+ * last successfully-resolved baseline (seeded from the build-time companion) rather than downgrading to
+ * consumer defaults. Here the build companion pins TLSv1.2 and {@code needClientAuth}; the rotation's
+ * companion then fails, and the reload must still apply the rotated context while keeping client-auth and
+ * the protocol restriction — the guarantee {@code SynthesizingSubscription} provides via its retained
+ * {@code lastBaseline}. Without it, the failed companion would silently drop client-auth/protocols.
+ */
+ @Test
+ public void serverRotationCompanionFailureRetainsLastGoodBaseline() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ SSLParameters lastGood = new SSLParameters();
+ lastGood.setProtocols(new String[] {"TLSv1.2"});
+ lastGood.setNeedClientAuth(true);
+ ScriptableFactory factory = new ScriptableFactory(initial, lastGood);
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ sslContextFactory.start();
+ try {
+ // The build-time companion is authoritative and seeds the retained last-good baseline.
+ assertThat(sslContextFactory.getNeedClientAuth()).isTrue();
+ assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+
+ factory.deferCompanions();
+ // Rotate material; the companion re-request for this rotation fails transiently.
+ factory.deliver(rotated);
+ factory.failCompanion(0, new IllegalStateException("companion temporarily unavailable"));
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(sslContextFactory.getSslContext())
+ .as("the rotated context is applied even though the companion failed")
+ .isSameAs(rotated);
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("a transient companion failure retains the last-good client-auth")
+ .isTrue();
+ assertThat(sslContextFactory.getIncludeProtocols())
+ .as("a transient companion failure retains the last-good protocol restriction")
+ .containsExactly("TLSv1.2");
+ });
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 companion revert, cipher suites: a companion that pins cipher suites on one delivery and drops them
+ * on the next must revert to the consumer default (here: no restriction) rather than leaving the stale
+ * allowlist pinned on the long-lived {@link SslContextFactory.Server}, which persists setter state across
+ * {@code reload()}. This is the same guarantee already covered for client-auth in
+ * {@link #serverCompanionClientAuthRotatesWithMaterialOnReload}, extended to the cipher/protocol members.
+ */
+ @Test
+ public void serverDroppedCompanionRevertsCipherSuitesToConsumerDefault() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ SSLParameters buildCompanion = new SSLParameters();
+ buildCompanion.setCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});
+ buildCompanion.setProtocols(new String[] {"TLSv1.2"});
+ ScriptableFactory factory = new ScriptableFactory(initial, buildCompanion);
+
+ // The consumer configures neither ciphers nor protocols, so the defaults are "no cipher restriction" and
+ // the {TLSv1.3, TLSv1.2} protocol floor.
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ sslContextFactory.start();
+ try {
+ assertThat(sslContextFactory.getIncludeCipherSuites())
+ .containsExactly("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
+ assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+
+ // Rotate with a companion that supplies nothing at all (empty()), modelling a delivery that
+ // legitimately drops the previously pinned members.
+ factory.deferCompanions();
+ factory.deliver(rotated);
+ factory.completeCompanion(0, null);
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(sslContextFactory.getIncludeCipherSuites())
+ .as("a dropped companion reverts cipher suites to the consumer default (unrestricted)")
+ .isEmpty();
+ assertThat(sslContextFactory.getIncludeProtocols())
+ .as("a dropped companion reverts protocols to the consumer default floor")
+ .containsExactlyInAnyOrder("TLSv1.3", "TLSv1.2");
+ });
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /** The client path is symmetric: a dropped companion must not leave a stale cipher allowlist pinned. */
+ @Test
+ public void clientDroppedCompanionRevertsCipherSuitesToConsumerDefault() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, USER1_CLIENT_CERT, USER1_CLIENT_KEY, null);
+ SSLParameters buildCompanion = new SSLParameters();
+ buildCompanion.setCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});
+ buildCompanion.setProtocols(new String[] {"TLSv1.2"});
+ ScriptableFactory factory = new ScriptableFactory(initial, buildCompanion);
+
+ JettyTlsFactory.ReloadableClientTls reloadable = JettyTlsFactory.createReloadingClientFactory(
+ factory, TlsPurpose.BROKER_CLIENT, SAME_THREAD, null, true);
+ SslContextFactory.Client clientFactory = reloadable.sslContextFactory();
+ clientFactory.start();
+ try {
+ assertThat(clientFactory.getIncludeCipherSuites())
+ .containsExactly("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
+ assertThat(clientFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+
+ factory.deferCompanions();
+ factory.deliver(rotated);
+ factory.completeCompanion(0, null);
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(clientFactory.getIncludeCipherSuites())
+ .as("a dropped companion reverts cipher suites to the consumer default (unrestricted)")
+ .isEmpty();
+ assertThat(clientFactory.getIncludeProtocols())
+ .as("a dropped companion reverts protocols to the consumer default floor")
+ .containsExactlyInAnyOrder("TLSv1.3", "TLSv1.2");
+ });
+ } finally {
+ clientFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478: a rotation delivered BEFORE the connector starts must still refresh the companion. Only the very
+ * first (pre-fetched, synchronous) delivery reuses the build-time baseline; a later delivery that lands while
+ * the factory is still unstarted re-requests the companion and applies it directly (Jetty's {@code reload()}
+ * is for a live factory), so the started factory runs the rotation's engine policy — protocols, cipher suites
+ * and client-auth — rather than the stale build-time one.
+ */
+ /**
+ * The reload must not run on the thread that delivered the rotation.
+ *
+ * <p>For the default factory the companion request completes synchronously — {@code SSLParameters} is
+ * an unsupported class, so {@code createInstance} returns an already-completed future — which means a
+ * plain {@code whenComplete} would run the whole Jetty reload inline, on a delivery thread that is
+ * inside the factory's {@code synchronized} fan-out. That put the source monitor at the head of a
+ * source -> coordinator -> Jetty lock chain and broke the delivery contract's "cheap non-blocking
+ * store". Dispatching to the supplied executor is what keeps that from happening.
+ */
+ @Test
+ public void rotationReloadRunsOnTheSuppliedExecutorNotTheDeliveryThread() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ ScriptableFactory factory = new ScriptableFactory(initial, null);
+ ExecutorService reloadExecutor = Executors.newSingleThreadExecutor(r -> new Thread(r, "reload-executor"));
+ try {
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, reloadExecutor, null, false, false, null, null);
+ SslContextFactory.Server target = reloadable.sslContextFactory();
+ target.start();
+
+ AtomicReference<String> reloadThread = new AtomicReference<>();
+ Thread deliveringThread = new Thread(() -> factory.deliver(rotated), "delivery-thread");
+ // Capture the thread the applied context lands on by observing the factory after the reload.
+ deliveringThread.start();
+ deliveringThread.join(TimeUnit.SECONDS.toMillis(10));
+
+ Awaitility.await().atMost(Duration.ofSeconds(10))
+ .untilAsserted(() -> assertThat(target.getSslContext()).isSameAs(rotated));
+ reloadExecutor.submit(() -> reloadThread.set(Thread.currentThread().getName()))
+ .get(10, TimeUnit.SECONDS);
+
+ assertThat(reloadThread.get()).as("the reload executor is the one that ran publish")
+ .isEqualTo("reload-executor");
+ assertThat(deliveringThread.isAlive())
+ .as("the delivery thread was not held for the duration of the reload").isFalse();
Review Comment:
**Moderate — this test cannot fail against the implementation it is guarding.** Both assertions are tautologies:
- Line 650-654: `reloadExecutor.submit(...)` is a *new* task submitted after the reload already completed, on a single-thread executor whose thread is named `reload-executor`. It reports `"reload-executor"` no matter which thread ran `publish`. It observes the executor's own naming, not the reload's placement.
- Line 655-656: `deliveringThread.isAlive()` is false because `join(10s)` on line 646 already waited for it. The delivery thread's body is `factory.deliver(rotated)` and nothing keeps it alive past that; it would be dead here even if the reload had run entirely inline on it.
I mutation-tested this. Reverting the fix at JettyTlsFactory:598-600 back to the pre-fix inline form:
```java
factory.createInstance(purpose, SSLParameters.class).whenComplete((companion, err) ->
publish(newContext, err != null ? null : extractBaseline(companion), generation, err == null));
```
`./gradlew :pulsar-broker-common:test --tests "org.apache.pulsar.jetty.tls.JettyTlsFactoryTest"` → **17/17 passing, `rotationReloadRunsOnTheSuppliedExecutorNotTheDeliveryThread` green in 0.124s** — identical to the unmutated baseline. Nothing in the class detects the regression.
To actually observe it, capture the thread from *inside* the reload rather than after it. `ScriptableFactory` controls when the companion future completes, so gating on that works: pause a `GatedExecutor` (the pattern already used in `FileBasedTlsFactoryTest`), deliver, assert the delivery thread has already returned *while the reload is still pending*, then release and assert the applied context. That distinguishes dispatch from inline; the current version doesn't.
Worth noting because this is the assertion protecting the `source -> coordinator -> Jetty` lock-chain fix — the one thing in this area that hangs a broker if it regresses.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/JettyTlsFactory.java:
##########
@@ -0,0 +1,637 @@
+/*
+ * 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.jetty.tls;
+
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.tls.impl.TlsContexts;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * The framework's Jetty integration for the PIP-478 TLS SPI. Both {@link SslContextFactory.Server} and
+ * {@link SslContextFactory.Client} are well-known SPI classes: the framework first asks the
+ * {@link PulsarTlsFactory} to supply one natively (a custom factory may build and own it, reload
+ * included); only when the factory returns {@code empty()} for the Jetty class does the framework
+ * synthesize a <em>vanilla</em> (never subclassed) one from an {@code SSLContext} subscription. The
+ * default {@code FileBasedTlsFactory} returns {@code empty()} for the Jetty classes, so the synthesized
+ * path is the usual one.
+ *
+ * <p><b>Factory-supplied (native) instances.</b> When the factory supplies the Jetty factory directly it
+ * is handed back <em>unstarted</em> (the connector / {@code HttpClient} starts it), is the factory's
+ * same-instance-per-purpose, and the factory owns its reload on material rotation. The framework only
+ * holds the returned {@link TlsHandle} for disposal and never drives {@code setSslContext}/{@code reload}
+ * or overlays consumer configuration on such an instance.
+ *
+ * <p>This deliberately abandons the unsound {@code getSslContext()} override of the superseded PIP-337
+ * {@code JettySslContextFactory}. Instead it uses
+ * Jetty's documented hot-reload API — the same one {@code KeyStoreScanner} uses: an {@code SSLContext}
+ * subscription drives {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each
+ * later delivery (once started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context and re-selects
+ * protocols/ciphers. Existing connections keep their sessions; new connections use the new context.
+ *
+ * <p><b>{@code SSLParameters} companion (PIP-478).</b> Because these are synthesized paths (the factory
+ * returned {@code empty()} for the Jetty class and supplies only the {@code SSLContext}), the framework also
+ * asks the factory for its optional {@code javax.net.ssl.SSLParameters} companion — the engine-level baseline
+ * a bare {@code SSLContext} cannot express — and maps its non-null members onto the Jetty setters: enabled
+ * protocols ({@link SslContextFactory#setIncludeProtocols}) and cipher suites
+ * ({@link SslContextFactory#setIncludeCipherSuites}), and (server side, merge rule 4) the authoritative
+ * client-auth mode ({@link SslContextFactory.Server#setNeedClientAuth} /
+ * {@link SslContextFactory.Server#setWantClientAuth}). The initial companion is overlaid before start (at build
+ * time); on each subsequent <em>rotation</em> delivery it is re-requested <em>asynchronously</em> — the reload
+ * callback composes {@code createInstance(purpose, SSLParameters.class)} with {@code whenComplete} and only then
+ * calls {@code reload(...)}, so engine policy rotates with material (pip-478.md:736) yet the companion is
+ * <b>never joined on the delivery thread</b>. Joining there would self-deadlock a custom factory that dispatches
+ * companion creation to the same single-thread scheduler that runs the poll delivery — the exact hazard
+ * {@code TlsContextAcquisition.SynthesizingSubscription} avoids by composing the companion asynchronously.
+ *
+ * <p>Because those asynchronous re-requests complete on arbitrary threads and may finish out of order, the
+ * synthesized reload mirrors the two ordering guarantees of {@code SynthesizingSubscription} (see
+ * {@code JettyReloadCoordinator}): each delivery captures a strictly increasing <em>generation</em> and applies
+ * its {@code reload(...)} only while that generation is still the latest, so a companion superseded by a newer
+ * rotation is dropped rather than pinning the listener to a stale context/baseline; and the last
+ * successfully-resolved companion is <em>retained</em> (seeded from the build-time baseline) so a transient
+ * companion-fetch failure during rotation reloads with that last-good baseline rather than downgrading engine
+ * policy (protocols/ciphers and, server side, client-auth) to consumer defaults. Consumer defaults are still
+ * re-applied <em>in full</em> first inside every {@code reload(...)} lambda — protocols, cipher suites and, server
+ * side, client-auth are each re-pinned or cleared unconditionally, since the long-lived {@code SslContextFactory}
+ * persists setter state across {@code reload()} — so any companion member legitimately dropped by a newer delivery
+ * reverts to the consumer default rather than staying stuck from the previous companion.
+ * {@code empty()} leaves the consumer's configuration in force, exactly as before.
+ */
+@CustomLog
+public final class JettyTlsFactory {
+
+ static {
+ // Install Conscrypt process-wide, if present, before any TLS object is built here. Jetty resolves a
+ // JSSE provider by name, so the provider has to be registered by the time a factory is configured.
+ JcaProviders.ensureConscryptRegistered();
+ }
+
+ private JettyTlsFactory() {
+ }
+
+ /**
+ * A Jetty server factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the web service stops.
+ *
+ * @param sslContextFactory the (unstarted) Jetty server factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableServerTls(SslContextFactory.Server sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * A Jetty client factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the owning HTTP client
+ * / servlet is destroyed.
+ *
+ * @param sslContextFactory the (unstarted) Jetty client factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableClientTls(SslContextFactory.Client sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * Build a self-reloading {@link SslContextFactory.Server} for a purpose, handed back <em>unstarted</em>
+ * (Jetty starts it with the connector lifecycle) with its initial {@code SSLContext} already set.
+ *
+ * <p><b>Must not be called from the factory's blocking executor.</b> This builder blocks on the
+ * factory's acquisition, and the default factory dispatches acquisitions to
+ * {@code TlsFactoryInitContext.blockingExecutor()} — so calling it from that executor waits on work
+ * queued behind itself, which deadlocks when the executor is single-threaded. Call it from the owning
+ * component's startup thread.
+ *
+ * @param factory the TLS factory to subscribe to
+ * @param purpose the server purpose (e.g. {@link TlsPurpose#WEB})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param requireTrustedClientCert whether to require (vs. request) a trusted client certificate
+ * @param allowInsecureConnection whether an untrusted client cert is accepted under optional client auth
+ * @param ciphers enabled cipher suites, or {@code null} for defaults
+ * @param protocols enabled protocols, or {@code null} for defaults
+ * @return the reloading factory and its subscription handle
Review Comment:
Nit: `reloadExecutor` is missing from the `@param` list (it's the third parameter, line 152). Given the class comment at line 525-528 explains exactly why inline execution is unsafe, the builder Javadoc is the place a caller will look for "what do I pass here, and can it be null?"
Same omission on `createReloadingClientFactory` (line 216-225 / parameter at line 228).
##########
pulsar-broker-common/src/test/java/org/apache/pulsar/jetty/tls/JettyTlsFactoryTest.java:
##########
@@ -0,0 +1,1341 @@
+/*
+ * 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.jetty.tls;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import com.google.common.io.Resources;
+import io.opentelemetry.api.OpenTelemetry;
+import java.io.File;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.net.Socket;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.FileTime;
+import java.security.KeyStore;
+import java.security.Principal;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+import java.time.Clock;
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLParameters;
+import javax.net.ssl.SSLServerSocket;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManagerFactory;
+import javax.net.ssl.X509ExtendedKeyManager;
+import org.apache.commons.io.FileUtils;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactory;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactorySettings;
+import org.apache.pulsar.common.util.tls.JdkSslContexts;
+import org.apache.pulsar.common.util.tls.PemReader;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.awaitility.Awaitility;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class JettyTlsFactoryTest {
+
+ /**
+ * Reload executor for tests: same-thread, so a delivery's reload has completed by the time the call
+ * that triggered it returns and the assertions below stay deterministic. That publish genuinely runs
+ * OFF the delivery thread when a real executor is supplied has its own test
+ * ({@link #rotationReloadRunsOnTheSuppliedExecutorNotTheDeliveryThread()}).
+ */
+ private static final Executor SAME_THREAD = Runnable::run;
+
+ private static final String CA = resource("certificate-authority/certs/ca.cert.pem");
+ private static final String BROKER_CERT = resource("certificate-authority/server-keys/broker.cert.pem");
+ private static final String BROKER_KEY = resource("certificate-authority/server-keys/broker.key-pk8.pem");
+ private static final String PROXY_CERT = resource("certificate-authority/server-keys/proxy.cert.pem");
+ private static final String PROXY_KEY = resource("certificate-authority/server-keys/proxy.key-pk8.pem");
+ // Client certificates (clientAuth EKU) trusted by the shared CA above.
+ private static final String TRUSTED_CLIENT_CERT = resource("certificate-authority/client-keys/admin.cert.pem");
+ private static final String TRUSTED_CLIENT_KEY = resource("certificate-authority/client-keys/admin.key-pk8.pem");
+ private static final String USER1_CLIENT_CERT = resource("certificate-authority/client-keys/user1.cert.pem");
+ private static final String USER1_CLIENT_KEY = resource("certificate-authority/client-keys/user1.key-pk8.pem");
+ // A self-signed client certificate NOT signed by the shared CA (from a separate my-ca root).
+ private static final String UNTRUSTED_CLIENT_CERT = resource("ssl/my-ca/client-ca.pem");
+ private static final String UNTRUSTED_CLIENT_KEY = resource("ssl/my-ca/client-key.pem");
+
+ private ScheduledExecutorService scheduler;
+ private Path tempDir;
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ scheduler = Executors.newSingleThreadScheduledExecutor();
+ tempDir = Files.createTempDirectory("pip478-jetty-");
+ Files.copy(Paths.get(CA), tempDir.resolve("ca.pem"), StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(BROKER_CERT), tempDir.resolve("cert.pem"), StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(BROKER_KEY), tempDir.resolve("key.pem"), StandardCopyOption.REPLACE_EXISTING);
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown() throws Exception {
+ scheduler.shutdownNow();
+ if (tempDir != null) {
+ FileUtils.deleteDirectory(tempDir.toFile());
+ }
+ }
+
+ @Test
+ public void reloadingServerFactoryServesRotatedCertificateToNewConnections() throws Exception {
+ FileBasedTlsFactory factory = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().refreshIntervalSeconds(1).build());
+ factory.initialize(initContext()).join();
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+
+ Server server = new Server();
+ ServerConnector connector = new ServerConnector(server, reloadable.sslContextFactory());
+ connector.setPort(0);
+ server.setConnectors(new ServerConnector[] {connector});
+ server.start();
+ try {
+ SSLContext clientContext = JdkSslContexts.createSslContext(false,
+ PemReader.loadCertificatesFromPemFile(CA), null, null);
+ int port = connector.getLocalPort();
+
+ BigInteger initialSerial = serverCertSerial(clientContext, port);
+ assertThat(initialSerial).isEqualTo(certSerial(BROKER_CERT));
+
+ // Rotate the server material to a different (proxy) certificate signed by the same CA.
+ Files.copy(Paths.get(PROXY_CERT), tempDir.resolve("cert.pem"), StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(PROXY_KEY), tempDir.resolve("key.pem"), StandardCopyOption.REPLACE_EXISTING);
+ long later = System.currentTimeMillis() + 5000;
+ Files.setLastModifiedTime(tempDir.resolve("cert.pem"), FileTime.fromMillis(later));
+ Files.setLastModifiedTime(tempDir.resolve("key.pem"), FileTime.fromMillis(later));
+
+ BigInteger proxySerial = certSerial(PROXY_CERT);
+ Awaitility.await().atMost(Duration.ofSeconds(15))
+ .until(() -> serverCertSerial(clientContext, port).equals(proxySerial));
+ assertThat(serverCertSerial(clientContext, port))
+ .as("new connections use the rotated certificate")
+ .isEqualTo(proxySerial).isNotEqualTo(initialSerial);
+ } finally {
+ reloadable.subscription().dispose();
+ server.stop();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478: a self-reloading {@link SslContextFactory.Client} presents rotated client-certificate
+ * material to new connections while the factory stays alive (mirrors the server rotation test).
+ */
+ @Test
+ public void reloadingClientFactoryPresentsRotatedClientCertOnNewConnections() throws Exception {
+ // Distinct filenames from the server rotation test's cert.pem/key.pem; these hold a client-auth
+ // certificate (the broker/proxy server certs carry a serverAuth-only EKU and cannot be presented as
+ // a client identity).
+ Path clientCert = tempDir.resolve("clientcert.pem");
+ Path clientKey = tempDir.resolve("clientkey.pem");
+ Files.copy(Paths.get(TRUSTED_CLIENT_CERT), clientCert, StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(TRUSTED_CLIENT_KEY), clientKey, StandardCopyOption.REPLACE_EXISTING);
+
+ FileBasedTlsFactory factory = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.BROKER_CLIENT, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ clientCert.toString(), clientKey.toString())),
+ FileBasedTlsFactorySettings.builder().refreshIntervalSeconds(1).build());
+ factory.initialize(initContext()).join();
+
+ JettyTlsFactory.ReloadableClientTls reloadable = JettyTlsFactory.createReloadingClientFactory(
+ factory, TlsPurpose.BROKER_CLIENT, SAME_THREAD, null, true);
+ SslContextFactory.Client clientFactory = reloadable.sslContextFactory();
+ clientFactory.start();
+ try {
+ assertThat(presentedClientCertSerial(clientFactory)).isEqualTo(certSerial(TRUSTED_CLIENT_CERT));
+
+ // Rotate the client identity to a different client certificate signed by the same CA.
+ Files.copy(Paths.get(USER1_CLIENT_CERT), clientCert, StandardCopyOption.REPLACE_EXISTING);
+ Files.copy(Paths.get(USER1_CLIENT_KEY), clientKey, StandardCopyOption.REPLACE_EXISTING);
+ long later = System.currentTimeMillis() + 5000;
+ Files.setLastModifiedTime(clientCert, FileTime.fromMillis(later));
+ Files.setLastModifiedTime(clientKey, FileTime.fromMillis(later));
+
+ BigInteger rotatedSerial = certSerial(USER1_CLIENT_CERT);
+ Awaitility.await().atMost(Duration.ofSeconds(15))
+ .until(() -> presentedClientCertSerial(clientFactory).equals(rotatedSerial));
+ assertThat(presentedClientCertSerial(clientFactory))
+ .as("new connections present the rotated client certificate")
+ .isEqualTo(rotatedSerial).isNotEqualTo(certSerial(TRUSTED_CLIENT_CERT));
+ } finally {
+ clientFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ // Handshake the reloading client factory's current context against a client-auth-requiring server and
+ // return the serial of the client certificate the server observed.
+ private BigInteger presentedClientCertSerial(SslContextFactory.Client clientFactory) throws Exception {
+ SSLContext serverContext = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ try (SSLServerSocket serverSocket =
+ (SSLServerSocket) serverContext.getServerSocketFactory().createServerSocket(0)) {
+ serverSocket.setNeedClientAuth(true);
+ // TLSv1.2 so client auth completes symmetrically within the handshake (avoids the TLS 1.3
+ // post-handshake close race where the server closes before the client flushes its Finished).
+ serverSocket.setEnabledProtocols(new String[] {"TLSv1.2"});
+ serverSocket.setSoTimeout(15000);
+ int port = serverSocket.getLocalPort();
+ CompletableFuture<BigInteger> serverSaw = new CompletableFuture<>();
+ Thread serverThread = new Thread(() -> {
+ try (SSLSocket accepted = (SSLSocket) serverSocket.accept()) {
+ accepted.setSoTimeout(15000);
+ accepted.startHandshake();
+ X509Certificate peer = (X509Certificate) accepted.getSession().getPeerCertificates()[0];
+ serverSaw.complete(peer.getSerialNumber());
+ } catch (Throwable t) {
+ serverSaw.completeExceptionally(t);
+ }
+ });
+ serverThread.setDaemon(true);
+ serverThread.start();
+
+ SSLContext clientContext = clientFactory.getSslContext();
+ try (SSLSocket clientSocket =
+ (SSLSocket) clientContext.getSocketFactory().createSocket("localhost", port)) {
+ clientSocket.setEnabledProtocols(new String[] {"TLSv1.2"});
+ clientSocket.setSoTimeout(15000);
+ clientSocket.startHandshake();
+ }
+ return serverSaw.get(15, TimeUnit.SECONDS);
+ }
+ }
+
+ /**
+ * PIP-478: under optional client auth ({@code requireTrustedClientCert=false}), an <em>untrusted</em>
+ * client certificate is rejected at the web listener's handshake when {@code allowInsecureConnection=false}
+ * and accepted when it is true; a trusted client certificate is accepted in both cases.
+ */
+ @Test
+ public void optionalClientAuthScopesTrustAllToInsecureFlag() throws Exception {
+ // Secure (insecure=false): untrusted client cert is rejected, trusted client cert is accepted. The
+ // server aborts the handshake, surfaced to the client either as an SSLHandshakeException or, once the
+ // server has already sent its close/alert, as a broken-pipe SocketException — both are handshake
+ // failures.
+ try (JettyServer secure = startWebServer(false)) {
+ assertThatThrownBy(() -> handshakeWithClientCert(secure.port, UNTRUSTED_CLIENT_CERT, UNTRUSTED_CLIENT_KEY))
+ .as("an untrusted client cert must be rejected when insecure=false")
+ .isInstanceOf(IOException.class);
+ handshakeWithClientCert(secure.port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY);
+ }
+ // Insecure (insecure=true): both untrusted and trusted client certs are accepted (trust-all).
+ try (JettyServer insecure = startWebServer(true)) {
+ handshakeWithClientCert(insecure.port, UNTRUSTED_CLIENT_CERT, UNTRUSTED_CLIENT_KEY);
+ handshakeWithClientCert(insecure.port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY);
+ }
+ }
+
+ /**
+ * PIP-478: a factory that supplies its {@code SSLContext} together with an {@code SSLParameters} companion
+ * drives the synthesized server {@link SslContextFactory.Server} — its enabled protocols/ciphers and its
+ * client-auth mode are mapped from the companion, the latter authoritatively (merge rule 4).
+ */
+ @Test
+ public void serverFactoryMapsCompanionProtocolsAndClientAuth() throws Exception {
+ SSLParameters companion = new SSLParameters();
+ companion.setProtocols(new String[] {"TLSv1.2"});
+ companion.setCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});
+ companion.setNeedClientAuth(true);
+
+ FileBasedTlsFactory delegate = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().build());
+ CompanionFactory factory = new CompanionFactory(delegate, companion);
+ factory.initialize(initContext()).join();
+
+ // Consumer config asks for no protocol/cipher restriction and only optional client auth; the companion
+ // overrides all three.
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ try {
+ assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+ assertThat(sslContextFactory.getIncludeCipherSuites())
+ .containsExactly("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
+ assertThat(sslContextFactory.getNeedClientAuth()).isTrue();
+ } finally {
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * T4: the companion's protocol restriction and {@code needClientAuth} are not just mapped onto the
+ * synthesized Jetty {@link SslContextFactory.Server} getters — they decide a real handshake against a live
+ * server. A trusted client certificate over the allowed protocol succeeds; a client presenting no
+ * certificate is rejected (needClientAuth); a client offering only a disallowed protocol is rejected.
+ */
+ @Test
+ public void serverCompanionNeedClientAuthAndProtocolEnforcedAtHandshake() throws Exception {
+ SSLParameters companion = new SSLParameters();
+ companion.setProtocols(new String[] {"TLSv1.2"});
+ companion.setNeedClientAuth(true);
+
+ FileBasedTlsFactory delegate = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().build());
+ CompanionFactory factory = new CompanionFactory(delegate, companion);
+ factory.initialize(initContext()).join();
+
+ // Consumer config asks for no protocol restriction and only optional client auth; the companion wins.
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ Server server = new Server();
+ ServerConnector connector = new ServerConnector(server, reloadable.sslContextFactory());
+ connector.setPort(0);
+ server.setConnectors(new ServerConnector[] {connector});
+ server.start();
+ int port = connector.getLocalPort();
+ try {
+ // A trusted client certificate over the allowed protocol completes the handshake.
+ handshakeWithClientCert(port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY);
+ // The companion's needClientAuth rejects a client that presents no certificate.
+ assertThatThrownBy(() -> handshakeWithoutClientCert(port))
+ .as("needClientAuth from the companion rejects a client with no certificate")
+ .isInstanceOf(IOException.class);
+ // The companion's TLSv1.2-only restriction rejects a client offering only TLSv1.3.
+ assertThatThrownBy(() -> handshakeWithClientCert(port, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY,
+ "TLSv1.3"))
+ .as("a TLSv1.3-only client cannot handshake with the companion-pinned TLSv1.2 server")
+ .isInstanceOf(IOException.class);
+ } finally {
+ reloadable.subscription().dispose();
+ server.stop();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 (pip-478.md:736): the {@code SSLParameters} companion is re-requested on <em>every</em>
+ * {@code SSLContext} delivery, not just at build time — so engine policy (here the server client-auth mode)
+ * rotates with material. A companion that flips {@code needClientAuth} on rotation must be reflected in the
+ * synthesized Jetty {@link SslContextFactory.Server} after the reload, and dropping the companion must
+ * revert client-auth to the consumer default rather than leaving the prior value stuck.
+ *
+ * <p>The companion is resolved on the <em>same single-thread scheduler</em> that runs the poll deliveries
+ * (see {@link CompanionFactory}'s executor): this reproduces the self-deadlock hazard a synchronous
+ * {@code join} on the delivery thread would hit. The reload path re-requests the companion asynchronously,
+ * so the rotation still applies (the assertions are awaited rather than read synchronously).
+ */
+ @Test
+ public void serverCompanionClientAuthRotatesWithMaterialOnReload() throws Exception {
+ // Build-time companion: no client auth. This overrides the consumer default (optional client auth).
+ SSLParameters noClientAuth = new SSLParameters();
+ noClientAuth.setNeedClientAuth(false);
+
+ FileBasedTlsFactory delegate = new FileBasedTlsFactory(
+ Map.of(TlsPurpose.WEB, TlsPolicy.pem(tempDir.resolve("ca.pem").toString(),
+ tempDir.resolve("cert.pem").toString(), tempDir.resolve("key.pem").toString())),
+ FileBasedTlsFactorySettings.builder().refreshIntervalSeconds(1).build());
+ // Dispatch companion creation onto the shared scheduler (the delivery thread), so a join inside the
+ // reload callback would deadlock; the async re-request must keep the rotation working.
+ CompanionFactory factory = new CompanionFactory(delegate, noClientAuth, scheduler);
+ factory.initialize(initContext()).join();
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ // Start standalone (no full Jetty server needed) so the reload path (isStarted()) runs on delivery.
+ sslContextFactory.start();
+ try {
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("the build-time companion (needClientAuth=false) is authoritative")
+ .isFalse();
+
+ // Flip the companion to require client auth, then rotate material to trigger an SSLContext delivery.
+ SSLParameters needClientAuth = new SSLParameters();
+ needClientAuth.setNeedClientAuth(true);
+ factory.setCompanion(needClientAuth);
+ rotateWebMaterial();
+
+ // The reload re-requests the companion and re-applies it under Jetty's lock, so the new
+ // needClientAuth takes effect on the synthesized factory.
+ Awaitility.await().atMost(Duration.ofSeconds(15)).until(sslContextFactory::getNeedClientAuth);
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("the companion is re-requested on delivery, so client-auth rotates with material")
+ .isTrue();
+
+ // Drop the companion entirely and rotate again: client-auth must revert to the consumer default
+ // (optional client auth => wantClientAuth, needClientAuth cleared) instead of staying stuck at need.
+ factory.setCompanion(null);
+ rotateWebMaterial();
+ Awaitility.await().atMost(Duration.ofSeconds(15)).until(() -> !sslContextFactory.getNeedClientAuth());
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("dropping the companion reverts needClientAuth to the consumer default")
+ .isFalse();
+ assertThat(sslContextFactory.getWantClientAuth())
+ .as("the consumer default (optional client auth) is restored")
+ .isTrue();
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 generation guard: two rotation companions that complete OUT OF ORDER must leave the NEWER
+ * rotation's context and baseline applied, never regressing to the older one. Each rotation captures a
+ * strictly increasing delivery generation; when the older rotation's companion completes last, its
+ * reload is dropped because a newer generation has already been published (mirroring
+ * {@code TlsContextAcquisition.SynthesizingSubscription}'s generation-guarded {@code publish}). Without the
+ * guard the stale companion would pin the synthesized {@link SslContextFactory.Server} to the older
+ * context/baseline until the next rotation.
+ */
+ @Test
+ public void serverRotationOutOfOrderCompanionKeepsNewerContextAndBaseline() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext contextA = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext contextB = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ ScriptableFactory factory = new ScriptableFactory(initial, null);
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ // Start standalone so the reload path (isStarted()) runs on each rotation delivery.
+ sslContextFactory.start();
+ try {
+ factory.deferCompanions();
+ // Two rotations: A (older, generation N) then B (newer, generation N+1).
+ factory.deliver(contextA);
+ factory.deliver(contextB);
+
+ SSLParameters baselineA = new SSLParameters();
+ baselineA.setProtocols(new String[] {"TLSv1.2"});
+ SSLParameters baselineB = new SSLParameters();
+ baselineB.setProtocols(new String[] {"TLSv1.3"});
+
+ // Complete the NEWER rotation's companion first, then the older one; the generation guard must
+ // drop the stale (older) result so the newer context/baseline stays applied.
+ factory.completeCompanion(1, baselineB);
+ factory.completeCompanion(0, baselineA);
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(sslContextFactory.getIncludeProtocols())
+ .as("the newer rotation's baseline wins despite the older companion completing last")
+ .containsExactly("TLSv1.3");
+ assertThat(sslContextFactory.getSslContext())
+ .as("the newer rotation's context stays pinned")
+ .isSameAs(contextB);
+ });
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 last-good retention: a rotation whose companion re-request fails transiently must retain the
+ * last successfully-resolved baseline (seeded from the build-time companion) rather than downgrading to
+ * consumer defaults. Here the build companion pins TLSv1.2 and {@code needClientAuth}; the rotation's
+ * companion then fails, and the reload must still apply the rotated context while keeping client-auth and
+ * the protocol restriction — the guarantee {@code SynthesizingSubscription} provides via its retained
+ * {@code lastBaseline}. Without it, the failed companion would silently drop client-auth/protocols.
+ */
+ @Test
+ public void serverRotationCompanionFailureRetainsLastGoodBaseline() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ SSLParameters lastGood = new SSLParameters();
+ lastGood.setProtocols(new String[] {"TLSv1.2"});
+ lastGood.setNeedClientAuth(true);
+ ScriptableFactory factory = new ScriptableFactory(initial, lastGood);
+
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ sslContextFactory.start();
+ try {
+ // The build-time companion is authoritative and seeds the retained last-good baseline.
+ assertThat(sslContextFactory.getNeedClientAuth()).isTrue();
+ assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+
+ factory.deferCompanions();
+ // Rotate material; the companion re-request for this rotation fails transiently.
+ factory.deliver(rotated);
+ factory.failCompanion(0, new IllegalStateException("companion temporarily unavailable"));
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(sslContextFactory.getSslContext())
+ .as("the rotated context is applied even though the companion failed")
+ .isSameAs(rotated);
+ assertThat(sslContextFactory.getNeedClientAuth())
+ .as("a transient companion failure retains the last-good client-auth")
+ .isTrue();
+ assertThat(sslContextFactory.getIncludeProtocols())
+ .as("a transient companion failure retains the last-good protocol restriction")
+ .containsExactly("TLSv1.2");
+ });
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478 companion revert, cipher suites: a companion that pins cipher suites on one delivery and drops them
+ * on the next must revert to the consumer default (here: no restriction) rather than leaving the stale
+ * allowlist pinned on the long-lived {@link SslContextFactory.Server}, which persists setter state across
+ * {@code reload()}. This is the same guarantee already covered for client-auth in
+ * {@link #serverCompanionClientAuthRotatesWithMaterialOnReload}, extended to the cipher/protocol members.
+ */
+ @Test
+ public void serverDroppedCompanionRevertsCipherSuitesToConsumerDefault() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, BROKER_CERT, BROKER_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, PROXY_CERT, PROXY_KEY, null);
+ SSLParameters buildCompanion = new SSLParameters();
+ buildCompanion.setCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});
+ buildCompanion.setProtocols(new String[] {"TLSv1.2"});
+ ScriptableFactory factory = new ScriptableFactory(initial, buildCompanion);
+
+ // The consumer configures neither ciphers nor protocols, so the defaults are "no cipher restriction" and
+ // the {TLSv1.3, TLSv1.2} protocol floor.
+ JettyTlsFactory.ReloadableServerTls reloadable = JettyTlsFactory.createReloadingServerFactory(
+ factory, TlsPurpose.WEB, SAME_THREAD, null, false, false, null, null);
+ SslContextFactory.Server sslContextFactory = reloadable.sslContextFactory();
+ sslContextFactory.start();
+ try {
+ assertThat(sslContextFactory.getIncludeCipherSuites())
+ .containsExactly("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
+ assertThat(sslContextFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+
+ // Rotate with a companion that supplies nothing at all (empty()), modelling a delivery that
+ // legitimately drops the previously pinned members.
+ factory.deferCompanions();
+ factory.deliver(rotated);
+ factory.completeCompanion(0, null);
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(sslContextFactory.getIncludeCipherSuites())
+ .as("a dropped companion reverts cipher suites to the consumer default (unrestricted)")
+ .isEmpty();
+ assertThat(sslContextFactory.getIncludeProtocols())
+ .as("a dropped companion reverts protocols to the consumer default floor")
+ .containsExactlyInAnyOrder("TLSv1.3", "TLSv1.2");
+ });
+ } finally {
+ sslContextFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /** The client path is symmetric: a dropped companion must not leave a stale cipher allowlist pinned. */
+ @Test
+ public void clientDroppedCompanionRevertsCipherSuitesToConsumerDefault() throws Exception {
+ SSLContext initial = JdkSslContexts.createSslContext(false, CA, TRUSTED_CLIENT_CERT, TRUSTED_CLIENT_KEY, null);
+ SSLContext rotated = JdkSslContexts.createSslContext(false, CA, USER1_CLIENT_CERT, USER1_CLIENT_KEY, null);
+ SSLParameters buildCompanion = new SSLParameters();
+ buildCompanion.setCipherSuites(new String[] {"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});
+ buildCompanion.setProtocols(new String[] {"TLSv1.2"});
+ ScriptableFactory factory = new ScriptableFactory(initial, buildCompanion);
+
+ JettyTlsFactory.ReloadableClientTls reloadable = JettyTlsFactory.createReloadingClientFactory(
+ factory, TlsPurpose.BROKER_CLIENT, SAME_THREAD, null, true);
+ SslContextFactory.Client clientFactory = reloadable.sslContextFactory();
+ clientFactory.start();
+ try {
+ assertThat(clientFactory.getIncludeCipherSuites())
+ .containsExactly("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256");
+ assertThat(clientFactory.getIncludeProtocols()).containsExactly("TLSv1.2");
+
+ factory.deferCompanions();
+ factory.deliver(rotated);
+ factory.completeCompanion(0, null);
+
+ Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
+ assertThat(clientFactory.getIncludeCipherSuites())
+ .as("a dropped companion reverts cipher suites to the consumer default (unrestricted)")
+ .isEmpty();
+ assertThat(clientFactory.getIncludeProtocols())
+ .as("a dropped companion reverts protocols to the consumer default floor")
+ .containsExactlyInAnyOrder("TLSv1.3", "TLSv1.2");
+ });
+ } finally {
+ clientFactory.stop();
+ reloadable.subscription().dispose();
+ factory.close();
+ }
+ }
+
+ /**
+ * PIP-478: a rotation delivered BEFORE the connector starts must still refresh the companion. Only the very
+ * first (pre-fetched, synchronous) delivery reuses the build-time baseline; a later delivery that lands while
+ * the factory is still unstarted re-requests the companion and applies it directly (Jetty's {@code reload()}
+ * is for a live factory), so the started factory runs the rotation's engine policy — protocols, cipher suites
+ * and client-auth — rather than the stale build-time one.
+ */
Review Comment:
Nit: orphaned Javadoc — this block describes a pre-start rotation refreshing the companion, which is `preStartRotationRefreshesCompanionBeforeStart` (line 664), not the reload-executor test it currently sits above. That test has its own Javadoc immediately below at line 620. Looks like a rebase artifact; it should move down to line 663.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/JettyTlsFactory.java:
##########
@@ -0,0 +1,637 @@
+/*
+ * 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.jetty.tls;
+
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.Executor;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.tls.impl.TlsContexts;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * The framework's Jetty integration for the PIP-478 TLS SPI. Both {@link SslContextFactory.Server} and
+ * {@link SslContextFactory.Client} are well-known SPI classes: the framework first asks the
+ * {@link PulsarTlsFactory} to supply one natively (a custom factory may build and own it, reload
+ * included); only when the factory returns {@code empty()} for the Jetty class does the framework
+ * synthesize a <em>vanilla</em> (never subclassed) one from an {@code SSLContext} subscription. The
+ * default {@code FileBasedTlsFactory} returns {@code empty()} for the Jetty classes, so the synthesized
+ * path is the usual one.
+ *
+ * <p><b>Factory-supplied (native) instances.</b> When the factory supplies the Jetty factory directly it
+ * is handed back <em>unstarted</em> (the connector / {@code HttpClient} starts it), is the factory's
+ * same-instance-per-purpose, and the factory owns its reload on material rotation. The framework only
+ * holds the returned {@link TlsHandle} for disposal and never drives {@code setSslContext}/{@code reload}
+ * or overlays consumer configuration on such an instance.
+ *
+ * <p>This deliberately abandons the unsound {@code getSslContext()} override of the superseded PIP-337
+ * {@code JettySslContextFactory}. Instead it uses
+ * Jetty's documented hot-reload API — the same one {@code KeyStoreScanner} uses: an {@code SSLContext}
+ * subscription drives {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each
+ * later delivery (once started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context and re-selects
+ * protocols/ciphers. Existing connections keep their sessions; new connections use the new context.
+ *
+ * <p><b>{@code SSLParameters} companion (PIP-478).</b> Because these are synthesized paths (the factory
+ * returned {@code empty()} for the Jetty class and supplies only the {@code SSLContext}), the framework also
+ * asks the factory for its optional {@code javax.net.ssl.SSLParameters} companion — the engine-level baseline
+ * a bare {@code SSLContext} cannot express — and maps its non-null members onto the Jetty setters: enabled
+ * protocols ({@link SslContextFactory#setIncludeProtocols}) and cipher suites
+ * ({@link SslContextFactory#setIncludeCipherSuites}), and (server side, merge rule 4) the authoritative
+ * client-auth mode ({@link SslContextFactory.Server#setNeedClientAuth} /
+ * {@link SslContextFactory.Server#setWantClientAuth}). The initial companion is overlaid before start (at build
+ * time); on each subsequent <em>rotation</em> delivery it is re-requested <em>asynchronously</em> — the reload
+ * callback composes {@code createInstance(purpose, SSLParameters.class)} with {@code whenComplete} and only then
+ * calls {@code reload(...)}, so engine policy rotates with material (pip-478.md:736) yet the companion is
+ * <b>never joined on the delivery thread</b>. Joining there would self-deadlock a custom factory that dispatches
+ * companion creation to the same single-thread scheduler that runs the poll delivery — the exact hazard
+ * {@code TlsContextAcquisition.SynthesizingSubscription} avoids by composing the companion asynchronously.
+ *
+ * <p>Because those asynchronous re-requests complete on arbitrary threads and may finish out of order, the
+ * synthesized reload mirrors the two ordering guarantees of {@code SynthesizingSubscription} (see
+ * {@code JettyReloadCoordinator}): each delivery captures a strictly increasing <em>generation</em> and applies
+ * its {@code reload(...)} only while that generation is still the latest, so a companion superseded by a newer
+ * rotation is dropped rather than pinning the listener to a stale context/baseline; and the last
+ * successfully-resolved companion is <em>retained</em> (seeded from the build-time baseline) so a transient
+ * companion-fetch failure during rotation reloads with that last-good baseline rather than downgrading engine
+ * policy (protocols/ciphers and, server side, client-auth) to consumer defaults. Consumer defaults are still
+ * re-applied <em>in full</em> first inside every {@code reload(...)} lambda — protocols, cipher suites and, server
+ * side, client-auth are each re-pinned or cleared unconditionally, since the long-lived {@code SslContextFactory}
+ * persists setter state across {@code reload()} — so any companion member legitimately dropped by a newer delivery
+ * reverts to the consumer default rather than staying stuck from the previous companion.
+ * {@code empty()} leaves the consumer's configuration in force, exactly as before.
+ */
+@CustomLog
+public final class JettyTlsFactory {
+
+ static {
+ // Install Conscrypt process-wide, if present, before any TLS object is built here. Jetty resolves a
+ // JSSE provider by name, so the provider has to be registered by the time a factory is configured.
+ JcaProviders.ensureConscryptRegistered();
+ }
+
+ private JettyTlsFactory() {
+ }
+
+ /**
+ * A Jetty server factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the web service stops.
+ *
+ * @param sslContextFactory the (unstarted) Jetty server factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableServerTls(SslContextFactory.Server sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * A Jetty client factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the owning HTTP client
+ * / servlet is destroyed.
+ *
+ * @param sslContextFactory the (unstarted) Jetty client factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableClientTls(SslContextFactory.Client sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * Build a self-reloading {@link SslContextFactory.Server} for a purpose, handed back <em>unstarted</em>
+ * (Jetty starts it with the connector lifecycle) with its initial {@code SSLContext} already set.
+ *
+ * <p><b>Must not be called from the factory's blocking executor.</b> This builder blocks on the
+ * factory's acquisition, and the default factory dispatches acquisitions to
+ * {@code TlsFactoryInitContext.blockingExecutor()} — so calling it from that executor waits on work
+ * queued behind itself, which deadlocks when the executor is single-threaded. Call it from the owning
+ * component's startup thread.
+ *
+ * @param factory the TLS factory to subscribe to
+ * @param purpose the server purpose (e.g. {@link TlsPurpose#WEB})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param requireTrustedClientCert whether to require (vs. request) a trusted client certificate
+ * @param allowInsecureConnection whether an untrusted client cert is accepted under optional client auth
+ * @param ciphers enabled cipher suites, or {@code null} for defaults
+ * @param protocols enabled protocols, or {@code null} for defaults
+ * @return the reloading factory and its subscription handle
+ */
+ public static ReloadableServerTls createReloadingServerFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ Executor reloadExecutor,
+ String sslProviderString,
+ boolean requireTrustedClientCert,
+ boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ // Ask the factory first: a custom factory may natively supply the Jetty server factory (a
+ // well-known class). When it does, hand it back unstarted with the factory owning its reload and
+ // configuration; the framework overlays no consumer config on it. The default file-based factory
+ // returns empty() here, so the synthesized, self-reloading fallback below runs (the usual path).
+ Optional<TlsHandle<SslContextFactory.Server>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Server.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Server> handle = nativeFactory.get();
+ return new ReloadableServerTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
+ // Consumer config plus the factory's engine-policy companion (if any), before start. The resolved
+ // companion seeds the coordinator's last-good baseline so a companion-fetch failure on the very first
+ // rotation retains it rather than downgrading to consumer defaults.
+ SSLParameters initialBaseline = configureServerBaseline(sslContextFactory, factory, purpose,
+ sslProviderString, requireTrustedClientCert, allowInsecureConnection, ciphers, protocols);
+
+ // Each rotation re-requests the companion asynchronously (off the delivery thread) and applies it under
+ // a generation guard so an out-of-order companion cannot pin a stale context, retaining the last-good
+ // baseline across a transient companion failure. See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, reloadExecutor,
+ sslContextFactory, initialBaseline, (newContext, baseline) -> {
+ sslContextFactory.setSslContext(newContext);
+ // Re-apply the consumer defaults first so a companion member dropped by this delivery
+ // (notably client-auth) reverts to the consumer default rather than staying stuck from the
+ // previous companion, then overlay the generation-guarded, last-good companion.
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert,
+ allowInsecureConnection, ciphers, protocols);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ awaitAcquisition(factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery), purpose)
+ .orElseThrow(() -> new IllegalStateException(
+ "TLS factory supplied no SSLContext for purpose " + purpose));
+ return new ReloadableServerTls(sslContextFactory, coordinator.bind(subscription));
+ }
+
+ /**
+ * Build an {@link SslContextFactory.Client} for a purpose (used by the proxy's {@code AdminProxyHandler},
+ * whose Jetty {@code HttpClient} outlives broker-client material rotation), handed back
+ * <em>unstarted</em>. Mirroring {@link #createReloadingServerFactory}, the framework first asks the
+ * factory to supply the Jetty client factory natively; a custom factory that does so owns its reload and
+ * endpoint identification, and the framework overlays nothing on it. Otherwise a vanilla, self-reloading
+ * one is synthesized: an {@code SSLContext} subscription drives
+ * {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each later delivery (once
+ * started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context so new connections use
+ * the rotated material. Dispose the returned {@link ReloadableClientTls#subscription()} when the owning
+ * client is destroyed.
+ *
+ * <p><b>Must not be called from the factory's blocking executor.</b> This builder blocks on the
+ * factory's acquisition, and the default factory dispatches acquisitions to
+ * {@code TlsFactoryInitContext.blockingExecutor()} — so calling it from that executor waits on work
+ * queued behind itself, which deadlocks when the executor is single-threaded. Call it from the owning
+ * component's startup thread.
+ *
+ * @param factory the TLS factory to acquire from / subscribe to
+ * @param purpose the client purpose (e.g. {@link TlsPurpose#BROKER_CLIENT})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param enableHostnameVerification whether to verify the peer hostname; when {@code false} the
+ * synthesized client's endpoint identification is disabled (a
+ * factory-supplied native client owns this itself and is left untouched)
+ * @return the client factory and the handle backing it
+ */
+ public static ReloadableClientTls createReloadingClientFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ Executor reloadExecutor,
+ String sslProviderString,
+ boolean enableHostnameVerification) {
+ // Ask the factory first: a custom factory may natively supply the Jetty client factory (a well-known
+ // class, mirroring the Server variant) to customize proxy->broker admin TLS. When it does, hand it
+ // back unstarted with the factory owning its reload and its own endpoint identification; the
+ // framework overlays no consumer config on it. The default file-based factory returns empty() here,
+ // so the SSLContext-synthesized, self-reloading fallback below runs (the usual path, including
+ // rotation of the long-lived admin HttpClient's broker-client material).
+ Optional<TlsHandle<SslContextFactory.Client>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Client.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Client> handle = nativeFactory.get();
+ return new ReloadableClientTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Client client = new SslContextFactory.Client();
+ if (StringUtils.isNotBlank(sslProviderString)) {
+ client.setProvider(sslProviderString);
+ }
+ // Pin the {TLSv1.3, TLSv1.2} floor and overlay the factory's engine-policy companion (if any), before
+ // start; the resolved companion seeds the coordinator's last-good baseline (see the Server variant).
+ SSLParameters initialBaseline = configureClientBaseline(client, factory, purpose);
+ // Hostname verification is a consumer (proxy) concern on the synthesized path: disable endpoint
+ // identification when the consumer has it off (a native factory, handled above, owns this itself). This
+ // is a per-consumer setting applied once at build, not part of the per-delivery companion overlay.
+ if (!enableHostnameVerification) {
+ client.setEndpointIdentificationAlgorithm(null);
+ }
+
+ // Rotations re-request the companion asynchronously (off the delivery thread) and apply it under a
+ // generation guard, retaining the last-good baseline across a transient companion failure (client-auth
+ // is a server concept; endpoint identification stays as set at build). See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, reloadExecutor, client,
+ initialBaseline,
+ (newContext, baseline) -> {
+ client.setSslContext(newContext);
+ // Re-apply the consumer defaults first (the {TLSv1.3, TLSv1.2} floor and an unrestricted cipher
+ // list), then overlay the generation-guarded, last-good companion so a companion member dropped
+ // by this delivery reverts to those defaults rather than staying stuck from the previous one.
+ applyClientConfig(client);
+ if (baseline != null) {
+ applyClientBaseline(client, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ awaitAcquisition(factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery), purpose)
+ .orElseThrow(() -> new IllegalStateException(
+ "TLS factory supplied no SSLContext for purpose " + purpose));
+ return new ReloadableClientTls(client, coordinator.bind(subscription));
+ }
+
+ /**
+ * Apply the consumer config, then overlay the factory's engine-policy companion, onto a synthesized server
+ * factory — at build time only (off any event loop; the companion is joined here). Each subsequent rotation
+ * delivery re-requests the companion asynchronously and re-applies it inside the {@code reload(...)} lambda
+ * (see {@link JettyReloadCoordinator}), never joined on the delivery thread.
+ *
+ * @return the resolved companion baseline, or {@code null} when the factory supplied none — used to seed the
+ * coordinator's retained last-good baseline.
+ */
+ private static SSLParameters configureServerBaseline(SslContextFactory.Server sslContextFactory,
+ PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString, boolean requireTrustedClientCert,
+ boolean allowInsecureConnection, Set<String> ciphers,
+ Set<String> protocols) {
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert, allowInsecureConnection,
+ ciphers, protocols);
+ SSLParameters baseline = resolveBaselineParameters(factory, purpose).orElse(null);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ return baseline;
+ }
+
+ /**
+ * Pin the {@code {TLSv1.3, TLSv1.2}} floor, then overlay the factory companion's protocols/ciphers, onto a
+ * synthesized client factory — at build time only (off any event loop; the companion is joined here). Each
+ * subsequent rotation delivery re-requests the companion asynchronously and re-pins the floor + overlays it
+ * inside the {@code reload(...)} lambda (see {@link JettyReloadCoordinator}), never joined on the delivery
+ * thread. Client-auth is a server concept and is not mapped here; endpoint identification is a per-consumer
+ * setting applied once at build.
+ *
+ * @return the resolved companion baseline, or {@code null} when the factory supplied none — used to seed the
+ * coordinator's retained last-good baseline.
+ */
+ private static SSLParameters configureClientBaseline(SslContextFactory.Client client, PulsarTlsFactory factory,
+ TlsPurpose purpose) {
+ applyClientConfig(client);
+ SSLParameters baseline = resolveBaselineParameters(factory, purpose).orElse(null);
+ if (baseline != null) {
+ applyClientBaseline(client, baseline);
+ }
+ return baseline;
+ }
+
+ /**
+ * The synthesized client's consumer defaults, shared by the build-time overlay and every reload lambda so both
+ * agree on what a dropped companion member reverts to: the {@code {TLSv1.3, TLSv1.2}} floor, and an unrestricted
+ * cipher list (an empty include list means "no restriction" in Jetty). Both are cleared/re-pinned unconditionally
+ * because the factory is long-lived and persists setter state across {@code reload()}. The provider and endpoint
+ * identification are per-consumer settings applied once at build, not part of this per-delivery reset.
+ */
+ private static void applyClientConfig(SslContextFactory.Client client) {
+ client.setIncludeProtocols(TlsContexts.DEFAULT_ENABLED_PROTOCOLS.toArray(new String[0]));
+ client.setIncludeCipherSuites();
+ }
+
+ private static void applyServerConfig(SslContextFactory.Server sslContextFactory, String sslProviderString,
+ boolean requireTrustedClientCertOnConnect, boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ if (ciphers != null && !ciphers.isEmpty()) {
+ sslContextFactory.setIncludeCipherSuites(ciphers.toArray(new String[0]));
+ } else {
+ // Clear the include list explicitly (not just rely on the fresh-factory default), for the same reason
+ // needClientAuth is reset below: this method is re-applied on each reload of a long-lived factory, so a
+ // prior companion delivery that pinned cipher suites must revert to the consumer default before a later
+ // companion (or its absence) is overlaid. An empty include list means "no restriction" in Jetty --
+ // SslContextFactory.processIncludeExcludePatterns falls back to the SSLContext's enabled suites.
+ sslContextFactory.setIncludeCipherSuites();
+ }
+ // Pin the enabled protocols even when unconfigured, matching the {TLSv1.3, TLSv1.2} floor the native
+ // Netty path applies rather than deferring to the provider default. A factory-supplied companion,
+ // applied afterwards by applyServerBaseline, still overrides this.
+ if (protocols != null && !protocols.isEmpty()) {
+ sslContextFactory.setIncludeProtocols(protocols.toArray(new String[0]));
+ } else {
+ sslContextFactory.setIncludeProtocols(TlsContexts.DEFAULT_ENABLED_PROTOCOLS.toArray(new String[0]));
+ }
+ if (StringUtils.isNotBlank(sslProviderString)) {
+ sslContextFactory.setProvider(sslProviderString);
+ }
+ if (requireTrustedClientCertOnConnect) {
+ sslContextFactory.setNeedClientAuth(true);
+ sslContextFactory.setTrustAll(false);
+ } else {
+ // PIP-478: optional client auth requests but does not require a client cert. An untrusted
+ // client cert is accepted at the handshake only when tlsAllowInsecureConnection=true, aligning the
+ // web listener with the Netty binary listener's semantics and diverging from the pre-5.0 Jetty
+ // path, which trusted any presented client cert whenever client auth was optional (see PIP-478
+ // Security Considerations).
+ //
+ // The actual enforcement is the trust managers baked into the SSLContext the framework hands to
+ // Jetty via setSslContext (built from the WEB TlsPolicy's allowInsecureConnection: CA-validating
+ // when secure, insecure-trust-all when insecure). Jetty's own setTrustAll only takes effect when
+ // Jetty builds the SSLContext itself, so it is inert on this setSslContext path; we still scope it
+ // to the insecure flag so the two never disagree (defence in depth) rather than leaving the
+ // inherited unconditional setTrustAll(true).
+ // Clear needClientAuth explicitly (not just rely on the fresh-factory default): this method is
+ // re-applied on each reload, so a prior companion delivery that set needClientAuth must be reset to
+ // the consumer default here before a later companion (or its absence) is overlaid.
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(true);
+ sslContextFactory.setTrustAll(allowInsecureConnection);
+ }
+ // https://jetty.org/docs/jetty/12.1/operations-guide/protocols/index.html#ssl-sni
+ // Set to false for backwards compatibility with Jetty 9.x
+ sslContextFactory.setSniRequired(false);
+ }
+
+ /**
+ * Ask the factory to supply a native Jetty {@code jettyClass} for {@code purpose} (one-shot). Jetty's
+ * {@link SslContextFactory.Server} and {@link SslContextFactory.Client} are well-known SPI classes, so a
+ * custom factory MAY build one directly; the default {@code FileBasedTlsFactory} returns
+ * {@link Optional#empty()}, in which case the caller synthesizes the factory from an {@code SSLContext}
+ * subscription. A supplied instance is the factory's own (unstarted, same-instance-per-purpose,
+ * factory-driven reload) — the caller returns it verbatim and keeps the {@link TlsHandle} for disposal.
+ * Resolved at factory-build time (off any event loop), mirroring {@link #resolveBaselineParameters}.
+ */
+ private static <T extends SslContextFactory> Optional<TlsHandle<T>> acquireNativeJettyFactory(
+ PulsarTlsFactory factory, TlsPurpose purpose, Class<T> jettyClass) {
+ return awaitAcquisition(factory.createInstance(purpose, jettyClass), purpose);
+ }
+
+ /**
+ * Request the factory's optional {@code SSLParameters} companion for a purpose (one-shot) at factory-build
+ * time, joining off any event loop, and return the supplied instance or {@link Optional#empty()} when the
+ * factory supplies none. Rotation deliveries do NOT use this: they re-request the companion asynchronously
+ * inside {@link JettyReloadCoordinator} (never joined on the delivery thread) and unwrap it via
+ * {@link #extractBaseline}.
+ */
+ private static Optional<SSLParameters> resolveBaselineParameters(PulsarTlsFactory factory, TlsPurpose purpose) {
+ return Optional.ofNullable(
+ extractBaseline(awaitAcquisition(factory.createInstance(purpose, SSLParameters.class), purpose)));
+ }
+
+ /**
+ * Unwrap the factory's {@code SSLParameters} companion from its handle, disposing the handle afterwards (a
+ * companion carries no reference-counted state). Returns {@code null} when the factory supplied none
+ * ({@link Optional#empty()}). Used both by the build-time {@link #resolveBaselineParameters} and by the
+ * asynchronous per-rotation re-request in {@link JettyReloadCoordinator}.
+ */
+ private static SSLParameters extractBaseline(Optional<TlsHandle<SSLParameters>> handle) {
+ if (handle.isEmpty()) {
+ return null;
+ }
+ TlsHandle<SSLParameters> paramsHandle = handle.get();
+ try {
+ return paramsHandle.get();
+ } finally {
+ paramsHandle.dispose();
+ }
+ }
+
+ /**
+ * Await a factory acquisition made during a synchronous builder, unwrapping {@link CompletionException}
+ * so a configuration failure surfaces as its own cause. The underlying messages ("No TLS material
+ * configured for server purpose WEB") are the actionable ones and should not arrive wrapped.
+ *
+ * @param pending the acquisition
+ * @param purpose the purpose being acquired, for the failure message
+ * @return the acquisition result
+ */
+ private static <T> T awaitAcquisition(CompletableFuture<T> pending, TlsPurpose purpose) {
+ try {
+ return pending.join();
+ } catch (CompletionException e) {
+ Throwable cause = e.getCause() != null ? e.getCause() : e;
+ if (cause instanceof RuntimeException runtime) {
+ throw runtime;
+ }
+ if (cause instanceof Error error) {
+ throw error;
+ }
+ throw new IllegalStateException("Failed to acquire TLS material for purpose " + purpose, cause);
+ }
+ }
+
+ /**
+ * Overlay a factory-supplied engine baseline onto a synthesized server factory (PIP-478 merge order):
+ * enabled protocols/cipher suites when the companion sets them, and the companion's client-auth mode as
+ * authoritative (rule 4) — {@code needClientAuth} wins over {@code wantClientAuth}, neither means none.
+ */
+ private static void applyServerBaseline(SslContextFactory.Server sslContextFactory, SSLParameters baseline) {
+ if (baseline.getProtocols() != null) {
+ sslContextFactory.setIncludeProtocols(baseline.getProtocols());
+ }
+ if (baseline.getCipherSuites() != null) {
+ sslContextFactory.setIncludeCipherSuites(baseline.getCipherSuites());
+ }
+ if (baseline.getNeedClientAuth()) {
+ sslContextFactory.setNeedClientAuth(true);
+ } else if (baseline.getWantClientAuth()) {
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(true);
+ } else {
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(false);
+ }
+ }
+
+ /**
+ * Overlay a factory-supplied engine baseline onto a synthesized client factory: enabled protocols/cipher
+ * suites only (client-auth is a server concept; SNI/hostname verification remain per-connection).
+ */
+ private static void applyClientBaseline(SslContextFactory.Client client, SSLParameters baseline) {
+ if (baseline.getProtocols() != null) {
+ client.setIncludeProtocols(baseline.getProtocols());
+ }
+ if (baseline.getCipherSuites() != null) {
+ client.setIncludeCipherSuites(baseline.getCipherSuites());
+ }
+ }
+
+ /**
+ * Per-subscription reload coordinator for the synthesized Jetty paths. It ports the two ordering guarantees
+ * of {@code TlsContextAcquisition.SynthesizingSubscription} to Jetty's hot-reload API, which the naive
+ * "compose {@code createInstance(SSLParameters)} then {@code reload}" delivery lacked:
+ *
+ * <ul>
+ * <li><b>Generation guard.</b> Each delivery captures a strictly increasing generation (deliveries are
+ * serial per subscription, per the SPI contract). A rotation's companion re-request is composed
+ * asynchronously and may complete on an arbitrary thread and out of order, so its {@code reload(...)}
+ * is applied — under a lock — only while its generation is still the latest; a companion superseded
+ * by a newer rotation is dropped rather than pinning the listener to a stale context/baseline.</li>
+ * <li><b>Last-good baseline retention.</b> The last successfully-resolved companion is retained (seeded
+ * from the build-time baseline). A transient companion-fetch failure during rotation reloads with that
+ * last-good baseline rather than consumer defaults, so it cannot silently drop protocols/ciphers or
+ * (server side) client-auth. The retained baseline is updated only for a successfully-resolved,
+ * non-superseded companion, under the same lock.</li>
+ * </ul>
+ *
+ * <p>The companion is never joined on the delivery thread (the self-deadlock hazard described on the class
+ * javadoc); only the <em>first</em> delivery — which fires synchronously inside the subscribe call, before the
+ * built factory is even returned — sets the already-overlaid context directly, mirroring
+ * {@code SynthesizingSubscription}'s pre-fetched first delivery. Every later delivery is a rotation and
+ * re-requests the companion, <em>including one that arrives before the connector/client starts</em>; whether
+ * the factory is started only decides how the result is applied (Jetty's {@code reload(...)} once started, the
+ * same setters directly before), so a factory started after such a rotation starts with that rotation's
+ * material AND its companion policy rather than the stale build-time baseline.
+ */
+ private static final class JettyReloadCoordinator {
+
+ private final PulsarTlsFactory factory;
+ private final TlsPurpose purpose;
+ // Where publish() runs. The companion request is composed, never joined — but for the DEFAULT
+ // factory it completes synchronously (SSLParameters is an unsupported class, so createInstance
+ // returns an already-completed empty future), which would run the whole Jetty reload inline on the
+ // delivery thread, i.e. while the factory holds its source monitor. Dispatching keeps the source
+ // monitor out of the Jetty lock chain and honours the delivery contract's "cheap non-blocking store".
+ private final Executor reloadExecutor;
+ private final SslContextFactory target;
+ // Applies the rotated context + (nullable) companion baseline inside Jetty's reload lambda.
+ private final BiConsumer<SSLContext, SSLParameters> applyReload;
+ // Last successfully-resolved companion, seeded from the pre-fetched build-time baseline. Retained across
+ // a transient companion-fetch failure so a rotation cannot silently downgrade engine policy.
+ private volatile SSLParameters lastBaseline;
+ // One-shot: only the first (synchronous, pre-fetched) delivery reuses the build-time baseline; every
+ // later delivery is a rotation and re-requests the companion, started or not.
+ private final AtomicBoolean firstDelivery = new AtomicBoolean(true);
+ private final AtomicLong deliveryGeneration = new AtomicLong();
+ private long lastPublishedGeneration;
+ // A rotation's companion request is composed asynchronously, so its completion can land after the
+ // owner disposed the subscription (and, on the server path, after Jetty stopped the connector).
+ // Reloading a stopped/abandoned factory then would be a pointless mutation at best.
+ private final AtomicBoolean disposed = new AtomicBoolean();
+
+ JettyReloadCoordinator(PulsarTlsFactory factory, TlsPurpose purpose, Executor reloadExecutor,
+ SslContextFactory target, SSLParameters initialBaseline,
+ BiConsumer<SSLContext, SSLParameters> applyReload) {
+ this.factory = factory;
+ this.purpose = purpose;
+ this.reloadExecutor = reloadExecutor == null ? Runnable::run : reloadExecutor;
Review Comment:
Minor, but it quietly re-opens the defect: `reloadExecutor == null ? Runnable::run : reloadExecutor` means any caller that passes `null` gets exactly the inline `whenComplete` behaviour this PR just removed — the Jetty reload back on the delivery thread, under the source monitor.
And today *every* production caller would: `createReloadingServerFactory` / `createReloadingClientFactory` take `reloadExecutor` as a parameter, but grepping the branch, the only non-null arguments come from tests. There's no production call site in this PR yet.
Since the whole point of the parameter is that inline execution is unsafe, I'd make it required:
```suggestion
this.reloadExecutor = Objects.requireNonNull(reloadExecutor, "reloadExecutor must not be null: "
+ "the Jetty reload must not run on the delivery thread");
```
If a caller genuinely wants inline (tests do), passing `Runnable::run` explicitly says so and is greppable. A silent `null` fallback isn't. Happy to hear if you'd rather leave the parameter permissive until the broker/proxy wiring lands in the follow-up — but then it's worth a `// TODO` naming that follow-up, so this doesn't ship as the effective default.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [feat][misc] PIP-478: default file-based TLS factory implementation [pulsar]
Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on PR #26271:
URL: https://github.com/apache/pulsar/pull/26271#issuecomment-5207252059
Thanks — this one landed harder than the last. Both mutation results reproduce, and you're right about the cause in each case: the re-entrancy guard fired only under a direct executor, which is the one configuration where the deadlock cannot occur, and the reload-executor test asserted the executor's own thread naming rather than where `publish` ran.
All six are addressed in 5 commits. The two substantive ones:
- **323e0cca8c9** — the re-entrancy check moves to the caller thread, pre-dispatch, in both acquisition paths, with `resolve(purpose)` wrapped so its failure stays a failed future rather than a synchronous throw (the SPI forbids that, so the suggested snippet needed one amendment). The test now uses a real single-threaded executor with bounded waits and covers a rotation as well as the initial delivery.
- **afa92685af1** — the dispatch test now gates the *reload executor* with a synchronously-completing companion. Gating the companion future, as suggested, would not have failed under your mutation: an inline `whenComplete` on an incomplete future also returns promptly.
Plus **82019a67ae3** (executor required, validated at both entry points so the native-factory path can't bypass it), **c7a8542b7d4** (`@param`) and **4487e521180** (Javadoc move).
Every changed test in this round was mutation-tested against the unfixed code before I claimed it works — that was the gap in my previous round, and it's a fair correction to have had made twice.
1269 tests, 0 failures locally, plus the full lint/license gate. I've resolved the threads from the first review; these six are the open ones.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [feat][misc] PIP-478: default file-based TLS factory implementation [pulsar]
Posted by "nodece (via GitHub)" <gi...@apache.org>.
nodece commented on code in PR #26271:
URL: https://github.com/apache/pulsar/pull/26271#discussion_r3727535076
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/tls/DefaultBrokerTlsFactory.java:
##########
@@ -0,0 +1,240 @@
+/*
+ * 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.broker.tls;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.client.api.Authentication;
+import org.apache.pulsar.client.api.AuthenticationDataProvider;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactory;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactorySettings;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The broker's default {@code PulsarTlsFactory}: a thin {@link FileBasedTlsFactory} whose purpose→
+ * policy map is composed from a {@link ServiceConfiguration} (PIP-478).
+ *
+ * <p>It lives in {@code pulsar-broker-common} — which owns the Jetty integration and the broker
+ * configuration — so that neither the SPI module nor {@code pulsar-common} carries broker-config
+ * knowledge. The class only <em>composes</em> the map; wiring it into the broker/proxy/web services is
+ * a later stage.
+ */
+public class DefaultBrokerTlsFactory extends FileBasedTlsFactory {
+
+ /**
+ * Construct the broker factory from an already-composed purpose→policy map.
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ super(policies, settings);
+ }
+
+ /**
+ * Construct a broker factory that additionally folds the broker-client authentication's TLS material
+ * over the {@link TlsPurpose#BROKER_CLIENT} file policy (PIP-478).
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ super(policies, settings, authMaterialSuppliers);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}.
+ *
+ * @param conf the broker service configuration
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf) {
+ return fromServiceConfiguration(conf, null);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}, optionally folding the
+ * broker's broker-client {@link Authentication} TLS material over the {@link TlsPurpose#BROKER_CLIENT}
+ * file policy (PIP-478) for the broker's own outbound (broker-to-broker / replication) connections.
+ *
+ * <p>The broker's server material is registered for the {@link TlsPurpose#BROKER},
+ * {@link TlsPurpose#PROXY} and {@link TlsPurpose#WEB} purposes; the broker's outbound
+ * (broker-to-broker) material for {@link TlsPurpose#BROKER_CLIENT}. When {@code brokerClientAuth} is
+ * supplied and a broker-client authentication plugin is configured, its in-memory cert/key override the
+ * {@code brokerClient*} file paths (auth-cert-wins), so the broker presents the right identity to its
+ * peers — the server-side mirror of the client TLS override hook.
+ *
+ * @param conf the broker service configuration
+ * @param brokerClientAuth the broker's broker-client authentication, or {@code null} for no fold
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf,
+ Authentication brokerClientAuth) {
+ Map<TlsPurpose, TlsPolicy> policies = new LinkedHashMap<>();
+ TlsPolicy serverPolicy = serverPolicy(conf);
+ policies.put(TlsPurpose.BROKER, serverPolicy);
+ policies.put(TlsPurpose.PROXY, serverPolicy);
+ policies.put(TlsPurpose.WEB, webPolicy(conf));
+ policies.put(TlsPurpose.BROKER_CLIENT, brokerClientPolicy(conf));
+
+ FileBasedTlsFactorySettings settings = FileBasedTlsFactorySettings.builder()
+ .requireTrustedClientCert(conf.isTlsRequireTrustedClientCertOnConnect())
+ .refreshIntervalSeconds(refreshIntervalSeconds(conf))
+ // Engine selection (JDK vs. OpenSSL) mapped from the broker's tlsProvider field: an explicit
+ // engine literal is honored verbatim, a JSSE provider name selects no engine, and an unset
+ // value takes the native engine as OPENSSL_REFCNT when tcnative is available (see
+ // TlsFactorySupport.engineProvider).
+ .engineProvider(TlsFactorySupport.engineProvider(conf.getTlsProvider()))
+ .build();
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authSuppliers =
+ (brokerClientAuth != null && StringUtils.isNotBlank(conf.getBrokerClientAuthenticationPlugin()))
+ ? Map.of(TlsPurpose.BROKER_CLIENT, FileBasedTlsFactory.authMaterialSupplier(brokerClientAuth))
+ : Map.of();
+ return new DefaultBrokerTlsFactory(policies, settings, authSuppliers);
+ }
+
+ /**
+ * The {@link TlsPurpose#WEB} policy. The web listener has its own provider/protocol/cipher keys, and
+ * they take precedence over the binary-listener ones when set — {@code webServiceTlsProvider},
+ * {@code webServiceTlsProtocols}, {@code webServiceTlsCiphers} — falling back to {@code tlsProvider},
+ * {@code tlsProtocols}, {@code tlsCiphers} when they are not. Material (PEM or keystore) and the
+ * insecure flag are shared with the binary listener, as they are today.
+ *
+ * <p>Note the fallback is what makes the precedence safe to apply now: {@code webServiceTlsProvider}
+ * ships a non-blank default of {@code Conscrypt}, so it always wins over {@code tlsProvider} unless an
+ * operator blanks it. That matches the key's documented meaning — it names the JSSE (SSLContext)
+ * provider for the Jetty web listener — and Conscrypt is shipped in the server distribution. On a
+ * platform where the Conscrypt native library cannot load, the provider is not registered and pinning
+ * it fails loudly at startup rather than silently ignoring the configuration.
+ */
+ @VisibleForTesting
+ static TlsPolicy webPolicy(ServiceConfiguration conf) {
+ return serverPolicy(conf,
+ firstNonBlank(conf.getWebServiceTlsProvider(), conf.getTlsProvider()),
+ firstNonEmpty(conf.getWebServiceTlsProtocols(), conf.getTlsProtocols()),
+ firstNonEmpty(conf.getWebServiceTlsCiphers(), conf.getTlsCiphers()));
+ }
+
+ @VisibleForTesting
+ static TlsPolicy serverPolicy(ServiceConfiguration conf) {
+ return serverPolicy(conf, conf.getTlsProvider(), conf.getTlsProtocols(), conf.getTlsCiphers());
+ }
+
+ private static String firstNonBlank(String preferred, String fallback) {
+ return StringUtils.isNotBlank(preferred) ? preferred : fallback;
+ }
+
+ private static Set<String> firstNonEmpty(Set<String> preferred, Set<String> fallback) {
+ return preferred != null && !preferred.isEmpty() ? preferred : fallback;
+ }
+
+ private static TlsPolicy serverPolicy(ServiceConfiguration conf, String provider, Set<String> protocols,
+ Set<String> ciphers) {
+ // enableHostnameVerification is pinned OFF on server-role policies rather than mapped from
+ // tlsHostnameVerificationEnabled, which is the broker's OUTBOUND setting ("whether the hostname is
+ // validated when the broker creates a TLS connection with other brokers") and belongs on
+ // brokerClientPolicy() alone. It is inert either way today — only the client context builders read
+ // the flag — but a server policy carrying it would invite a future consumer to enable endpoint
+ // identification on a server engine, i.e. verify the CLIENT's hostname. It has to be set
+ // explicitly: TlsPolicy.Builder defaults the flag to true (secure-by-default for clients), so
+ // simply omitting it would leave every server policy claiming hostname verification is on.
+ TlsPolicy.Builder builder = TlsPolicy.builder()
+ .allowInsecureConnection(conf.isTlsAllowInsecureConnection())
+ .enableHostnameVerification(false)
Review Comment:
```suggestion
.enableHostnameVerification(conf.isTlsHostnameVerificationEnabled())
```
Please respect the broker configuration
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [feat][misc] PIP-478: default file-based TLS factory implementation [pulsar]
Posted by "david-streamlio (via GitHub)" <gi...@apache.org>.
david-streamlio commented on code in PR #26271:
URL: https://github.com/apache/pulsar/pull/26271#discussion_r3716896646
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/tls/DefaultBrokerTlsFactory.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.broker.tls;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.client.api.Authentication;
+import org.apache.pulsar.client.api.AuthenticationDataProvider;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactory;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactorySettings;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The broker's default {@code PulsarTlsFactory}: a thin {@link FileBasedTlsFactory} whose purpose→
+ * policy map is composed from a {@link ServiceConfiguration} (PIP-478).
+ *
+ * <p>It lives in {@code pulsar-broker-common} — which owns the Jetty integration and the broker
+ * configuration — so that neither the SPI module nor {@code pulsar-common} carries broker-config
+ * knowledge. The class only <em>composes</em> the map; wiring it into the broker/proxy/web services is
+ * a later stage.
+ */
+public class DefaultBrokerTlsFactory extends FileBasedTlsFactory {
+
+ /**
+ * Construct the broker factory from an already-composed purpose→policy map.
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ super(policies, settings);
+ }
+
+ /**
+ * Construct a broker factory that additionally folds the broker-client authentication's TLS material
+ * over the {@link TlsPurpose#BROKER_CLIENT} file policy (PIP-478).
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ super(policies, settings, authMaterialSuppliers);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}.
+ *
+ * @param conf the broker service configuration
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf) {
+ return fromServiceConfiguration(conf, null);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}, optionally folding the
+ * broker's broker-client {@link Authentication} TLS material over the {@link TlsPurpose#BROKER_CLIENT}
+ * file policy (PIP-478) for the broker's own outbound (broker-to-broker / replication) connections.
+ *
+ * <p>The broker's server material is registered for the {@link TlsPurpose#BROKER},
+ * {@link TlsPurpose#PROXY} and {@link TlsPurpose#WEB} purposes; the broker's outbound
+ * (broker-to-broker) material for {@link TlsPurpose#BROKER_CLIENT}. When {@code brokerClientAuth} is
+ * supplied and a broker-client authentication plugin is configured, its in-memory cert/key override the
+ * {@code brokerClient*} file paths (auth-cert-wins), so the broker presents the right identity to its
+ * peers — the server-side mirror of the client TLS override hook.
+ *
+ * @param conf the broker service configuration
+ * @param brokerClientAuth the broker's broker-client authentication, or {@code null} for no fold
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf,
+ Authentication brokerClientAuth) {
+ Map<TlsPurpose, TlsPolicy> policies = new LinkedHashMap<>();
+ TlsPolicy serverPolicy = serverPolicy(conf);
+ policies.put(TlsPurpose.BROKER, serverPolicy);
+ policies.put(TlsPurpose.PROXY, serverPolicy);
+ policies.put(TlsPurpose.WEB, serverPolicy);
+ policies.put(TlsPurpose.BROKER_CLIENT, brokerClientPolicy(conf));
+
+ FileBasedTlsFactorySettings settings = FileBasedTlsFactorySettings.builder()
+ .requireTrustedClientCert(conf.isTlsRequireTrustedClientCertOnConnect())
Review Comment:
`requireTrustedClientCert` is factory-wide in `FileBasedTlsFactorySettings` and so applies identically to `BROKER`, `PROXY` and `WEB`. That matches PIP-337 (`JettySslContextFactory` also keyed off `tlsRequireTrustedClientCertOnConnect`), so I think it's right — but since it's the one client-auth knob for three listeners with historically separate wiring, it's worth an explicit note in the settings Javadoc that this is intentional parity rather than a simplification.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/tls/DefaultBrokerTlsFactory.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.broker.tls;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.client.api.Authentication;
+import org.apache.pulsar.client.api.AuthenticationDataProvider;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactory;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactorySettings;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The broker's default {@code PulsarTlsFactory}: a thin {@link FileBasedTlsFactory} whose purpose→
+ * policy map is composed from a {@link ServiceConfiguration} (PIP-478).
+ *
+ * <p>It lives in {@code pulsar-broker-common} — which owns the Jetty integration and the broker
+ * configuration — so that neither the SPI module nor {@code pulsar-common} carries broker-config
+ * knowledge. The class only <em>composes</em> the map; wiring it into the broker/proxy/web services is
+ * a later stage.
+ */
+public class DefaultBrokerTlsFactory extends FileBasedTlsFactory {
+
+ /**
+ * Construct the broker factory from an already-composed purpose→policy map.
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ super(policies, settings);
+ }
+
+ /**
+ * Construct a broker factory that additionally folds the broker-client authentication's TLS material
+ * over the {@link TlsPurpose#BROKER_CLIENT} file policy (PIP-478).
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ super(policies, settings, authMaterialSuppliers);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}.
+ *
+ * @param conf the broker service configuration
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf) {
+ return fromServiceConfiguration(conf, null);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}, optionally folding the
+ * broker's broker-client {@link Authentication} TLS material over the {@link TlsPurpose#BROKER_CLIENT}
+ * file policy (PIP-478) for the broker's own outbound (broker-to-broker / replication) connections.
+ *
+ * <p>The broker's server material is registered for the {@link TlsPurpose#BROKER},
+ * {@link TlsPurpose#PROXY} and {@link TlsPurpose#WEB} purposes; the broker's outbound
+ * (broker-to-broker) material for {@link TlsPurpose#BROKER_CLIENT}. When {@code brokerClientAuth} is
+ * supplied and a broker-client authentication plugin is configured, its in-memory cert/key override the
+ * {@code brokerClient*} file paths (auth-cert-wins), so the broker presents the right identity to its
+ * peers — the server-side mirror of the client TLS override hook.
+ *
+ * @param conf the broker service configuration
+ * @param brokerClientAuth the broker's broker-client authentication, or {@code null} for no fold
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf,
+ Authentication brokerClientAuth) {
+ Map<TlsPurpose, TlsPolicy> policies = new LinkedHashMap<>();
+ TlsPolicy serverPolicy = serverPolicy(conf);
+ policies.put(TlsPurpose.BROKER, serverPolicy);
+ policies.put(TlsPurpose.PROXY, serverPolicy);
+ policies.put(TlsPurpose.WEB, serverPolicy);
+ policies.put(TlsPurpose.BROKER_CLIENT, brokerClientPolicy(conf));
+
+ FileBasedTlsFactorySettings settings = FileBasedTlsFactorySettings.builder()
+ .requireTrustedClientCert(conf.isTlsRequireTrustedClientCertOnConnect())
+ .refreshIntervalSeconds(refreshIntervalSeconds(conf))
+ // Engine selection (JDK vs. OpenSSL) mapped from the broker's tlsProvider field: an explicit
+ // engine literal is honored verbatim, a JSSE provider name selects no engine, and an unset
+ // value takes the native engine as OPENSSL_REFCNT when tcnative is available (see
+ // TlsFactorySupport.engineProvider).
+ .engineProvider(TlsFactorySupport.engineProvider(conf.getTlsProvider()))
+ .build();
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authSuppliers =
+ (brokerClientAuth != null && StringUtils.isNotBlank(conf.getBrokerClientAuthenticationPlugin()))
+ ? Map.of(TlsPurpose.BROKER_CLIENT, FileBasedTlsFactory.authMaterialSupplier(brokerClientAuth))
+ : Map.of();
+ return new DefaultBrokerTlsFactory(policies, settings, authSuppliers);
+ }
+
+ private static TlsPolicy serverPolicy(ServiceConfiguration conf) {
+ TlsPolicy.Builder builder = TlsPolicy.builder()
+ .allowInsecureConnection(conf.isTlsAllowInsecureConnection())
+ .enableHostnameVerification(conf.isTlsHostnameVerificationEnabled())
Review Comment:
`tlsHostnameVerificationEnabled` is the broker's *outbound client* setting ("whether the hostname is validated when the broker creates a TLS connection with other brokers"), but it's being set on the policy for `BROKER`/`PROXY`/`WEB` — all server-role purposes.
It's inert today: only `TlsContexts.buildNettyClientContext` and `synthesizeNettyClientFromJdk` read `enableHostnameVerification`, and neither runs for a server purpose. But it means the server policy carries a client-only flag with a non-default value, and a future consumer that reads it off the policy would turn on endpoint identification for a server engine — i.e. validate the *client's* hostname. I'd leave it unset on server policies, or add a comment saying why it's carried.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/TlsMaterialSource.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.common.tls.impl;
+
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.attribute.FileTime;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.PrivateKey;
+import java.security.Provider;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.common.util.tls.PemReader;
+import org.apache.pulsar.tls.TlsPolicy;
+
+/**
+ * Loads, watches and caches ONE material set (the crypto for a single {@code TlsPurpose}) from a
+ * {@link TlsPolicy} for the default {@code FileBasedTlsFactory} (PIP-478).
+ *
+ * <p>This collapses the old branch's {@code FileBasedClient/ServerTlsMaterialSource} split into a
+ * single, role-neutral class: the difference was only the value builder and a few flags, while the
+ * watch/cache machinery was duplicated verbatim.
+ *
+ * <p><b>Keystore-over-PEM per-field precedence.</b> For each of the three material slots (trust
+ * certs, private key, key certificate chain) the keystore location wins when set, otherwise the PEM
+ * location is used. PEM material is loaded via {@link PemReader}; keystores (PKCS12/JKS) are read
+ * with the raw {@link KeyStore} API and an alias walk.
+ *
+ * <p><b>Rotation detection (fixed mtime baseline).</b> Change detection snapshots the modification
+ * times of every configured file, and — unlike the old {@code FileModifiedTimeUpdater}-based scheme,
+ * which advanced the baseline <em>before</em> the load and so never retried a failed rotation until the
+ * next mtime change — commits the new baseline <strong>only after a successful load</strong>. A load
+ * that throws (a half-written or invalid rotated file, the canonical incident) leaves both the baseline
+ * and the last-good material untouched, so the next poll observes the same change again and retries.
+ * When mtimes advanced but the loaded material is byte-for-byte {@link TlsMaterial#equals(Object)
+ * equal} to the cached one (a file touched without content change), the baseline is committed but no
+ * change is signalled.
+ *
+ * <p><b>Fail-closed trust and identity.</b> A configured keystore truststore that holds zero certificates
+ * is rejected rather than loaded as an empty trust list: downstream, an empty trust list is
+ * indistinguishable from "no truststore configured" and both context builders then install the platform
+ * default trust manager, silently trusting every public CA. v4's {@code KeyStoreSSLContext} initialised the
+ * {@code TrustManagerFactory} with the explicit store and rejected every peer. The same applies to the
+ * identity axis: a keystore with no usable key entry, or a PEM certificate without its private key, fails
+ * the load instead of degrading to "no identity presented", which would surface only as a much later
+ * handshake failure. The PEM trust axis is deliberately NOT hardened (v4 fell back to the platform trust
+ * store for an empty trust file and deployments rely on that), and a PEM key without a certificate is a
+ * WARN, not a failure, for the same v4-parity reason.
+ *
+ * <p>Not thread-safe on its own; the owning factory serialises access under its per-source monitor.
+ */
+@CustomLog
+final class TlsMaterialSource implements MaterialSource {
+
+ /** Sentinel modification time recorded for a path that is currently missing or unreadable. */
+ private static final FileTime MISSING = FileTime.fromMillis(Long.MIN_VALUE);
+
+ private final TlsPolicy policy;
+ private final List<String> watchedPaths;
+ // Resolved once: the policy's jcaProvider (KeyStore/CertificateFactory/KeyFactory axis), or null when the
+ // policy pins none (the JVM provider search order). Resolving here keeps the ServiceLoader walk off the
+ // per-load path and fails loudly at factory init for an unresolvable name.
+ private final Provider jcaProvider;
+
+ private Map<String, FileTime> baseline;
+ private TlsMaterial cached;
+
+ TlsMaterialSource(TlsPolicy policy) {
+ this.policy = Objects.requireNonNull(policy, "policy must not be null");
+ this.watchedPaths = watchedPathsFor(policy);
+ this.jcaProvider = JcaProviders.resolveNamedProvider(policy.jcaProvider());
+ }
+
+ TlsPolicy policy() {
+ return policy;
+ }
+
+ /**
+ * @return the resolved JCA (material) provider, or {@code null} when the policy pins none. Package-private
+ * so the {@code BROKER_CLIENT} auth overlay parses its material through the same provider.
+ */
+ Provider jcaProvider() {
+ return jcaProvider;
+ }
+
+ /**
+ * Re-stat the configured files, reloading the material when they changed since the last successful
+ * load. Returns the current (possibly rebuilt) material together with whether it changed in value.
+ *
+ * @return the refresh outcome
+ * @throws Exception if the material could not be loaded (the last-good material and baseline are
+ * left untouched so the next call retries)
+ */
+ @Override
+ public MaterialSource.RefreshOutcome refresh() throws Exception {
+ Map<String, FileTime> snapshot = snapshotModificationTimes();
+ if (cached != null && snapshot.equals(baseline)) {
+ return new MaterialSource.RefreshOutcome(cached, false);
+ }
+ TlsMaterial loaded = load();
+ boolean changed = cached == null || !loaded.equals(cached);
+ // Commit the baseline only after a successful load (keep-last-good + retry-on-next-change).
+ baseline = snapshot;
+ if (changed) {
+ cached = loaded;
+ }
+ return new MaterialSource.RefreshOutcome(cached, changed);
+ }
+
+ private TlsMaterial load() throws Exception {
+ List<X509Certificate> trustCerts = loadTrustCerts();
+ // Keystore identity: load the whole store and carry every key entry, so a multi-identity keystore
+ // (e.g. RSA + EC) preserves JSSE alias selection at context build. The single privateKey/keyCertChain
+ // mirror the first entry, keeping hasKeyMaterial() and the value-equality rotation check meaningful.
+ if (StringUtils.isNotBlank(policy.keyStorePath())) {
+ KeyStore keyStore = TlsKeyStoreLoader.loadKeyStore(policy.keyStoreType(), policy.keyStorePath(),
+ policy.keyStorePassword(), jcaProvider);
+ List<TlsMaterial.KeyEntry> entries =
+ TlsKeyStoreLoader.extractKeyEntries(keyStore, policy.keyStorePassword());
+ validateKeyStoreIdentity(entries);
+ TlsMaterial.KeyEntry first = entries.get(0);
+ return new TlsMaterial(first.privateKey(), first.chain(), trustCerts, entries);
+ }
+ validatePemIdentity();
+ return new TlsMaterial(loadPemPrivateKey(), loadPemCertificateChain(), trustCerts);
+ }
+
+ /**
+ * Reject a keystore that holds no usable key entry. v4 handed such a store to
+ * {@code KeyManagerFactory.init}, which initialised fine but produced a key manager with no aliases — a
+ * certain, undiagnosed handshake failure for a server and a silently identity-less client. Failing the
+ * load is a deliberate tightening: the only deployments it can break already presented no identity.
+ *
+ * @param entries the key entries extracted from the configured keystore
+ * @throws KeyStoreException if the keystore carries no usable key entry
+ */
+ private void validateKeyStoreIdentity(List<TlsMaterial.KeyEntry> entries) throws KeyStoreException {
+ if (entries.isEmpty()) {
+ throw new KeyStoreException("Configured keystore '" + policy.keyStorePath()
+ + "' holds no usable key entry (a private key with an X.509 certificate chain); no TLS "
+ + "identity would be presented. Fix the keystore or its password, or unset keyStorePath.");
+ }
+ }
+
+ /**
+ * Reject a half-configured PEM identity that would be silently dropped. A certificate without its key
+ * yields {@link TlsMaterial#hasKeyMaterial()} {@code == false}, so the identity is omitted from the built
+ * context and the misconfiguration only surfaces as a handshake/authentication failure much later. The
+ * check is deliberately <em>asymmetric</em>: a key without a certificate is what v4 silently tolerated, so
+ * it stays a WARN rather than a new startup failure. Enforced here rather than in {@code TlsPolicy.Builder}
+ * so custom {@code PulsarTlsFactory} implementations that build their own policies are not constrained by
+ * this default factory's requirement.
+ */
+ private void validatePemIdentity() {
+ boolean hasCert = StringUtils.isNotBlank(policy.certificateFilePath());
+ boolean hasKey = StringUtils.isNotBlank(policy.keyFilePath());
+ if (hasCert && !hasKey) {
+ throw new IllegalArgumentException("TlsPolicy sets certificateFilePath='" + policy.certificateFilePath()
+ + "' but leaves keyFilePath unset; a certificate without its private key yields no usable TLS "
+ + "identity. Set keyFilePath, or unset certificateFilePath.");
+ }
+ if (hasKey && !hasCert) {
+ log.warn().attr("keyFilePath", policy.keyFilePath())
+ .log("TlsPolicy sets keyFilePath but no certificateFilePath; no TLS identity will be presented");
+ }
+ }
+
+ private List<X509Certificate> loadTrustCerts() throws Exception {
+ if (StringUtils.isNotBlank(policy.trustStorePath())) {
+ List<X509Certificate> trustCerts = TlsKeyStoreLoader.extractTrustCerts(
+ TlsKeyStoreLoader.loadKeyStore(policy.trustStoreType(), policy.trustStorePath(),
+ policy.trustStorePassword(), jcaProvider));
+ if (trustCerts.isEmpty()) {
+ // An empty trust list is indistinguishable from "no truststore configured" downstream, and both
+ // context builders then install the platform default trust manager — silently trusting every
+ // public CA. v4 initialised the TrustManagerFactory with the explicit store and rejected every peer.
+ throw new KeyStoreException("Configured truststore '" + policy.trustStorePath()
Review Comment:
This one is a genuine security fix, not just a tightening — today an empty keystore truststore is indistinguishable downstream from "no truststore configured", so both context builders install the platform default trust manager and the deployment trusts every public CA while believing it pinned a private CA. Good catch.
Because it's a fail-at-startup change, could the migration PR's release notes call out all three tightenings in this class explicitly?
- empty keystore truststore → now fails (this one)
- keystore with no usable key entry → now fails (line 161)
- PEM certificate without its private key → now fails (line 178)
The Javadoc argues each is safe ("the only deployments it can break already presented no identity"), which I buy, but they're startup failures on upgrade and shouldn't be discovered from a stack trace.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/util/tls/JcaProviders.java:
##########
@@ -0,0 +1,474 @@
+/*
+ * 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.common.util.tls;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.security.NoSuchAlgorithmException;
+import java.security.Provider;
+import java.security.Security;
+import java.util.Iterator;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.ServiceConfigurationError;
+import java.util.ServiceLoader;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+
+/**
+ * Resolves the JCA/JCE security providers Pulsar relies on: a named provider for the PIP-478
+ * {@code jsseProvider} / {@code jcaProvider} axes, the Bouncy Castle provider (FIPS or non-FIPS), and the
+ * optional Conscrypt (OpenSSL) provider. This is the single provider-resolution primitive extracted from the
+ * {@code SecurityUtility} grab-bag (PIP-478).
+ *
+ * <p><b>Bouncy Castle is resolved lazily and is optional.</b> Loading this class must not require it: the
+ * class exists mainly to resolve <em>named</em> providers for the two TLS provider axes, which every TLS
+ * policy does, whereas Bouncy Castle is needed only by the code that actually asks for it (message
+ * encryption, and a deployment that pins {@code jcaProvider=BC}/{@code BCFIPS}). The provider is therefore
+ * looked up on first use through {@link #bouncyCastleProvider()} — which reports absence as
+ * {@link Optional#empty()} rather than failing — and only a caller that genuinely needs it, via
+ * {@link #requireBouncyCastleProvider()}, turns absence into an error. Resolving it does install it
+ * process-wide via {@code Security.addProvider}, as before.
+ *
+ * <p>Conscrypt, by contrast, is resolved during class initialization ({@link #CONSCRYPT_PROVIDER}) and
+ * installed process-wide when present; it reports absence as {@code null} and never fails class loading.
+ */
+@CustomLog
+public final class JcaProviders {
+
+ public static final String BC_FIPS_PROVIDER_CLASS = "org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider";
+ public static final String BC_NON_FIPS_PROVIDER_CLASS = "org.bouncycastle.jce.provider.BouncyCastleProvider";
+ public static final String BC_JSSE_PROVIDER_CLASS = "org.bouncycastle.jsse.provider.BouncyCastleJsseProvider";
+ public static final String CONSCRYPT_PROVIDER_CLASS = "org.conscrypt.OpenSSLProvider";
+ public static final Provider CONSCRYPT_PROVIDER = loadConscryptProvider();
+
+ // Security.getProvider("BC") / Security.getProvider("BCFIPS").
+ // also used to get Factories. e.g. CertificateFactory.getInstance("X.509", "BCFIPS")
+ public static final String BC_FIPS = "BCFIPS";
+ public static final String BC = "BC";
+
+ /**
+ * The name BouncyCastle's JSSE provider registers under — the same in FIPS and non-FIPS mode, because
+ * the mode is a constructor argument rather than part of the provider identity.
+ */
+ public static final String BC_JSSE = "BCJSSE";
+
+ private JcaProviders() {
+ }
+
+ /**
+ * A resolved Bouncy Castle provider together with which of the two artifacts it came from. The flavour
+ * travels with the provider because callers that care (FIPS-approved-only algorithm choices) would
+ * otherwise have to re-derive it from the provider's class name, and because the answer is fixed once
+ * the provider is resolved.
+ *
+ * @param provider the resolved, process-wide registered provider
+ * @param fips whether it is the FIPS-certified artifact ({@code bc-fips}, registered as
+ * {@code BCFIPS}) rather than the general-purpose one ({@code bcprov}, registered as
+ * {@code BC})
+ */
+ public record ResolvedBouncyCastleProvider(Provider provider, boolean fips) {
+ public ResolvedBouncyCastleProvider {
+ Objects.requireNonNull(provider, "provider must not be null");
+ }
+ }
+
+ /**
+ * Lazily resolves Bouncy Castle on first access, so that merely loading {@link JcaProviders} — which
+ * every named-provider resolution does — never requires Bouncy Castle to be on the classpath.
+ */
+ private static final class BouncyCastleHolder {
+ private static final ResolvedBouncyCastleProvider RESOLVED = loadBouncyCastleProvider();
+ }
+
+ /**
+ * The Bouncy Castle provider, installed process-wide on first resolution:
+ * <ol>
+ * <li>an already-registered {@code BC} or {@code BCFIPS} provider, if any;</li>
+ * <li>otherwise loaded from the classpath (non-FIPS preferred, FIPS as fallback) and registered via
+ * {@code Security.addProvider}.</li>
+ * </ol>
+ *
+ * @return the resolved provider and its flavour, or {@link Optional#empty()} when Bouncy Castle is not
+ * available. Callers that cannot proceed without it should use
+ * {@link #requireBouncyCastleProvider()}, so the failure names them rather than surfacing as a
+ * class-initialization error somewhere unrelated.
+ */
+ public static Optional<ResolvedBouncyCastleProvider> bouncyCastleProvider() {
+ return Optional.ofNullable(BouncyCastleHolder.RESOLVED);
+ }
+
+ /**
+ * As {@link #bouncyCastleProvider()}, for callers whose functionality genuinely requires Bouncy Castle.
+ *
+ * @return the resolved provider and its flavour
+ * @throws IllegalStateException when Bouncy Castle is not on the classpath
+ */
+ public static ResolvedBouncyCastleProvider requireBouncyCastleProvider() {
+ return bouncyCastleProvider().orElseThrow(() -> new IllegalStateException(
+ "No Bouncy Castle provider is available: neither an already-registered " + BC + "/" + BC_FIPS
+ + " provider nor " + BC_NON_FIPS_PROVIDER_CLASS + " / " + BC_FIPS_PROVIDER_CLASS
+ + " on the classpath. Add the bcprov (or bc-fips) dependency to use this feature."));
+ }
+
+ private static ResolvedBouncyCastleProvider loadBouncyCastleProvider() {
+ Provider installed = Security.getProvider(BC);
+ if (installed == null) {
+ installed = Security.getProvider(BC_FIPS);
+ }
+ if (installed != null) {
+ log.debug().attr("provider", installed.getName()).log("Already instantiated Bouncy Castle provider");
+ return toResolvedProvider(installed);
+ }
+ // Not installed, try to load from the classpath. Absence is not an error here — it is only an error
+ // for a caller that needs Bouncy Castle, which requireBouncyCastleProvider() reports.
+ try {
+ return toResolvedProvider(getBCProviderFromClassPath());
+ } catch (Exception e) {
+ log.debug().exception(e)
+ .log("No Bouncy Castle provider (FIPS or non-FIPS) on the classpath");
+ return null;
+ }
+ }
+
+ /**
+ * Lazily resolves BouncyCastle's JSSE provider on first access, registering it from the classpath when
+ * the operator has not installed it themselves.
+ */
+ private static final class BouncyCastleJsseHolder {
+ private static final ResolvedBouncyCastleProvider RESOLVED = loadBouncyCastleJsseProvider();
+ }
+
+ /**
+ * BouncyCastle's JSSE provider ({@value #BC_JSSE}), the provider a FIPS TLS deployment pins as
+ * {@code jsseProvider}.
+ *
+ * <p>Unlike every other provider this class resolves, {@value #BC_JSSE} cannot be discovered: {@code bctls}
+ * ships no {@code META-INF/services/java.security.Provider} entry, so an unregistered one is invisible to
+ * {@link ServiceLoader}. And it cannot simply be default-constructed either, because its FIPS mode is a
+ * constructor argument fixed at construction — the provider registers under the same name either way, so
+ * a no-arg instance would quietly be the non-FIPS one. This resolves it explicitly instead:
+ *
+ * <ol>
+ * <li>an instance the operator already registered wins, whatever mode they built it in;</li>
+ * <li>otherwise, when {@code bctls} is on the classpath, it is constructed and registered here — in
+ * FIPS mode bound to the FIPS JCA provider when {@link #bouncyCastleProvider()} resolved that one,
+ * and in the default mode otherwise, so the TLS stack follows whichever BouncyCastle artifact the
+ * deployment actually ships;</li>
+ * <li>otherwise it is absent, and pinning {@code jsseProvider=BCJSSE} fails loudly.</li>
+ * </ol>
+ *
+ * @return the resolved provider and whether it is in FIPS mode, or {@link Optional#empty()} when
+ * {@code bctls} is not on the classpath
+ */
+ public static Optional<ResolvedBouncyCastleProvider> bouncyCastleJsseProvider() {
+ return Optional.ofNullable(BouncyCastleJsseHolder.RESOLVED);
+ }
+
+ private static ResolvedBouncyCastleProvider loadBouncyCastleJsseProvider() {
+ Provider registered = Security.getProvider(BC_JSSE);
+ if (registered != null) {
+ log.debug().attr("provider", BC_JSSE).log("Already instantiated BouncyCastle JSSE provider");
+ return new ResolvedBouncyCastleProvider(registered, isJsseFipsMode(registered));
+ }
+ Class<?> providerClass;
+ try {
+ providerClass = Class.forName(BC_JSSE_PROVIDER_CLASS);
+ } catch (ClassNotFoundException e) {
+ log.debug().attr("class", BC_JSSE_PROVIDER_CLASS)
+ .log("No BouncyCastle JSSE provider on the classpath");
+ return null;
+ }
+ // Resolving the JCA provider first also installs it, which the FIPS configuration below needs: the
+ // JSSE provider looks its crypto provider up by name while constructing.
+ String config = jsseProviderConfig(bouncyCastleProvider().orElse(null));
+ try {
+ Provider provider = config == null
+ ? (Provider) providerClass.getDeclaredConstructor().newInstance()
+ : (Provider) providerClass.getDeclaredConstructor(String.class).newInstance(config);
+ Security.addProvider(provider);
+ boolean fips = isJsseFipsMode(provider);
+ log.info().attr("provider", provider.getName()).attr("fips", fips)
+ .log("Registered the BouncyCastle JSSE provider");
+ return new ResolvedBouncyCastleProvider(provider, fips);
+ } catch (ReflectiveOperationException | RuntimeException e) {
+ log.warn().attr("class", BC_JSSE_PROVIDER_CLASS).attr("config", config).exception(e)
+ .log("Failed to register the BouncyCastle JSSE provider");
+ return null;
+ }
+ }
+
+ /**
+ * The constructor argument for a self-registered {@value #BC_JSSE}: {@code "fips:<name>"} binds it to a
+ * FIPS JCA provider and turns FIPS mode on, while {@code null} selects the no-arg (default, non-FIPS)
+ * constructor. FIPS mode is chosen only when the resolved BouncyCastle JCA provider is itself the FIPS
+ * artifact — pairing a FIPS JSSE provider with a non-validated crypto provider would be FIPS-shaped
+ * rather than FIPS-compliant, which is exactly what the two provider axes exist to prevent.
+ *
+ * @param jcaProvider the resolved BouncyCastle JCA provider, or {@code null} when there is none
+ * @return the constructor argument, or {@code null} to use the no-arg constructor
+ */
+ @VisibleForTesting
+ static String jsseProviderConfig(ResolvedBouncyCastleProvider jcaProvider) {
+ if (jcaProvider == null || !jcaProvider.fips()) {
+ return null;
+ }
+ return "fips:" + jcaProvider.provider().getName();
+ }
+
+ /** Query a JSSE provider's FIPS mode reflectively, so this class never needs {@code bctls} to compile. */
+ private static boolean isJsseFipsMode(Provider provider) {
+ try {
+ return Boolean.TRUE.equals(provider.getClass().getMethod("isFipsMode").invoke(provider));
+ } catch (ReflectiveOperationException | RuntimeException e) {
+ log.debug().attr("provider", provider.getName()).exception(e)
+ .log("Provider exposes no isFipsMode(); assuming non-FIPS");
+ return false;
+ }
+ }
+
+ /**
+ * Classify a resolved provider. Both the registered name and the implementation class are checked: the
+ * FIPS artifact registers as {@code BCFIPS}, and matching the class as well keeps the classification
+ * right for a provider registered under a non-standard name.
+ */
+ private static ResolvedBouncyCastleProvider toResolvedProvider(Provider provider) {
+ boolean fips = BC_FIPS.equals(provider.getName())
+ || BC_FIPS_PROVIDER_CLASS.equals(provider.getClass().getCanonicalName());
+ return new ResolvedBouncyCastleProvider(provider, fips);
+ }
+
+ private static Provider loadConscryptProvider() {
+ Class<?> conscryptClazz;
+
+ try {
+ conscryptClazz = Class.forName("org.conscrypt.Conscrypt");
+ conscryptClazz.getMethod("checkAvailability").invoke(null);
+ } catch (Throwable e) {
+ if (e instanceof ClassNotFoundException) {
+ log.debug("Conscrypt isn't available in the classpath. Using JDK default security provider.");
+ } else if (e.getCause() instanceof UnsatisfiedLinkError) {
+ log.debug().attr("os", System.getProperty("os.name")).attr("arch", System.getProperty("os.arch"))
+ .log("Conscrypt isn't available. Using JDK default security provider");
+ } else {
+ log.debug().attr("cause", e.getCause()).attr("reason", e.getMessage())
+ .log("Conscrypt isn't available. Using JDK default security provider");
+ }
+ return null;
+ }
+
+ Provider provider;
+ try {
+ provider = (Provider) Class.forName(CONSCRYPT_PROVIDER_CLASS).getDeclaredConstructor().newInstance();
+ } catch (ReflectiveOperationException e) {
+ log.debug().attr("class", CONSCRYPT_PROVIDER_CLASS).exception(e)
+ .log("Unable to get security provider");
+ return null;
+ }
+
+ // Unlike the PIP-337 loader this one installs NO custom hostname verifier, so Conscrypt keeps its
+ // built-in default: standard RFC 2818 (SAN-based) verification, matching PIP-478's removal of the
+ // deprecated CN-based matching. The bug-1015 workaround in processConscryptTrustManager propagates
+ // whatever Conscrypt's DEFAULT verifier is onto each TrustManager.
+ //
+ // CAVEAT while both TLS stacks coexist: Conscrypt.setDefaultHostnameVerifier is process-global, and
+ // SecurityUtility's static initializer (still the wired PIP-337 path) sets it to the CN-tolerant
+ // TlsHostnameVerifier. Whenever that class has been loaded, the "default" propagated above is that
+ // relaxed verifier, not Conscrypt's own. Nothing routes through this class yet so no deployment is
+ // affected today; the PR that turns SAN-only hostname verification on by default must neutralize that
+ // global (or land together with SecurityUtility's removal) for the SAN-only guarantee to hold on a
+ // Conscrypt-pinned deployment.
+
+ Security.addProvider(provider);
+ log.debug().attr("provider", provider.getName()).attr("class", CONSCRYPT_PROVIDER_CLASS)
+ .log("Added security provider");
+ return provider;
+ }
+
+ /**
+ * Get Bouncy Castle provider from classpath, and call Security.addProvider.
+ * Throw Exception if failed.
+ */
+ private static Provider getBCProviderFromClassPath() throws Exception {
+ Class<?> clazz;
+ try {
+ // prefer non FIPS, for backward compatibility concern.
+ clazz = Class.forName(BC_NON_FIPS_PROVIDER_CLASS);
+ } catch (ClassNotFoundException cnf) {
+ log.warn().attr("nonFipsClass", BC_NON_FIPS_PROVIDER_CLASS).attr("fipsClass", BC_FIPS_PROVIDER_CLASS)
+ .log("Not able to get Bouncy Castle provider, try to get FIPS provider");
+ // attempt to use the FIPS provider.
+ clazz = Class.forName(BC_FIPS_PROVIDER_CLASS);
+ }
+
+ Provider provider = (Provider) clazz.getDeclaredConstructor().newInstance();
+ Security.addProvider(provider);
+ log.debug().attr("provider", provider.getName())
+ .log("Found and Instantiated Bouncy Castle provider in classpath");
+ return provider;
+ }
+
+ /**
+ * Resolve a named {@link Provider} — e.g. the JSSE (SSLContext) provider named by the PIP-478
+ * {@code jsseProvider} field. Resolution prefers a provider the operator has already registered in the
+ * JVM ({@link Security#getProvider(String)}), falls back to the {@link ServiceLoader} mechanism on the
+ * application (thread-context) class loader ({@code META-INF/services/java.security.Provider}) matching
+ * by {@link Provider#getName()}, and fails loudly when the name resolves to nothing (the fail-fast
+ * contract — a misconfigured provider surfaces at client build / server start rather than silently
+ * defaulting).
+ *
+ * <p><b>Why the registered provider wins.</b> The two steps differ in <em>which instance</em> answers a
+ * name: {@code ServiceLoader} constructs a fresh instance through the provider's <em>no-arg</em>
+ * constructor, whereas {@link Security#getProvider(String)} returns the instance the operator installed.
+ * Preferring the latter makes an explicit {@code java.security} registration authoritative, which is
+ * what configuring one means — the operator's instance may carry provider-level configuration, and it is
+ * the object actually present in the JVM's provider list. It matters concretely for any provider that
+ * ships a {@code META-INF/services/java.security.Provider} entry <em>and</em> whose configuration is
+ * constructor-supplied; {@code bcprov} ships such an entry, so before this ordering a pinned
+ * {@code jcaProvider=BC} resolved to a fresh provider rather than the registered one.
+ *
+ * <p>Note that BouncyCastle's JSSE provider is <em>not</em> affected either way: {@code bctls} ships no
+ * services entry, so {@code BCJSSE} is never {@code ServiceLoader}-discoverable and must be registered
+ * by the operator to be resolvable at all. That is the only way its FIPS mode — a constructor argument,
+ * {@code new BouncyCastleJsseProvider("fips:BCFIPS")}, with the provider registering under the plain
+ * name {@code BCJSSE} either way — can reach Pulsar.
+ *
+ * <p>Unlike {@link #resolveProvider(String)} (which falls back to the default provider), this never
+ * returns {@code null} for a non-blank name: an unresolvable name is a configuration error.
+ *
+ * @param providerName the {@code java.security.Provider} name (blank/{@code null} returns {@code null})
+ * @return the resolved provider, or {@code null} when {@code providerName} is blank
+ * @throws IllegalArgumentException if a non-blank name resolves to no installed provider
+ */
+ public static Provider resolveNamedProvider(String providerName) {
+ if (StringUtils.isBlank(providerName)) {
+ return null;
+ }
+ String name = providerName.trim();
+ // 1. A provider the operator registered in the JVM wins — it carries their configuration (see above).
+ Provider registered = Security.getProvider(name);
+ if (registered != null) {
+ log.debug().attr("provider", name).log("Resolved JCA provider via Security.getProvider");
+ return registered;
+ }
+ // 2. ServiceLoader on the application class loader (META-INF/services/java.security.Provider).
+ ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+ if (classLoader == null) {
+ classLoader = JcaProviders.class.getClassLoader();
+ }
+ // Iterate defensively: a single broken META-INF/services/java.security.Provider entry (an unrelated
+ // provider whose class fails to load) throws ServiceConfigurationError from hasNext()/next(). Skipping
+ // it — rather than aborting the whole loop — lets a good provider still resolve here, and otherwise
+ // still falls through to the Security.getProvider fallback (step 2) rather than failing early.
+ Iterator<Provider> it = ServiceLoader.load(Provider.class, classLoader).iterator();
Review Comment:
Two things here:
1. `ServiceLoader.load(Provider.class, ...)` **constructs** every provider on the classpath as it iterates, until a name matches. Provider constructors are not always side-effect-free, and the ones we don't want are being instantiated purely to read `getName()`. `ServiceLoader.stream()` gives `Provider<Provider>` handles whose `type()` can be inspected without instantiating — though matching by `getName()` does unfortunately need the instance, so this may be unavoidable. Worth a sentence acknowledging it.
2. The provider resolved this way is returned without `Security.addProvider`. That's correct for direct `getInstance(alg, providerObject)` use, but means `jcaProvider=Foo` resolving via `ServiceLoader` yields a *different* instance than a later `Security.getProvider("Foo")` would. Given the Javadoc goes to some length about which instance answers a name, that asymmetry is worth stating too.
Minor: the comment on line 378-379 says "still falls through to the `Security.getProvider` fallback (step 2)" — `Security.getProvider` is step 1, and the fallthrough is to step 3/4.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/JettyTlsFactory.java:
##########
@@ -0,0 +1,586 @@
+/*
+ * 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.jetty.tls;
+
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.tls.impl.TlsContexts;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * The framework's Jetty integration for the PIP-478 TLS SPI. Both {@link SslContextFactory.Server} and
+ * {@link SslContextFactory.Client} are well-known SPI classes: the framework first asks the
+ * {@link PulsarTlsFactory} to supply one natively (a custom factory may build and own it, reload
+ * included); only when the factory returns {@code empty()} for the Jetty class does the framework
+ * synthesize a <em>vanilla</em> (never subclassed) one from an {@code SSLContext} subscription. The
+ * default {@code FileBasedTlsFactory} returns {@code empty()} for the Jetty classes, so the synthesized
+ * path is the usual one.
+ *
+ * <p><b>Factory-supplied (native) instances.</b> When the factory supplies the Jetty factory directly it
+ * is handed back <em>unstarted</em> (the connector / {@code HttpClient} starts it), is the factory's
+ * same-instance-per-purpose, and the factory owns its reload on material rotation. The framework only
+ * holds the returned {@link TlsHandle} for disposal and never drives {@code setSslContext}/{@code reload}
+ * or overlays consumer configuration on such an instance.
+ *
+ * <p>This deliberately abandons the unsound {@code getSslContext()} override of the superseded PIP-337
+ * {@code JettySslContextFactory}. Instead it uses
+ * Jetty's documented hot-reload API — the same one {@code KeyStoreScanner} uses: an {@code SSLContext}
+ * subscription drives {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each
+ * later delivery (once started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context and re-selects
+ * protocols/ciphers. Existing connections keep their sessions; new connections use the new context.
+ *
+ * <p><b>{@code SSLParameters} companion (PIP-478).</b> Because these are synthesized paths (the factory
+ * returned {@code empty()} for the Jetty class and supplies only the {@code SSLContext}), the framework also
+ * asks the factory for its optional {@code javax.net.ssl.SSLParameters} companion — the engine-level baseline
+ * a bare {@code SSLContext} cannot express — and maps its non-null members onto the Jetty setters: enabled
+ * protocols ({@link SslContextFactory#setIncludeProtocols}) and cipher suites
+ * ({@link SslContextFactory#setIncludeCipherSuites}), and (server side, merge rule 4) the authoritative
+ * client-auth mode ({@link SslContextFactory.Server#setNeedClientAuth} /
+ * {@link SslContextFactory.Server#setWantClientAuth}). The initial companion is overlaid before start (at build
+ * time); on each subsequent <em>rotation</em> delivery it is re-requested <em>asynchronously</em> — the reload
+ * callback composes {@code createInstance(purpose, SSLParameters.class)} with {@code whenComplete} and only then
+ * calls {@code reload(...)}, so engine policy rotates with material (pip-478.md:736) yet the companion is
+ * <b>never joined on the delivery thread</b>. Joining there would self-deadlock a custom factory that dispatches
+ * companion creation to the same single-thread scheduler that runs the poll delivery — the exact hazard
+ * {@code TlsContextAcquisition.SynthesizingSubscription} avoids by composing the companion asynchronously.
+ *
+ * <p>Because those asynchronous re-requests complete on arbitrary threads and may finish out of order, the
+ * synthesized reload mirrors the two ordering guarantees of {@code SynthesizingSubscription} (see
+ * {@code JettyReloadCoordinator}): each delivery captures a strictly increasing <em>generation</em> and applies
+ * its {@code reload(...)} only while that generation is still the latest, so a companion superseded by a newer
+ * rotation is dropped rather than pinning the listener to a stale context/baseline; and the last
+ * successfully-resolved companion is <em>retained</em> (seeded from the build-time baseline) so a transient
+ * companion-fetch failure during rotation reloads with that last-good baseline rather than downgrading engine
+ * policy (protocols/ciphers and, server side, client-auth) to consumer defaults. Consumer defaults are still
+ * re-applied <em>in full</em> first inside every {@code reload(...)} lambda — protocols, cipher suites and, server
+ * side, client-auth are each re-pinned or cleared unconditionally, since the long-lived {@code SslContextFactory}
+ * persists setter state across {@code reload()} — so any companion member legitimately dropped by a newer delivery
+ * reverts to the consumer default rather than staying stuck from the previous companion.
+ * {@code empty()} leaves the consumer's configuration in force, exactly as before.
+ */
+@CustomLog
+public final class JettyTlsFactory {
+
+ static {
+ // DO NOT EDIT - Load Conscrypt provider
+ if (JcaProviders.CONSCRYPT_PROVIDER != null) {
Review Comment:
Nit: an empty `if` body as a class-initialization trigger. I realise this is carried over verbatim from `JettySslContextFactory` (hence "DO NOT EDIT"), but in a new file it reads as a mistake and only survives checkstyle by luck. A named no-op on `JcaProviders` — `JcaProviders.ensureConscryptLoaded()` — would express the intent and give the "DO NOT EDIT" something to protect.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/JettyTlsFactory.java:
##########
@@ -0,0 +1,586 @@
+/*
+ * 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.jetty.tls;
+
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.tls.impl.TlsContexts;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * The framework's Jetty integration for the PIP-478 TLS SPI. Both {@link SslContextFactory.Server} and
+ * {@link SslContextFactory.Client} are well-known SPI classes: the framework first asks the
+ * {@link PulsarTlsFactory} to supply one natively (a custom factory may build and own it, reload
+ * included); only when the factory returns {@code empty()} for the Jetty class does the framework
+ * synthesize a <em>vanilla</em> (never subclassed) one from an {@code SSLContext} subscription. The
+ * default {@code FileBasedTlsFactory} returns {@code empty()} for the Jetty classes, so the synthesized
+ * path is the usual one.
+ *
+ * <p><b>Factory-supplied (native) instances.</b> When the factory supplies the Jetty factory directly it
+ * is handed back <em>unstarted</em> (the connector / {@code HttpClient} starts it), is the factory's
+ * same-instance-per-purpose, and the factory owns its reload on material rotation. The framework only
+ * holds the returned {@link TlsHandle} for disposal and never drives {@code setSslContext}/{@code reload}
+ * or overlays consumer configuration on such an instance.
+ *
+ * <p>This deliberately abandons the unsound {@code getSslContext()} override of the superseded PIP-337
+ * {@code JettySslContextFactory}. Instead it uses
+ * Jetty's documented hot-reload API — the same one {@code KeyStoreScanner} uses: an {@code SSLContext}
+ * subscription drives {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each
+ * later delivery (once started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context and re-selects
+ * protocols/ciphers. Existing connections keep their sessions; new connections use the new context.
+ *
+ * <p><b>{@code SSLParameters} companion (PIP-478).</b> Because these are synthesized paths (the factory
+ * returned {@code empty()} for the Jetty class and supplies only the {@code SSLContext}), the framework also
+ * asks the factory for its optional {@code javax.net.ssl.SSLParameters} companion — the engine-level baseline
+ * a bare {@code SSLContext} cannot express — and maps its non-null members onto the Jetty setters: enabled
+ * protocols ({@link SslContextFactory#setIncludeProtocols}) and cipher suites
+ * ({@link SslContextFactory#setIncludeCipherSuites}), and (server side, merge rule 4) the authoritative
+ * client-auth mode ({@link SslContextFactory.Server#setNeedClientAuth} /
+ * {@link SslContextFactory.Server#setWantClientAuth}). The initial companion is overlaid before start (at build
+ * time); on each subsequent <em>rotation</em> delivery it is re-requested <em>asynchronously</em> — the reload
+ * callback composes {@code createInstance(purpose, SSLParameters.class)} with {@code whenComplete} and only then
+ * calls {@code reload(...)}, so engine policy rotates with material (pip-478.md:736) yet the companion is
+ * <b>never joined on the delivery thread</b>. Joining there would self-deadlock a custom factory that dispatches
+ * companion creation to the same single-thread scheduler that runs the poll delivery — the exact hazard
+ * {@code TlsContextAcquisition.SynthesizingSubscription} avoids by composing the companion asynchronously.
+ *
+ * <p>Because those asynchronous re-requests complete on arbitrary threads and may finish out of order, the
+ * synthesized reload mirrors the two ordering guarantees of {@code SynthesizingSubscription} (see
+ * {@code JettyReloadCoordinator}): each delivery captures a strictly increasing <em>generation</em> and applies
+ * its {@code reload(...)} only while that generation is still the latest, so a companion superseded by a newer
+ * rotation is dropped rather than pinning the listener to a stale context/baseline; and the last
+ * successfully-resolved companion is <em>retained</em> (seeded from the build-time baseline) so a transient
+ * companion-fetch failure during rotation reloads with that last-good baseline rather than downgrading engine
+ * policy (protocols/ciphers and, server side, client-auth) to consumer defaults. Consumer defaults are still
+ * re-applied <em>in full</em> first inside every {@code reload(...)} lambda — protocols, cipher suites and, server
+ * side, client-auth are each re-pinned or cleared unconditionally, since the long-lived {@code SslContextFactory}
+ * persists setter state across {@code reload()} — so any companion member legitimately dropped by a newer delivery
+ * reverts to the consumer default rather than staying stuck from the previous companion.
+ * {@code empty()} leaves the consumer's configuration in force, exactly as before.
+ */
+@CustomLog
+public final class JettyTlsFactory {
+
+ static {
+ // DO NOT EDIT - Load Conscrypt provider
+ if (JcaProviders.CONSCRYPT_PROVIDER != null) {
+ }
+ }
+
+ private JettyTlsFactory() {
+ }
+
+ /**
+ * A Jetty server factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the web service stops.
+ *
+ * @param sslContextFactory the (unstarted) Jetty server factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableServerTls(SslContextFactory.Server sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * A Jetty client factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the owning HTTP client
+ * / servlet is destroyed.
+ *
+ * @param sslContextFactory the (unstarted) Jetty client factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableClientTls(SslContextFactory.Client sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * Build a self-reloading {@link SslContextFactory.Server} for a purpose, handed back <em>unstarted</em>
+ * (Jetty starts it with the connector lifecycle) with its initial {@code SSLContext} already set.
+ *
+ * @param factory the TLS factory to subscribe to
+ * @param purpose the server purpose (e.g. {@link TlsPurpose#WEB})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param requireTrustedClientCert whether to require (vs. request) a trusted client certificate
+ * @param allowInsecureConnection whether an untrusted client cert is accepted under optional client auth
+ * @param ciphers enabled cipher suites, or {@code null} for defaults
+ * @param protocols enabled protocols, or {@code null} for defaults
+ * @return the reloading factory and its subscription handle
+ */
+ public static ReloadableServerTls createReloadingServerFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString,
+ boolean requireTrustedClientCert,
+ boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ // Ask the factory first: a custom factory may natively supply the Jetty server factory (a
+ // well-known class). When it does, hand it back unstarted with the factory owning its reload and
+ // configuration; the framework overlays no consumer config on it. The default file-based factory
+ // returns empty() here, so the synthesized, self-reloading fallback below runs (the usual path).
+ Optional<TlsHandle<SslContextFactory.Server>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Server.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Server> handle = nativeFactory.get();
+ return new ReloadableServerTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
+ // Consumer config plus the factory's engine-policy companion (if any), before start. The resolved
+ // companion seeds the coordinator's last-good baseline so a companion-fetch failure on the very first
+ // rotation retains it rather than downgrading to consumer defaults.
+ SSLParameters initialBaseline = configureServerBaseline(sslContextFactory, factory, purpose,
+ sslProviderString, requireTrustedClientCert, allowInsecureConnection, ciphers, protocols);
+
+ // Each rotation re-requests the companion asynchronously (off the delivery thread) and applies it under
+ // a generation guard so an out-of-order companion cannot pin a stale context, retaining the last-good
+ // baseline across a transient companion failure. See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, sslContextFactory,
+ initialBaseline, (newContext, baseline) -> {
+ sslContextFactory.setSslContext(newContext);
+ // Re-apply the consumer defaults first so a companion member dropped by this delivery
+ // (notably client-auth) reverts to the consumer default rather than staying stuck from the
+ // previous companion, then overlay the generation-guarded, last-good companion.
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert,
+ allowInsecureConnection, ciphers, protocols);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery)
+ .join()
Review Comment:
`join()` here (and at line 259, and in `acquireNativeJettyFactory`/`resolveBaselineParameters`) makes these builders safe only by convention: for the default factory `createInstance` dispatches the task to `initContext.blockingExecutor()`, so calling `createReloadingServerFactory` *from* that executor deadlocks. That is plausible for a component wired with a single-threaded executor — the websocket proxy and the functions worker are the ones I'd worry about, and they are exactly the components `TlsFactorySupport.initContext` has a dedicated overload for. Could the javadoc state the constraint ("must not be called from the factory's blockingExecutor")?
Minor, same line: this `join()` does not unwrap `CompletionException`, unlike `TlsFactorySupport.initializeBlocking` which goes to some trouble to. A misconfigured purpose surfaces as `CompletionException: IllegalStateException: No TLS material configured for server purpose WEB` rather than the clean cause — a shame, because that underlying message is genuinely actionable.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/TlsMaterial.java:
##########
@@ -0,0 +1,108 @@
+/*
+ * 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.common.tls.impl;
+
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+import java.util.List;
+
+/**
+ * The loaded TLS material for one {@code TlsPurpose}: the private key, its certificate chain, and the
+ * trust certificates (PIP-478, internal to the default {@code FileBasedTlsFactory}).
+ *
+ * <p>This is a value type with structural {@code equals}/{@code hashCode} (a record). The default
+ * factory uses value equality to detect real rotations: a {@code TlsMaterialSource} that re-reads its
+ * files but finds identical content produces an {@code equal} instance, which suppresses spurious
+ * context rebuilds and reload callbacks (a file touched without content change fires nothing).
+ *
+ * <p>Role-neutral: the policy flags (insecure, hostname verification, client-auth requirement) and the
+ * protocols/ciphers are fixed at construction and live on the owning {@code TlsPolicy}/factory
+ * settings, not here — only the crypto material rotates.
+ *
+ * <p><b>Multi-identity keystores.</b> PEM material describes exactly one identity, carried in
+ * {@link #privateKey()}/{@link #keyCertChain()}. A keystore may hold several key entries (e.g. an RSA and
+ * an EC identity, or client identities issued by different accepted CAs); those are carried in full in
+ * {@link #keyEntries()} so the context builders can hand the <em>whole</em> set to a
+ * {@code KeyManagerFactory} and let JSSE select an alias by the peer's requested key type / acceptable
+ * issuers. For keystore material {@code privateKey}/{@code keyCertChain} mirror the first entry (so
+ * {@link #hasKeyMaterial()} and the value-equality rotation check remain meaningful), but the builders
+ * prefer {@code keyEntries} whenever it is non-empty.
+ *
+ * @param privateKey the private key (client key for mTLS, server key on the server side), or
+ * {@code null} when none is configured
+ * @param keyCertChain the certificate chain matching {@link #privateKey()} (never {@code null})
+ * @param trustCerts the trusted CA certificates, or empty to use the platform default trust store
+ * @param keyEntries every key entry of a keystore identity (empty for PEM/single-identity material)
+ */
+record TlsMaterial(PrivateKey privateKey, List<X509Certificate> keyCertChain, List<X509Certificate> trustCerts,
Review Comment:
Rotation suppression rests on this record's generated `equals`, which delegates to `PrivateKey.equals`. That's encoding equality for SunRsaSign and for BC/BCFIPS, so it works — but it's an implicit contract on a provider-supplied object, and the whole point of the `jcaProvider` axis is that the provider is swappable.
A provider whose `PrivateKey` doesn't override `equals` (identity semantics — non-extractable or HSM-backed keys are the realistic case) would make every refresh look changed, rebuilding and re-releasing the context on each poll, and on `AuthProvidedMaterialSource` on every acquisition. Worth a test that asserts value equality holds for keys manufactured through BCFIPS, since that's the target deployment for this axis.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/tls/DefaultBrokerTlsFactory.java:
##########
@@ -0,0 +1,195 @@
+/*
+ * 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.broker.tls;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Supplier;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.broker.ServiceConfiguration;
+import org.apache.pulsar.client.api.Authentication;
+import org.apache.pulsar.client.api.AuthenticationDataProvider;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactory;
+import org.apache.pulsar.common.tls.impl.FileBasedTlsFactorySettings;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The broker's default {@code PulsarTlsFactory}: a thin {@link FileBasedTlsFactory} whose purpose→
+ * policy map is composed from a {@link ServiceConfiguration} (PIP-478).
+ *
+ * <p>It lives in {@code pulsar-broker-common} — which owns the Jetty integration and the broker
+ * configuration — so that neither the SPI module nor {@code pulsar-common} carries broker-config
+ * knowledge. The class only <em>composes</em> the map; wiring it into the broker/proxy/web services is
+ * a later stage.
+ */
+public class DefaultBrokerTlsFactory extends FileBasedTlsFactory {
+
+ /**
+ * Construct the broker factory from an already-composed purpose→policy map.
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ super(policies, settings);
+ }
+
+ /**
+ * Construct a broker factory that additionally folds the broker-client authentication's TLS material
+ * over the {@link TlsPurpose#BROKER_CLIENT} file policy (PIP-478).
+ *
+ * @param policies the composed purpose→policy map
+ * @param settings the factory-wide engine/refresh/client-auth settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public DefaultBrokerTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ super(policies, settings, authMaterialSuppliers);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}.
+ *
+ * @param conf the broker service configuration
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf) {
+ return fromServiceConfiguration(conf, null);
+ }
+
+ /**
+ * Compose a {@link DefaultBrokerTlsFactory} from a {@link ServiceConfiguration}, optionally folding the
+ * broker's broker-client {@link Authentication} TLS material over the {@link TlsPurpose#BROKER_CLIENT}
+ * file policy (PIP-478) for the broker's own outbound (broker-to-broker / replication) connections.
+ *
+ * <p>The broker's server material is registered for the {@link TlsPurpose#BROKER},
+ * {@link TlsPurpose#PROXY} and {@link TlsPurpose#WEB} purposes; the broker's outbound
+ * (broker-to-broker) material for {@link TlsPurpose#BROKER_CLIENT}. When {@code brokerClientAuth} is
+ * supplied and a broker-client authentication plugin is configured, its in-memory cert/key override the
+ * {@code brokerClient*} file paths (auth-cert-wins), so the broker presents the right identity to its
+ * peers — the server-side mirror of the client TLS override hook.
+ *
+ * @param conf the broker service configuration
+ * @param brokerClientAuth the broker's broker-client authentication, or {@code null} for no fold
+ * @return an uninitialized broker factory (call {@code initialize(...)} before use)
+ */
+ public static DefaultBrokerTlsFactory fromServiceConfiguration(ServiceConfiguration conf,
+ Authentication brokerClientAuth) {
+ Map<TlsPurpose, TlsPolicy> policies = new LinkedHashMap<>();
+ TlsPolicy serverPolicy = serverPolicy(conf);
+ policies.put(TlsPurpose.BROKER, serverPolicy);
+ policies.put(TlsPurpose.PROXY, serverPolicy);
+ policies.put(TlsPurpose.WEB, serverPolicy);
Review Comment:
`WEB` is composed from `serverPolicy(conf)`, which reads `tlsProvider`, `tlsProtocols` and `tlsCiphers`. But the web service has its own keys in `ServiceConfiguration`:
- `webServiceTlsProvider` (line 214) — **defaults to `"Conscrypt"`, not blank**
- `webServiceTlsProtocols` (line 221)
- `webServiceTlsCiphers` (line 228)
This PR updates the `webServiceTlsProvider` doc to describe it as the Jetty JSSE (`SSLContext`) provider axis, but nothing here reads it. Wired as-is, every deployment on the Conscrypt default silently moves off Conscrypt for the web listener, and any web-specific protocol/cipher pinning is replaced by the binary-listener lists.
Is this deliberately deferred to the migration PR? If so, could it carry a `TODO` here (and ideally a failing-by-omission test), so it can't be lost between PRs in the series?
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/AuthProvidedMaterialSource.java:
##########
@@ -0,0 +1,214 @@
+/*
+ * 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.common.tls.impl;
+
+import java.io.InputStream;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Supplier;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.client.api.AuthenticationDataProvider;
+import org.apache.pulsar.client.api.KeyStoreParams;
+import org.apache.pulsar.common.util.tls.PemReader;
+
+/**
+ * A {@link MaterialSource} that folds a server component's broker-client {@code Authentication} TLS
+ * material over a file-based base source for the {@code BROKER_CLIENT} purpose (PIP-478). This is the
+ * server-side mirror of the client TLS override hook, preserving the PIP-337 auth-data behavior it
+ * supersedes:
+ * when the broker-client authentication plugin (e.g.
+ * {@code AuthenticationTls}) supplies key material, its in-memory certificate/key <em>override</em> the
+ * configured {@code brokerClient*} file paths, so a proxy or broker presents the right identity to the
+ * broker and forwarded-principal authorization works.
+ *
+ * <p>Precedence per material slot:
+ * <ul>
+ * <li><b>key + certificate chain</b>: the authentication plugin's material wins when it supplies both;
+ * otherwise the base file material is used;</li>
+ * <li><b>trust certificates</b>: the base (file) trust material wins; only when the base has none is the
+ * authentication plugin's trust-store stream consulted.</li>
+ * </ul>
+ *
+ * <p><b>Rotation.</b> {@link #refresh()} re-reads the authentication data on every call (the plugin may
+ * hot-reload its own files) and rebuilds the combined material, signalling a change through
+ * {@link TlsMaterial} value equality — so a rotated auth certificate is picked up independently of whether
+ * the base files changed. A transient authentication failure keeps the last-good combined material.
+ */
+@CustomLog
+final class AuthProvidedMaterialSource implements MaterialSource {
+
+ private final TlsMaterialSource base;
+ private final Supplier<AuthenticationDataProvider> authDataSupplier;
+ private final AtomicBoolean unpinnedAuthMaterialWarned = new AtomicBoolean();
+ private TlsMaterial cached;
+
+ AuthProvidedMaterialSource(TlsMaterialSource base, Supplier<AuthenticationDataProvider> authDataSupplier) {
+ this.base = Objects.requireNonNull(base, "base");
+ this.authDataSupplier = Objects.requireNonNull(authDataSupplier, "authDataSupplier");
+ }
+
+ @Override
+ public RefreshOutcome refresh() throws Exception {
Review Comment:
Unlike `TlsMaterialSource`, this has no mtime short-circuit — every `refresh()` calls the auth supplier and re-parses the certificate/key (and, on the pinned-provider path, deliberately re-reads the file rather than reusing the plugin's parsed objects).
`FileBasedTlsFactory.createOneShot` calls `currentMaterial()` on *every* acquisition, so on the acquire-per-connection paths a `BROKER_CLIENT` connection would re-parse key material per connection. `TlsMaterialSource` avoids this precisely because the baseline snapshot is cheap; the overlay gives that up.
Would it work to fold the base source's `changed` flag (currently discarded on line 75) together with a cheap auth-data identity check, and skip the re-parse when neither moved?
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/FileBasedTlsFactory.java:
##########
@@ -0,0 +1,768 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.util.ReferenceCountUtil;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import javax.net.ssl.SSLContext;
+import lombok.CustomLog;
+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.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsEndpoint;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The default, file-based {@link PulsarTlsFactory} (PIP-478).
+ *
+ * <p>Immutable after construction: the complete {@code TlsPurpose -> TlsPolicy} map and the
+ * factory-wide {@link FileBasedTlsFactorySettings} are fixed by the constructor and never mutated. The
+ * owning component (the v5 client builder, or {@code DefaultBrokerTlsFactory} on the server side)
+ * composes the final map before constructing the factory.
+ *
+ * <p>Natively supplies the Netty {@code SslContext} (on the configured engine — JDK or OpenSSL) and the
+ * JDK {@code SSLContext}; returns {@code empty()} for every other class (notably Jetty's
+ * {@code SslContextFactory.Server} and {@code SslContextFactory.Client}), which the framework synthesizes
+ * from the JDK {@code SSLContext}. It also
+ * returns {@code empty()} for the {@code javax.net.ssl.SSLParameters} companion (PIP-478): its engine policy
+ * (protocols, ciphers, client-auth mode, hostname verification) is baked natively into the Netty contexts it
+ * builds, so it exposes no separate baseline for the framework to overlay on those.
+ *
+ * <p>A JDK {@code SSLContext} cannot itself carry that policy — enabled protocols and cipher suites,
+ * algorithm constraints and the endpoint-identification algorithm are all per-engine {@code SSLParameters}
+ * settings — so the JDK context this factory returns is a <em>material carrier</em>: it holds the key and
+ * trust managers (built through the pinned providers) and nothing else. Every consumer of it applies the
+ * engine policy itself from the same {@link TlsPolicy}, which is what {@code JettyTlsFactory} does. A
+ * consumer that instead created engines straight from this {@code SSLContext} would get the provider defaults,
+ * so consumers must not do that.
+ *
+ * <p><b>Purpose resolution.</b> A request resolves the requested purpose directly against the configured
+ * {@code TlsPurpose -> TlsPolicy} map. When nothing is configured for the purpose, a {@code CLIENT}-role
+ * purpose resolves to the system default (OS trust store, no client certificate) and a {@code SERVER}-role
+ * purpose fails the request. A resolved-but-unbuildable request completes the future <em>exceptionally</em>
+ * — never {@code empty()}, which strictly means "unsupported {@code (purpose, class)} combination".
+ *
+ * <p><b>Rotation.</b> One {@link TlsMaterialSource} is shared per configured purpose. Server-side
+ * subscribers are pushed rebuilt instances by a background poll (interval from the settings, on the
+ * framework scheduler); client-side one-shot callers re-stat on each request and pick up rotation
+ * naturally. Because a re-stat consumes the source's change signal, an acquisition that observes a change
+ * first also fans it out to that purpose's subscribers, so a rotation is never swallowed by whoever happened
+ * to look first. A failed rebuild keeps the last-good instance, logs at WARN, and retries on the next
+ * change; a subscriber callback that throws is caught and logged, and the subscription stays live.
+ */
+@CustomLog
+public class FileBasedTlsFactory implements PulsarTlsFactory {
+
+ private final Map<TlsPurpose, RegisteredSource> registry;
+ private final FileBasedTlsFactorySettings settings;
+
+ private volatile TlsFactoryInitContext initContext;
+ private volatile TlsReloadMetrics metrics;
+ private volatile RegisteredSource systemDefaultSource;
+ private volatile ScheduledFuture<?> pollFuture;
+ private volatile boolean closed;
+
+ /**
+ * Construct an immutable file-based factory.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ this(policies, settings, Map.of());
+ }
+
+ /**
+ * Construct an immutable file-based factory that additionally folds an authentication plugin's TLS
+ * material over the configured file policy for the named purposes (the server-side {@code BROKER_CLIENT}
+ * fold — PIP-478). For a purpose present in {@code authMaterialSuppliers}, the supplier's
+ * {@code Authentication} material overrides the file policy's key/cert per
+ * {@link AuthProvidedMaterialSource} (auth-cert-wins); other purposes use the file policy unchanged.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ Objects.requireNonNull(policies, "policies must not be null");
+ this.settings = Objects.requireNonNull(settings, "settings must not be null");
+ Objects.requireNonNull(authMaterialSuppliers, "authMaterialSuppliers must not be null");
+ Map<TlsPurpose, RegisteredSource> built = new LinkedHashMap<>();
+ for (Map.Entry<TlsPurpose, TlsPolicy> entry : policies.entrySet()) {
+ TlsPurpose purpose = Objects.requireNonNull(entry.getKey(), "purpose key must not be null");
+ TlsPolicy policy = Objects.requireNonNull(entry.getValue(), "policy must not be null");
+ TlsMaterialSource fileSource = new TlsMaterialSource(policy);
+ Supplier<AuthenticationDataProvider> authSupplier = authMaterialSuppliers.get(purpose);
+ MaterialSource source = authSupplier == null
+ ? fileSource
+ : new AuthProvidedMaterialSource(fileSource, authSupplier);
+ built.put(purpose, new RegisteredSource(purpose, policy, source));
+ }
+ this.registry = Map.copyOf(built);
+ }
+
+ /**
+ * Adapt a component's broker-client {@link Authentication} to a per-refresh
+ * {@link AuthenticationDataProvider} supplier for use with the {@code BROKER_CLIENT} fold constructor.
+ * The supplier re-reads {@code getAuthData()} on each poll so credential rotation is observed; a checked
+ * {@link PulsarClientException} is rethrown unchecked and handled by the factory's keep-last-good poll.
+ *
+ * @param authentication the broker-client authentication plugin (never {@code null})
+ * @return a supplier of the plugin's current authentication data
+ */
+ public static Supplier<AuthenticationDataProvider> authMaterialSupplier(Authentication authentication) {
+ Objects.requireNonNull(authentication, "authentication must not be null");
+ return () -> {
+ try {
+ return resolveAuthData(authentication);
+ } catch (PulsarClientException e) {
+ throw new RuntimeException("Failed to obtain broker-client authentication TLS material", e);
+ }
+ };
+ }
+
+ // The BROKER_CLIENT TLS fold is host-agnostic — TLS key material does not vary by peer — so the
+ // host-less getAuthData() is exactly what we want; isolate its deprecation here.
+ @SuppressWarnings("deprecation")
+ private static AuthenticationDataProvider resolveAuthData(Authentication authentication)
+ throws PulsarClientException {
+ return authentication.getAuthData();
+ }
+
+ @Override
+ public CompletableFuture<Void> initialize(TlsFactoryInitContext context) {
+ try {
+ Objects.requireNonNull(context, "context must not be null");
+ // Required, not optional: every acquisition path in this factory reads files and parses key
+ // material. Without an executor the work would run inline on the caller's thread, which the SPI
+ // contract says may be a consumer event loop. Fail at wiring time rather than stalling a channel.
+ Objects.requireNonNull(context.blockingExecutor(),
+ "TlsFactoryInitContext.blockingExecutor() must not be null: FileBasedTlsFactory performs "
+ + "blocking file and key-material loading and must never run it on a consumer thread");
+ this.initContext = context;
+ // Cancel any poll scheduled by a prior initialize() so a second call does not orphan the first:
+ // the field is overwritten below and the old task would otherwise run forever.
+ ScheduledFuture<?> previousPoll = this.pollFuture;
+ if (previousPoll != null) {
+ previousPoll.cancel(false);
+ }
+ // Same reasoning for the metrics: a prior initialize() registered an observable gauge that stays
+ // registered on the meter until close(), so overwriting the field without closing it would leave
+ // an orphaned callback reporting stale per-purpose timestamps forever.
+ TlsReloadMetrics previousMetrics = this.metrics;
+ if (previousMetrics != null) {
+ previousMetrics.close();
+ }
+ this.metrics = TlsReloadMetrics.create(context.openTelemetry(), context.clock());
+ int interval = settings.refreshIntervalSeconds();
+ if (interval > 0 && context.scheduler() != null) {
+ this.pollFuture = context.scheduler().scheduleWithFixedDelay(
+ this::pollSafely, interval, interval, TimeUnit.SECONDS);
+ }
+ log.debug().attr("purposes", registry.keySet()).attr("refreshIntervalSeconds", interval)
+ .log("Initialized FileBasedTlsFactory");
+ return CompletableFuture.completedFuture(null);
+ } catch (Throwable t) {
+ return CompletableFuture.failedFuture(t);
+ }
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(TlsPurpose purpose, Class<T> instanceClass) {
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, TlsEndpoint endpoint, Class<T> instanceClass) {
+ // The default file-based factory serves purpose-scoped material and ignores the endpoint hint.
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, Class<T> instanceClass, Consumer<T> onLoadOrReload) {
+ if (onLoadOrReload == null) {
+ // SPI contract: argument-validation failures complete the returned future exceptionally — this
+ // method never throws on the calling thread.
+ return CompletableFuture.failedFuture(new NullPointerException("onLoadOrReload must not be null"));
+ }
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ synchronized (source) {
+ // FIX F: close() runs releaseAll() under this same source lock, and may have completed after
+ // the outer closed-check but before this task acquired the lock. Re-check here so we never
+ // build+cache+deliver a context (and register a subscription) whose factory-owned reference
+ // would then never be released — that would leak past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ Subscription<T> subscription = new Subscription<>(instanceClass, onLoadOrReload);
+ // Initial delivery happens-before the returned future completes (same thread, ordered).
+ subscription.deliver(instance);
+ source.subscriptions.add(subscription);
+ return Optional.of((TlsHandle<T>) new SubscriptionHandle<>(source, subscription));
+ }
+ });
+ }
+
+ private <T> CompletableFuture<Optional<TlsHandle<T>>> createOneShot(TlsPurpose purpose, Class<T> instanceClass) {
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ synchronized (source) {
+ // FIX F: re-check under the source lock (see createInstance above) so a task racing a
+ // concurrent close()/releaseAll() never builds+retains a context that then leaks past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ retain(instance);
+ return Optional.of((TlsHandle<T>) new OneShotHandle<>(instance));
+ }
+ });
+ }
+
+ /**
+ * Load (or reuse the cached) instance of {@code instanceClass} for the resolved source, recording a
+ * {@code pulsar.tls.reload} attempt for the source's purpose. A resolution failure upstream (an
+ * unconfigured server purpose) is a startup configuration error and is not counted here — only actual
+ * material loads are. Must be called while holding the source monitor.
+ *
+ * <p>Success is counted only for a <em>real</em> (re)load, mirroring the poll path: the first build of a
+ * context class for this source, or a refresh that found changed material. A repeat one-shot acquisition
+ * that re-serves the memoized context (every new connection, on the acquire-per-connection paths) is not a
+ * reload — counting it would inflate {@code pulsar.tls.reload} and keep advancing
+ * {@code pulsar.tls.last_reload_success}, masking exactly the stalled rotation the Monitoring section
+ * alerts on. Failures stay unconditional: an attempt that threw is always worth counting.
+ */
+ private <T> T loadInitialInstance(RegisteredSource source, Class<T> instanceClass) throws Exception {
+ // Hoisted out of the try so the catch can tell whether this call already CONSUMED a rotation before
+ // failing (see the comment on the catch below). Null means currentMaterial() itself threw, which
+ // commits no baseline and so consumes nothing.
+ MaterialSource.RefreshOutcome outcome = null;
+ try {
+ outcome = source.currentMaterial();
+ // Sampled before acquireInstance, which is what populates the memo (both calls run under the
+ // source monitor held by the caller, so no other acquisition can interleave).
+ boolean firstBuild = source.cachedInstance(instanceClass) == null;
+ T instance = source.acquireInstance(instanceClass, outcome.material(), settings);
+ // Rotation fan-out: currentMaterial() CONSUMES the source's change signal (refresh() commits the new
+ // mtime baseline), so whoever refreshes first is the only caller that ever sees changed=true. Without
+ // this, a one-shot acquisition (or an initial subscribing acquisition) that observes a rotation first
+ // leaves every later poll reporting changed=false and the subscribers on this same purpose wedged on
+ // the pre-rotation instance forever — e.g. an https:// client whose FrameworkHttpClientFactory
+ // subscribes to CLIENT_DEFAULT while another path acquires one-shot on it. Deliver the observed
+ // change here, exactly as the poll would have; a delivery failure arms pendingRedeliver so the next
+ // poll retries. No extra metric is recorded — this shares the single recordLoad below.
+ // Also drive the retry when a previous rotation's fan-out failed: the poll is the usual driver,
+ // but it is disabled entirely when refreshIntervalSeconds <= 0, and even when enabled an
+ // acquisition may get here first. Without this, a subscriber wedged by a failed rebuild would
+ // stay on the pre-rotation instance until the files changed again.
+ boolean retryPending = source.pendingRedeliver();
+ boolean delivered = true;
+ if (outcome.changed() || retryPending) {
+ delivered = source.deliverToSubscribers(outcome.material(), settings);
+ }
+ if (outcome.changed() || retryPending || firstBuild) {
+ recordLoad(source.purpose, delivered);
+ }
+ return instance;
+ } catch (Exception e) {
+ recordLoad(source.purpose, false);
+ // The material parsed (the baseline is committed) but building or delivering the context failed.
+ // currentMaterial() has therefore already CONSUMED this rotation's change signal, so every later
+ // poll would report changed=false and — without arming the redeliver flag here — return early,
+ // leaving the subscribers wedged on the pre-rotation instance until the files change again.
+ // deliverToSubscribers arms the flag itself on a partial delivery failure; this covers the case
+ // where the failure happened before it was ever reached.
+ if (outcome != null && outcome.changed()) {
+ source.armRedeliver();
+ }
+ // Keep-last-good (PIP-478): a one-shot (or initial subscribing) acquisition during a
+ // non-atomic rotation window — e.g. the cert file briefly unreadable while it is being replaced —
+ // must not fail when a prior load already built a context of this class. Serve that last-good
+ // instance and WARN; the reload-failure metric was recorded above. Fail only when there is no
+ // last-good to fall back on (a genuine startup misconfiguration, per the fail-fast contract).
+ T cached = source.cachedInstance(instanceClass);
+ if (cached != null) {
+ log.warn().attr("purpose", source.purpose).exception(e)
+ .log("Failed to load TLS material; serving the last-good instance");
+ return cached;
+ }
+ throw e;
+ }
+ }
+
+ private void recordLoad(TlsPurpose purpose, boolean success) {
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.recordLoad(purpose, success);
+ }
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ ScheduledFuture<?> poll = this.pollFuture;
+ if (poll != null) {
+ poll.cancel(false);
+ }
+ for (RegisteredSource source : registry.values()) {
+ source.releaseAll();
+ }
+ RegisteredSource systemDefault = this.systemDefaultSource;
+ if (systemDefault != null) {
+ systemDefault.releaseAll();
+ }
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.close();
+ }
+ }
+
+ /**
+ * Resolve a requested purpose to the {@link RegisteredSource} that owns its material, applying the
+ * role's terminal-resolution rule when nothing is configured for the purpose.
+ *
+ * @throws TlsMaterialUnavailableException when a server-role purpose has no material configured
+ */
+ private RegisteredSource resolve(TlsPurpose purpose) {
+ Objects.requireNonNull(purpose, "purpose must not be null");
+ RegisteredSource source = registry.get(purpose);
+ if (source != null) {
+ return source;
+ }
+ if (purpose.role() == TlsPurpose.Role.CLIENT) {
+ return systemDefaultSource();
+ }
+ throw new TlsMaterialUnavailableException(
+ "No TLS material configured for server purpose " + purpose);
+ }
+
+ private RegisteredSource systemDefaultSource() {
+ RegisteredSource existing = this.systemDefaultSource;
+ if (existing != null) {
+ return existing;
+ }
+ synchronized (this) {
+ if (this.systemDefaultSource == null) {
+ // System default: verify hostnames, OS trust store, no client certificate. A constant
+ // source (no files, never rotates).
+ TlsPolicy defaultPolicy = TlsPolicy.builder().build();
+ this.systemDefaultSource = new RegisteredSource(
+ TlsPurpose.CLIENT_DEFAULT, defaultPolicy, null);
+ }
+ return this.systemDefaultSource;
+ }
+ }
+
+ private void pollSafely() {
+ if (closed) {
+ return;
+ }
+ try {
+ for (RegisteredSource source : registry.values()) {
+ source.poll(settings, metrics);
+ }
+ } catch (Throwable t) {
+ log.warn().exception(t).log("Unexpected error during TLS material poll");
+ }
+ }
+
+ private <R> CompletableFuture<R> runAsync(Callable<R> task) {
+ CompletableFuture<R> future = new CompletableFuture<>();
+ TlsFactoryInitContext context = this.initContext;
+ // initialize() rejects a null blockingExecutor, so the caller-thread fallback is reachable only before
+ // initialize() has run — a direct-construction path (tests, or a component acquiring during its own
+ // startup) that is by definition not on a consumer event loop.
+ Executor executor = context != null ? context.blockingExecutor() : Runnable::run;
+ try {
+ executor.execute(() -> {
+ try {
+ R result = task.call();
+ if (!future.complete(result)) {
+ // The caller cancelled (or otherwise completed) the future while the acquisition was
+ // still running, so nothing will ever receive this handle. The task has already
+ // retained the context on its behalf, and with the finalizer-free OPENSSL_REFCNT
+ // engine an unbalanced retain is a permanent native leak — dispose the orphan here.
+ disposeOrphan(result);
+ }
+ } catch (Throwable t) {
+ future.completeExceptionally(t);
+ }
+ });
+ } catch (Throwable t) {
+ future.completeExceptionally(t);
+ }
+ return future;
+ }
+
+ /**
+ * Release a handle that was built but could not be delivered to its caller. Both acquisition forms
+ * produce an {@code Optional<TlsHandle<?>>}, and disposing it is exactly what the caller would have done:
+ * it drops the one-shot's retained reference, or unregisters the subscription and releases its borrows.
+ */
+ private static void disposeOrphan(Object result) {
+ if (result instanceof Optional<?> optional && optional.orElse(null) instanceof TlsHandle<?> handle) {
+ try {
+ handle.dispose();
+ } catch (Throwable t) {
+ log.warn().exception(t).log("Failed to dispose an undelivered TLS handle");
+ }
+ }
+ }
+
+ private static boolean isSupported(Class<?> instanceClass) {
+ return instanceClass == SslContext.class || instanceClass == SSLContext.class;
+ }
+
+ private static void retain(Object instance) {
+ if (instance != null) {
+ ReferenceCountUtil.retain(instance);
+ }
+ }
+
+ private static void release(Object instance) {
+ if (instance != null) {
+ ReferenceCountUtil.release(instance);
+ }
+ }
+
+ /**
+ * A configured purpose's material source together with the cached, factory-owned context instances
+ * and the active subscriptions. All state is guarded by the instance monitor.
+ */
+ private static final class RegisteredSource {
+ private final TlsPurpose purpose;
+ private final TlsPolicy policy;
+ // Null for the system-default source, whose constant material never rotates.
+ private final MaterialSource source;
+ private final CopyOnWriteArrayList<Subscription<?>> subscriptions = new CopyOnWriteArrayList<>();
+
+ private SslContext nettyContext;
+ private TlsMaterial nettyMaterial;
+ private SSLContext jdkContext;
+ private TlsMaterial jdkMaterial;
+ // Set when a rotation's rebuild/delivery to some subscriber failed, so the next poll re-attempts the
+ // rebuild even if the source now reports changed=false (PIP-478 L1 reload-wedge guard).
+ private boolean pendingRedeliver;
+
+ RegisteredSource(TlsPurpose purpose, TlsPolicy policy, MaterialSource source) {
+ this.purpose = purpose;
+ this.policy = policy;
+ this.source = source;
+ }
+
+ /**
+ * Refresh the material, reporting whether it changed in value. The system-default source has no
+ * backing files, so it never changes — its single context build is counted via the first-build check
+ * in {@link FileBasedTlsFactory#loadInitialInstance}.
+ */
+ synchronized MaterialSource.RefreshOutcome currentMaterial() throws Exception {
+ if (source == null) {
+ return new MaterialSource.RefreshOutcome(TlsMaterial.SYSTEM_DEFAULT, false);
+ }
+ return source.refresh();
+ }
+
+ /**
+ * Return the cached context of the requested class, rebuilding it (and releasing the superseded
+ * one) only when the material changed in value. The returned instance is the factory-owned memo;
+ * callers that hand it to a consumer {@link FileBasedTlsFactory#retain(Object) retain} it.
+ */
+ synchronized <T> T acquireInstance(Class<T> instanceClass, TlsMaterial material,
+ FileBasedTlsFactorySettings settings) throws Exception {
+ if (instanceClass == SslContext.class) {
+ if (nettyContext == null || !material.equals(nettyMaterial)) {
+ SslContext built = purpose.role() == TlsPurpose.Role.SERVER
+ ? TlsContexts.buildNettyServerContext(material, policy, settings.engineProvider(),
+ settings.requireTrustedClientCert())
+ : TlsContexts.buildNettyClientContext(material, policy, settings.engineProvider());
+ release(nettyContext);
+ nettyContext = built;
+ nettyMaterial = material;
+ }
+ return instanceClass.cast(nettyContext);
+ }
+ if (instanceClass == SSLContext.class) {
+ if (jdkContext == null || !material.equals(jdkMaterial)) {
+ jdkContext = TlsContexts.buildJdkContext(material, policy);
+ jdkMaterial = material;
+ }
+ return instanceClass.cast(jdkContext);
+ }
+ throw new IllegalArgumentException("Unsupported instance class " + instanceClass);
+ }
+
+ /**
+ * The last-good cached context of the requested class, or {@code null} if none has been built yet.
+ * Used by the keep-last-good one-shot path when a fresh load fails mid-rotation.
+ */
+ synchronized <T> T cachedInstance(Class<T> instanceClass) {
+ if (instanceClass == SslContext.class && nettyContext != null) {
+ return instanceClass.cast(nettyContext);
+ }
+ if (instanceClass == SSLContext.class && jdkContext != null) {
+ return instanceClass.cast(jdkContext);
+ }
+ return null;
+ }
+
+ synchronized void poll(FileBasedTlsFactorySettings settings, TlsReloadMetrics metrics) {
+ if (source == null || subscriptions.isEmpty()) {
+ return;
+ }
+ MaterialSource.RefreshOutcome outcome;
+ try {
+ outcome = source.refresh();
+ } catch (Exception e) {
+ // Keep-last-good: leave every subscription on its current instance and retry next change.
+ recordLoad(metrics, false);
+ log.warn().attr("purpose", purpose).exception(e)
+ .log("Failed to reload TLS material; keeping the last-good instance");
+ return;
+ }
+ // A poll that finds no change is not a reload — do not count it, so the reload counter and the
+ // last-success gauge reflect real (re)load events only. But if a prior rotation's rebuild/delivery
+ // to some subscriber failed (pendingRedeliver), retry it even when the source now reports
+ // changed=false: otherwise, once the source commits the new baseline, every later poll sees
+ // changed=false and that subscriber stays wedged on the old instance until the next file change
+ // (L1). The retry rebuilds against the current last-good material.
+ if (!outcome.changed() && !pendingRedeliver) {
+ return;
+ }
+ recordLoad(metrics, deliverToSubscribers(outcome.material(), settings));
+ }
+
+ /**
+ * Rebuild and hand {@code material} to every live subscription, reporting whether all succeeded. Called
+ * both by the background poll and by an acquisition that consumed the source's change signal first
+ * (see {@link FileBasedTlsFactory#loadInitialInstance}), so a rotation reaches the subscribers no matter
+ * which caller observed it. Records no metric itself — each caller counts the (re)load once.
+ *
+ * <p><b>Consumer callbacks run while this source's monitor is held</b>, which keeps a rotation's
+ * rebuild-and-publish atomic against a concurrent acquisition. The cost is a reentrancy constraint on
+ * consumers: a reload callback must not call {@code createInstance} for the same purpose and block on
+ * the returned future, because that acquisition needs this same monitor and would deadlock when the
+ * blocking executor runs it on another thread. Consumers are expected to do only a volatile store in
+ * the callback (swap the context they hand to new connections) and never to block in it.
+ */
+ synchronized boolean deliverToSubscribers(TlsMaterial material, FileBasedTlsFactorySettings settings) {
Review Comment:
The Javadoc is admirably explicit that consumer callbacks run under this monitor and that a callback must not `createInstance` for the same purpose and block on the future. My concern is that the constraint is documented but unenforceable, and the consumers are written in later PRs by people who won't necessarily read this class.
Would it be feasible to snapshot the rebuilt instances under the lock and invoke the callbacks outside it? The atomicity you're protecting is rebuild-and-publish against a concurrent acquisition, which the `acquireInstance` memo already provides — the callback itself is contractually a volatile store. If it has to stay inside the lock, could the deadlock at least be made loud (e.g. a re-entrancy check that throws with a pointer to this Javadoc) rather than a hang?
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/TlsMaterialSource.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.common.tls.impl;
+
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.attribute.FileTime;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.PrivateKey;
+import java.security.Provider;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.common.util.tls.PemReader;
+import org.apache.pulsar.tls.TlsPolicy;
+
+/**
+ * Loads, watches and caches ONE material set (the crypto for a single {@code TlsPurpose}) from a
+ * {@link TlsPolicy} for the default {@code FileBasedTlsFactory} (PIP-478).
+ *
+ * <p>This collapses the old branch's {@code FileBasedClient/ServerTlsMaterialSource} split into a
+ * single, role-neutral class: the difference was only the value builder and a few flags, while the
+ * watch/cache machinery was duplicated verbatim.
+ *
+ * <p><b>Keystore-over-PEM per-field precedence.</b> For each of the three material slots (trust
+ * certs, private key, key certificate chain) the keystore location wins when set, otherwise the PEM
+ * location is used. PEM material is loaded via {@link PemReader}; keystores (PKCS12/JKS) are read
+ * with the raw {@link KeyStore} API and an alias walk.
+ *
+ * <p><b>Rotation detection (fixed mtime baseline).</b> Change detection snapshots the modification
+ * times of every configured file, and — unlike the old {@code FileModifiedTimeUpdater}-based scheme,
+ * which advanced the baseline <em>before</em> the load and so never retried a failed rotation until the
+ * next mtime change — commits the new baseline <strong>only after a successful load</strong>. A load
+ * that throws (a half-written or invalid rotated file, the canonical incident) leaves both the baseline
+ * and the last-good material untouched, so the next poll observes the same change again and retries.
+ * When mtimes advanced but the loaded material is byte-for-byte {@link TlsMaterial#equals(Object)
+ * equal} to the cached one (a file touched without content change), the baseline is committed but no
+ * change is signalled.
+ *
+ * <p><b>Fail-closed trust and identity.</b> A configured keystore truststore that holds zero certificates
+ * is rejected rather than loaded as an empty trust list: downstream, an empty trust list is
+ * indistinguishable from "no truststore configured" and both context builders then install the platform
+ * default trust manager, silently trusting every public CA. v4's {@code KeyStoreSSLContext} initialised the
+ * {@code TrustManagerFactory} with the explicit store and rejected every peer. The same applies to the
+ * identity axis: a keystore with no usable key entry, or a PEM certificate without its private key, fails
+ * the load instead of degrading to "no identity presented", which would surface only as a much later
+ * handshake failure. The PEM trust axis is deliberately NOT hardened (v4 fell back to the platform trust
+ * store for an empty trust file and deployments rely on that), and a PEM key without a certificate is a
+ * WARN, not a failure, for the same v4-parity reason.
+ *
+ * <p>Not thread-safe on its own; the owning factory serialises access under its per-source monitor.
+ */
+@CustomLog
+final class TlsMaterialSource implements MaterialSource {
+
+ /** Sentinel modification time recorded for a path that is currently missing or unreadable. */
+ private static final FileTime MISSING = FileTime.fromMillis(Long.MIN_VALUE);
+
+ private final TlsPolicy policy;
+ private final List<String> watchedPaths;
+ // Resolved once: the policy's jcaProvider (KeyStore/CertificateFactory/KeyFactory axis), or null when the
+ // policy pins none (the JVM provider search order). Resolving here keeps the ServiceLoader walk off the
+ // per-load path and fails loudly at factory init for an unresolvable name.
+ private final Provider jcaProvider;
+
+ private Map<String, FileTime> baseline;
+ private TlsMaterial cached;
+
+ TlsMaterialSource(TlsPolicy policy) {
+ this.policy = Objects.requireNonNull(policy, "policy must not be null");
+ this.watchedPaths = watchedPathsFor(policy);
+ this.jcaProvider = JcaProviders.resolveNamedProvider(policy.jcaProvider());
+ }
+
+ TlsPolicy policy() {
+ return policy;
+ }
+
+ /**
+ * @return the resolved JCA (material) provider, or {@code null} when the policy pins none. Package-private
+ * so the {@code BROKER_CLIENT} auth overlay parses its material through the same provider.
+ */
+ Provider jcaProvider() {
+ return jcaProvider;
+ }
+
+ /**
+ * Re-stat the configured files, reloading the material when they changed since the last successful
+ * load. Returns the current (possibly rebuilt) material together with whether it changed in value.
+ *
+ * @return the refresh outcome
+ * @throws Exception if the material could not be loaded (the last-good material and baseline are
+ * left untouched so the next call retries)
+ */
+ @Override
+ public MaterialSource.RefreshOutcome refresh() throws Exception {
+ Map<String, FileTime> snapshot = snapshotModificationTimes();
Review Comment:
Change detection is mtime-only. On filesystems with 1-second mtime granularity, a certificate replaced twice within the same second — or restored with a preserved mtime — is missed until the next real change. v4's `FileModifiedTimeUpdater` had the same weakness so this isn't a regression, and the fixed-baseline scheme here is a clear improvement on it.
But since this is the rewrite, including file size in the snapshot alongside `FileTime` would close most of it for free (`Files.readAttributes` returns both in one syscall). Not blocking; just cheap while the code is being written.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/FileBasedTlsFactory.java:
##########
@@ -0,0 +1,768 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.util.ReferenceCountUtil;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import javax.net.ssl.SSLContext;
+import lombok.CustomLog;
+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.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsEndpoint;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The default, file-based {@link PulsarTlsFactory} (PIP-478).
+ *
+ * <p>Immutable after construction: the complete {@code TlsPurpose -> TlsPolicy} map and the
+ * factory-wide {@link FileBasedTlsFactorySettings} are fixed by the constructor and never mutated. The
+ * owning component (the v5 client builder, or {@code DefaultBrokerTlsFactory} on the server side)
+ * composes the final map before constructing the factory.
+ *
+ * <p>Natively supplies the Netty {@code SslContext} (on the configured engine — JDK or OpenSSL) and the
+ * JDK {@code SSLContext}; returns {@code empty()} for every other class (notably Jetty's
+ * {@code SslContextFactory.Server} and {@code SslContextFactory.Client}), which the framework synthesizes
+ * from the JDK {@code SSLContext}. It also
+ * returns {@code empty()} for the {@code javax.net.ssl.SSLParameters} companion (PIP-478): its engine policy
+ * (protocols, ciphers, client-auth mode, hostname verification) is baked natively into the Netty contexts it
+ * builds, so it exposes no separate baseline for the framework to overlay on those.
+ *
+ * <p>A JDK {@code SSLContext} cannot itself carry that policy — enabled protocols and cipher suites,
+ * algorithm constraints and the endpoint-identification algorithm are all per-engine {@code SSLParameters}
+ * settings — so the JDK context this factory returns is a <em>material carrier</em>: it holds the key and
+ * trust managers (built through the pinned providers) and nothing else. Every consumer of it applies the
+ * engine policy itself from the same {@link TlsPolicy}, which is what {@code JettyTlsFactory} does. A
+ * consumer that instead created engines straight from this {@code SSLContext} would get the provider defaults,
+ * so consumers must not do that.
+ *
+ * <p><b>Purpose resolution.</b> A request resolves the requested purpose directly against the configured
+ * {@code TlsPurpose -> TlsPolicy} map. When nothing is configured for the purpose, a {@code CLIENT}-role
+ * purpose resolves to the system default (OS trust store, no client certificate) and a {@code SERVER}-role
+ * purpose fails the request. A resolved-but-unbuildable request completes the future <em>exceptionally</em>
+ * — never {@code empty()}, which strictly means "unsupported {@code (purpose, class)} combination".
+ *
+ * <p><b>Rotation.</b> One {@link TlsMaterialSource} is shared per configured purpose. Server-side
+ * subscribers are pushed rebuilt instances by a background poll (interval from the settings, on the
+ * framework scheduler); client-side one-shot callers re-stat on each request and pick up rotation
+ * naturally. Because a re-stat consumes the source's change signal, an acquisition that observes a change
+ * first also fans it out to that purpose's subscribers, so a rotation is never swallowed by whoever happened
+ * to look first. A failed rebuild keeps the last-good instance, logs at WARN, and retries on the next
+ * change; a subscriber callback that throws is caught and logged, and the subscription stays live.
+ */
+@CustomLog
+public class FileBasedTlsFactory implements PulsarTlsFactory {
+
+ private final Map<TlsPurpose, RegisteredSource> registry;
+ private final FileBasedTlsFactorySettings settings;
+
+ private volatile TlsFactoryInitContext initContext;
+ private volatile TlsReloadMetrics metrics;
+ private volatile RegisteredSource systemDefaultSource;
+ private volatile ScheduledFuture<?> pollFuture;
+ private volatile boolean closed;
+
+ /**
+ * Construct an immutable file-based factory.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ this(policies, settings, Map.of());
+ }
+
+ /**
+ * Construct an immutable file-based factory that additionally folds an authentication plugin's TLS
+ * material over the configured file policy for the named purposes (the server-side {@code BROKER_CLIENT}
+ * fold — PIP-478). For a purpose present in {@code authMaterialSuppliers}, the supplier's
+ * {@code Authentication} material overrides the file policy's key/cert per
+ * {@link AuthProvidedMaterialSource} (auth-cert-wins); other purposes use the file policy unchanged.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ Objects.requireNonNull(policies, "policies must not be null");
+ this.settings = Objects.requireNonNull(settings, "settings must not be null");
+ Objects.requireNonNull(authMaterialSuppliers, "authMaterialSuppliers must not be null");
+ Map<TlsPurpose, RegisteredSource> built = new LinkedHashMap<>();
+ for (Map.Entry<TlsPurpose, TlsPolicy> entry : policies.entrySet()) {
+ TlsPurpose purpose = Objects.requireNonNull(entry.getKey(), "purpose key must not be null");
+ TlsPolicy policy = Objects.requireNonNull(entry.getValue(), "policy must not be null");
+ TlsMaterialSource fileSource = new TlsMaterialSource(policy);
+ Supplier<AuthenticationDataProvider> authSupplier = authMaterialSuppliers.get(purpose);
+ MaterialSource source = authSupplier == null
+ ? fileSource
+ : new AuthProvidedMaterialSource(fileSource, authSupplier);
+ built.put(purpose, new RegisteredSource(purpose, policy, source));
+ }
+ this.registry = Map.copyOf(built);
+ }
+
+ /**
+ * Adapt a component's broker-client {@link Authentication} to a per-refresh
+ * {@link AuthenticationDataProvider} supplier for use with the {@code BROKER_CLIENT} fold constructor.
+ * The supplier re-reads {@code getAuthData()} on each poll so credential rotation is observed; a checked
+ * {@link PulsarClientException} is rethrown unchecked and handled by the factory's keep-last-good poll.
+ *
+ * @param authentication the broker-client authentication plugin (never {@code null})
+ * @return a supplier of the plugin's current authentication data
+ */
+ public static Supplier<AuthenticationDataProvider> authMaterialSupplier(Authentication authentication) {
+ Objects.requireNonNull(authentication, "authentication must not be null");
+ return () -> {
+ try {
+ return resolveAuthData(authentication);
+ } catch (PulsarClientException e) {
+ throw new RuntimeException("Failed to obtain broker-client authentication TLS material", e);
+ }
+ };
+ }
+
+ // The BROKER_CLIENT TLS fold is host-agnostic — TLS key material does not vary by peer — so the
+ // host-less getAuthData() is exactly what we want; isolate its deprecation here.
+ @SuppressWarnings("deprecation")
+ private static AuthenticationDataProvider resolveAuthData(Authentication authentication)
+ throws PulsarClientException {
+ return authentication.getAuthData();
+ }
+
+ @Override
+ public CompletableFuture<Void> initialize(TlsFactoryInitContext context) {
+ try {
+ Objects.requireNonNull(context, "context must not be null");
+ // Required, not optional: every acquisition path in this factory reads files and parses key
+ // material. Without an executor the work would run inline on the caller's thread, which the SPI
+ // contract says may be a consumer event loop. Fail at wiring time rather than stalling a channel.
+ Objects.requireNonNull(context.blockingExecutor(),
+ "TlsFactoryInitContext.blockingExecutor() must not be null: FileBasedTlsFactory performs "
+ + "blocking file and key-material loading and must never run it on a consumer thread");
+ this.initContext = context;
+ // Cancel any poll scheduled by a prior initialize() so a second call does not orphan the first:
+ // the field is overwritten below and the old task would otherwise run forever.
+ ScheduledFuture<?> previousPoll = this.pollFuture;
+ if (previousPoll != null) {
+ previousPoll.cancel(false);
+ }
+ // Same reasoning for the metrics: a prior initialize() registered an observable gauge that stays
+ // registered on the meter until close(), so overwriting the field without closing it would leave
+ // an orphaned callback reporting stale per-purpose timestamps forever.
+ TlsReloadMetrics previousMetrics = this.metrics;
+ if (previousMetrics != null) {
+ previousMetrics.close();
+ }
+ this.metrics = TlsReloadMetrics.create(context.openTelemetry(), context.clock());
Review Comment:
`TlsReloadMetrics.create(...)` is on the mandatory path in `initialize()` — not behind a flag, a capability check or a try/catch. `opentelemetry-api` is `compileOnly` in `pulsar-common` (pre-existing, from #26222), so any runtime classpath without it gets a `NoClassDefFoundError` here once this becomes the default TLS path for the client.
The build-file comment says "the real OpenTelemetry root is always supplied at runtime by the owning component", which covers the *instance* but not the *classes*. Could you confirm every consumer that will construct this factory — including the shaded client jars — carries `opentelemetry-api` at runtime? If it genuinely always does, `implementation` would state that; if not, this construction needs to degrade rather than throw.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/TlsContexts.java:
##########
@@ -0,0 +1,494 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.ApplicationProtocolConfig;
+import io.netty.handler.ssl.ClientAuth;
+import io.netty.handler.ssl.IdentityCipherSuiteFilter;
+import io.netty.handler.ssl.JdkSslContext;
+import io.netty.handler.ssl.SslContext;
+import io.netty.handler.ssl.SslContextBuilder;
+import io.netty.handler.ssl.SslProvider;
+import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
+import java.security.GeneralSecurityException;
+import java.security.KeyStoreException;
+import java.security.Provider;
+import java.util.Arrays;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import lombok.CustomLog;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.common.util.tls.JdkSslContexts;
+import org.apache.pulsar.tls.TlsPolicy;
+
+/**
+ * Builds the well-known TLS instance classes from loaded {@link TlsMaterial} and a {@link TlsPolicy}
+ * for the default {@code FileBasedTlsFactory}, and synthesizes the richer objects from a JDK
+ * {@code SSLContext} for the framework fallback (PIP-478).
+ *
+ * <p>This class owns TLS context assembly end-to-end, composing the focused low-level primitives rather
+ * than a general-purpose helper: it consumes already-parsed in-memory {@link TlsMaterial} (PEM and keystore
+ * parsing lives in the material sources), builds the JDK {@code SSLContext} through {@link JdkSslContexts},
+ * and assembles the Netty {@link SslContext} objects inline through {@link SslContextBuilder}. The Netty
+ * contexts are built here rather than delegated because two per-context settings must be baked at build time
+ * from the in-memory material:
+ * <ul>
+ * <li><b>Client hostname verification</b> — set via
+ * {@link SslContextBuilder#endpointIdentificationAlgorithm(String)} to {@code "HTTPS"} when the
+ * policy enables it. It cannot be left to a per-{@code SSLEngine} override: Netty's OpenSSL
+ * backend fixes the endpoint-identification algorithm at build time.</li>
+ * <li><b>Server insecure trust</b> — {@code policy.allowInsecureConnection()} on a
+ * server context installs {@link InsecureTrustManagerFactory#INSTANCE} so an untrusted client
+ * certificate still completes the handshake and remains available for TLS authentication, while
+ * client-auth stays {@link ClientAuth#REQUIRE}/{@link ClientAuth#OPTIONAL} (never
+ * {@link ClientAuth#NONE}, per {@code tlsRequireTrustedClientCert} semantics).</li>
+ * </ul>
+ */
+@CustomLog
+public final class TlsContexts {
+
+ /**
+ * The default enabled TLS protocol set, applied whenever the effective protocol list is empty — a policy
+ * with no {@code protocols()}, or a synthesized context whose factory companion set none. This preserves
+ * the {@code {TLSv1.3, TLSv1.2}} floor {@code DefaultPulsarSslFactory} forces at engine build:
+ * without it the PIP-478 path would silently defer to the JVM/provider default protocol set, a
+ * security-relevant drift on upgrade.
+ */
+ public static final List<String> DEFAULT_ENABLED_PROTOCOLS = List.of("TLSv1.3", "TLSv1.2");
+
+ // WARN-once dedup for the insecure (trust-all) mode, keyed by policy value so a rotation's context rebuilds
+ // (and both the Netty and JDK builds of the same policy) log at most once.
+ private static final Set<TlsPolicy> INSECURE_WARNED = ConcurrentHashMap.newKeySet();
Review Comment:
`INSECURE_WARNED` is an unbounded static set that is never cleared, and `TlsPolicy` holds `keyStorePassword`/`trustStorePassword` as fields — so this pins plaintext passwords for the JVM lifetime, for every distinct insecure policy the process ever builds.
Fine for a broker with a fixed policy set; less so for a long-lived process constructing many clients with varying paths (the proxy, function workers, test suites). Since the only thing needed is dedup, keying on `policy.hashCode()` in a bounded structure — or just on the trust/cert paths — would avoid retaining the policy objects themselves.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/FileBasedTlsFactory.java:
##########
@@ -0,0 +1,768 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.util.ReferenceCountUtil;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import javax.net.ssl.SSLContext;
+import lombok.CustomLog;
+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.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsEndpoint;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The default, file-based {@link PulsarTlsFactory} (PIP-478).
+ *
+ * <p>Immutable after construction: the complete {@code TlsPurpose -> TlsPolicy} map and the
+ * factory-wide {@link FileBasedTlsFactorySettings} are fixed by the constructor and never mutated. The
+ * owning component (the v5 client builder, or {@code DefaultBrokerTlsFactory} on the server side)
+ * composes the final map before constructing the factory.
+ *
+ * <p>Natively supplies the Netty {@code SslContext} (on the configured engine — JDK or OpenSSL) and the
+ * JDK {@code SSLContext}; returns {@code empty()} for every other class (notably Jetty's
+ * {@code SslContextFactory.Server} and {@code SslContextFactory.Client}), which the framework synthesizes
+ * from the JDK {@code SSLContext}. It also
+ * returns {@code empty()} for the {@code javax.net.ssl.SSLParameters} companion (PIP-478): its engine policy
+ * (protocols, ciphers, client-auth mode, hostname verification) is baked natively into the Netty contexts it
+ * builds, so it exposes no separate baseline for the framework to overlay on those.
+ *
+ * <p>A JDK {@code SSLContext} cannot itself carry that policy — enabled protocols and cipher suites,
+ * algorithm constraints and the endpoint-identification algorithm are all per-engine {@code SSLParameters}
+ * settings — so the JDK context this factory returns is a <em>material carrier</em>: it holds the key and
+ * trust managers (built through the pinned providers) and nothing else. Every consumer of it applies the
+ * engine policy itself from the same {@link TlsPolicy}, which is what {@code JettyTlsFactory} does. A
+ * consumer that instead created engines straight from this {@code SSLContext} would get the provider defaults,
+ * so consumers must not do that.
+ *
+ * <p><b>Purpose resolution.</b> A request resolves the requested purpose directly against the configured
+ * {@code TlsPurpose -> TlsPolicy} map. When nothing is configured for the purpose, a {@code CLIENT}-role
+ * purpose resolves to the system default (OS trust store, no client certificate) and a {@code SERVER}-role
+ * purpose fails the request. A resolved-but-unbuildable request completes the future <em>exceptionally</em>
+ * — never {@code empty()}, which strictly means "unsupported {@code (purpose, class)} combination".
+ *
+ * <p><b>Rotation.</b> One {@link TlsMaterialSource} is shared per configured purpose. Server-side
+ * subscribers are pushed rebuilt instances by a background poll (interval from the settings, on the
+ * framework scheduler); client-side one-shot callers re-stat on each request and pick up rotation
+ * naturally. Because a re-stat consumes the source's change signal, an acquisition that observes a change
+ * first also fans it out to that purpose's subscribers, so a rotation is never swallowed by whoever happened
+ * to look first. A failed rebuild keeps the last-good instance, logs at WARN, and retries on the next
+ * change; a subscriber callback that throws is caught and logged, and the subscription stays live.
+ */
+@CustomLog
+public class FileBasedTlsFactory implements PulsarTlsFactory {
+
+ private final Map<TlsPurpose, RegisteredSource> registry;
+ private final FileBasedTlsFactorySettings settings;
+
+ private volatile TlsFactoryInitContext initContext;
+ private volatile TlsReloadMetrics metrics;
+ private volatile RegisteredSource systemDefaultSource;
+ private volatile ScheduledFuture<?> pollFuture;
+ private volatile boolean closed;
+
+ /**
+ * Construct an immutable file-based factory.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ this(policies, settings, Map.of());
+ }
+
+ /**
+ * Construct an immutable file-based factory that additionally folds an authentication plugin's TLS
+ * material over the configured file policy for the named purposes (the server-side {@code BROKER_CLIENT}
+ * fold — PIP-478). For a purpose present in {@code authMaterialSuppliers}, the supplier's
+ * {@code Authentication} material overrides the file policy's key/cert per
+ * {@link AuthProvidedMaterialSource} (auth-cert-wins); other purposes use the file policy unchanged.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ Objects.requireNonNull(policies, "policies must not be null");
+ this.settings = Objects.requireNonNull(settings, "settings must not be null");
+ Objects.requireNonNull(authMaterialSuppliers, "authMaterialSuppliers must not be null");
+ Map<TlsPurpose, RegisteredSource> built = new LinkedHashMap<>();
+ for (Map.Entry<TlsPurpose, TlsPolicy> entry : policies.entrySet()) {
+ TlsPurpose purpose = Objects.requireNonNull(entry.getKey(), "purpose key must not be null");
+ TlsPolicy policy = Objects.requireNonNull(entry.getValue(), "policy must not be null");
+ TlsMaterialSource fileSource = new TlsMaterialSource(policy);
+ Supplier<AuthenticationDataProvider> authSupplier = authMaterialSuppliers.get(purpose);
+ MaterialSource source = authSupplier == null
+ ? fileSource
+ : new AuthProvidedMaterialSource(fileSource, authSupplier);
+ built.put(purpose, new RegisteredSource(purpose, policy, source));
+ }
+ this.registry = Map.copyOf(built);
+ }
+
+ /**
+ * Adapt a component's broker-client {@link Authentication} to a per-refresh
+ * {@link AuthenticationDataProvider} supplier for use with the {@code BROKER_CLIENT} fold constructor.
+ * The supplier re-reads {@code getAuthData()} on each poll so credential rotation is observed; a checked
+ * {@link PulsarClientException} is rethrown unchecked and handled by the factory's keep-last-good poll.
+ *
+ * @param authentication the broker-client authentication plugin (never {@code null})
+ * @return a supplier of the plugin's current authentication data
+ */
+ public static Supplier<AuthenticationDataProvider> authMaterialSupplier(Authentication authentication) {
+ Objects.requireNonNull(authentication, "authentication must not be null");
+ return () -> {
+ try {
+ return resolveAuthData(authentication);
+ } catch (PulsarClientException e) {
+ throw new RuntimeException("Failed to obtain broker-client authentication TLS material", e);
+ }
+ };
+ }
+
+ // The BROKER_CLIENT TLS fold is host-agnostic — TLS key material does not vary by peer — so the
+ // host-less getAuthData() is exactly what we want; isolate its deprecation here.
+ @SuppressWarnings("deprecation")
+ private static AuthenticationDataProvider resolveAuthData(Authentication authentication)
+ throws PulsarClientException {
+ return authentication.getAuthData();
+ }
+
+ @Override
+ public CompletableFuture<Void> initialize(TlsFactoryInitContext context) {
+ try {
+ Objects.requireNonNull(context, "context must not be null");
+ // Required, not optional: every acquisition path in this factory reads files and parses key
+ // material. Without an executor the work would run inline on the caller's thread, which the SPI
+ // contract says may be a consumer event loop. Fail at wiring time rather than stalling a channel.
+ Objects.requireNonNull(context.blockingExecutor(),
+ "TlsFactoryInitContext.blockingExecutor() must not be null: FileBasedTlsFactory performs "
+ + "blocking file and key-material loading and must never run it on a consumer thread");
+ this.initContext = context;
+ // Cancel any poll scheduled by a prior initialize() so a second call does not orphan the first:
+ // the field is overwritten below and the old task would otherwise run forever.
+ ScheduledFuture<?> previousPoll = this.pollFuture;
+ if (previousPoll != null) {
+ previousPoll.cancel(false);
+ }
+ // Same reasoning for the metrics: a prior initialize() registered an observable gauge that stays
+ // registered on the meter until close(), so overwriting the field without closing it would leave
+ // an orphaned callback reporting stale per-purpose timestamps forever.
+ TlsReloadMetrics previousMetrics = this.metrics;
+ if (previousMetrics != null) {
+ previousMetrics.close();
+ }
+ this.metrics = TlsReloadMetrics.create(context.openTelemetry(), context.clock());
+ int interval = settings.refreshIntervalSeconds();
+ if (interval > 0 && context.scheduler() != null) {
+ this.pollFuture = context.scheduler().scheduleWithFixedDelay(
+ this::pollSafely, interval, interval, TimeUnit.SECONDS);
+ }
+ log.debug().attr("purposes", registry.keySet()).attr("refreshIntervalSeconds", interval)
+ .log("Initialized FileBasedTlsFactory");
+ return CompletableFuture.completedFuture(null);
+ } catch (Throwable t) {
+ return CompletableFuture.failedFuture(t);
+ }
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(TlsPurpose purpose, Class<T> instanceClass) {
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, TlsEndpoint endpoint, Class<T> instanceClass) {
+ // The default file-based factory serves purpose-scoped material and ignores the endpoint hint.
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, Class<T> instanceClass, Consumer<T> onLoadOrReload) {
+ if (onLoadOrReload == null) {
+ // SPI contract: argument-validation failures complete the returned future exceptionally — this
+ // method never throws on the calling thread.
+ return CompletableFuture.failedFuture(new NullPointerException("onLoadOrReload must not be null"));
+ }
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ synchronized (source) {
+ // FIX F: close() runs releaseAll() under this same source lock, and may have completed after
+ // the outer closed-check but before this task acquired the lock. Re-check here so we never
+ // build+cache+deliver a context (and register a subscription) whose factory-owned reference
+ // would then never be released — that would leak past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ Subscription<T> subscription = new Subscription<>(instanceClass, onLoadOrReload);
+ // Initial delivery happens-before the returned future completes (same thread, ordered).
+ subscription.deliver(instance);
+ source.subscriptions.add(subscription);
+ return Optional.of((TlsHandle<T>) new SubscriptionHandle<>(source, subscription));
+ }
+ });
+ }
+
+ private <T> CompletableFuture<Optional<TlsHandle<T>>> createOneShot(TlsPurpose purpose, Class<T> instanceClass) {
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ synchronized (source) {
+ // FIX F: re-check under the source lock (see createInstance above) so a task racing a
+ // concurrent close()/releaseAll() never builds+retains a context that then leaks past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ retain(instance);
+ return Optional.of((TlsHandle<T>) new OneShotHandle<>(instance));
+ }
+ });
+ }
+
+ /**
+ * Load (or reuse the cached) instance of {@code instanceClass} for the resolved source, recording a
+ * {@code pulsar.tls.reload} attempt for the source's purpose. A resolution failure upstream (an
+ * unconfigured server purpose) is a startup configuration error and is not counted here — only actual
+ * material loads are. Must be called while holding the source monitor.
+ *
+ * <p>Success is counted only for a <em>real</em> (re)load, mirroring the poll path: the first build of a
+ * context class for this source, or a refresh that found changed material. A repeat one-shot acquisition
+ * that re-serves the memoized context (every new connection, on the acquire-per-connection paths) is not a
+ * reload — counting it would inflate {@code pulsar.tls.reload} and keep advancing
+ * {@code pulsar.tls.last_reload_success}, masking exactly the stalled rotation the Monitoring section
+ * alerts on. Failures stay unconditional: an attempt that threw is always worth counting.
+ */
+ private <T> T loadInitialInstance(RegisteredSource source, Class<T> instanceClass) throws Exception {
+ // Hoisted out of the try so the catch can tell whether this call already CONSUMED a rotation before
+ // failing (see the comment on the catch below). Null means currentMaterial() itself threw, which
+ // commits no baseline and so consumes nothing.
+ MaterialSource.RefreshOutcome outcome = null;
+ try {
+ outcome = source.currentMaterial();
+ // Sampled before acquireInstance, which is what populates the memo (both calls run under the
+ // source monitor held by the caller, so no other acquisition can interleave).
+ boolean firstBuild = source.cachedInstance(instanceClass) == null;
+ T instance = source.acquireInstance(instanceClass, outcome.material(), settings);
+ // Rotation fan-out: currentMaterial() CONSUMES the source's change signal (refresh() commits the new
+ // mtime baseline), so whoever refreshes first is the only caller that ever sees changed=true. Without
+ // this, a one-shot acquisition (or an initial subscribing acquisition) that observes a rotation first
+ // leaves every later poll reporting changed=false and the subscribers on this same purpose wedged on
+ // the pre-rotation instance forever — e.g. an https:// client whose FrameworkHttpClientFactory
+ // subscribes to CLIENT_DEFAULT while another path acquires one-shot on it. Deliver the observed
+ // change here, exactly as the poll would have; a delivery failure arms pendingRedeliver so the next
+ // poll retries. No extra metric is recorded — this shares the single recordLoad below.
+ // Also drive the retry when a previous rotation's fan-out failed: the poll is the usual driver,
+ // but it is disabled entirely when refreshIntervalSeconds <= 0, and even when enabled an
+ // acquisition may get here first. Without this, a subscriber wedged by a failed rebuild would
+ // stay on the pre-rotation instance until the files changed again.
+ boolean retryPending = source.pendingRedeliver();
+ boolean delivered = true;
+ if (outcome.changed() || retryPending) {
+ delivered = source.deliverToSubscribers(outcome.material(), settings);
+ }
+ if (outcome.changed() || retryPending || firstBuild) {
+ recordLoad(source.purpose, delivered);
+ }
+ return instance;
+ } catch (Exception e) {
+ recordLoad(source.purpose, false);
+ // The material parsed (the baseline is committed) but building or delivering the context failed.
+ // currentMaterial() has therefore already CONSUMED this rotation's change signal, so every later
+ // poll would report changed=false and — without arming the redeliver flag here — return early,
+ // leaving the subscribers wedged on the pre-rotation instance until the files change again.
+ // deliverToSubscribers arms the flag itself on a partial delivery failure; this covers the case
+ // where the failure happened before it was ever reached.
+ if (outcome != null && outcome.changed()) {
+ source.armRedeliver();
+ }
+ // Keep-last-good (PIP-478): a one-shot (or initial subscribing) acquisition during a
+ // non-atomic rotation window — e.g. the cert file briefly unreadable while it is being replaced —
+ // must not fail when a prior load already built a context of this class. Serve that last-good
+ // instance and WARN; the reload-failure metric was recorded above. Fail only when there is no
+ // last-good to fall back on (a genuine startup misconfiguration, per the fail-fast contract).
+ T cached = source.cachedInstance(instanceClass);
+ if (cached != null) {
+ log.warn().attr("purpose", source.purpose).exception(e)
+ .log("Failed to load TLS material; serving the last-good instance");
+ return cached;
+ }
+ throw e;
+ }
+ }
+
+ private void recordLoad(TlsPurpose purpose, boolean success) {
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.recordLoad(purpose, success);
+ }
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ ScheduledFuture<?> poll = this.pollFuture;
+ if (poll != null) {
+ poll.cancel(false);
+ }
+ for (RegisteredSource source : registry.values()) {
+ source.releaseAll();
+ }
+ RegisteredSource systemDefault = this.systemDefaultSource;
+ if (systemDefault != null) {
+ systemDefault.releaseAll();
+ }
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.close();
+ }
+ }
+
+ /**
+ * Resolve a requested purpose to the {@link RegisteredSource} that owns its material, applying the
+ * role's terminal-resolution rule when nothing is configured for the purpose.
+ *
+ * @throws TlsMaterialUnavailableException when a server-role purpose has no material configured
+ */
+ private RegisteredSource resolve(TlsPurpose purpose) {
+ Objects.requireNonNull(purpose, "purpose must not be null");
+ RegisteredSource source = registry.get(purpose);
+ if (source != null) {
+ return source;
+ }
+ if (purpose.role() == TlsPurpose.Role.CLIENT) {
+ return systemDefaultSource();
+ }
+ throw new TlsMaterialUnavailableException(
+ "No TLS material configured for server purpose " + purpose);
+ }
+
+ private RegisteredSource systemDefaultSource() {
+ RegisteredSource existing = this.systemDefaultSource;
+ if (existing != null) {
+ return existing;
+ }
+ synchronized (this) {
+ if (this.systemDefaultSource == null) {
+ // System default: verify hostnames, OS trust store, no client certificate. A constant
+ // source (no files, never rotates).
+ TlsPolicy defaultPolicy = TlsPolicy.builder().build();
+ this.systemDefaultSource = new RegisteredSource(
+ TlsPurpose.CLIENT_DEFAULT, defaultPolicy, null);
+ }
+ return this.systemDefaultSource;
+ }
+ }
+
+ private void pollSafely() {
+ if (closed) {
+ return;
+ }
+ try {
+ for (RegisteredSource source : registry.values()) {
+ source.poll(settings, metrics);
+ }
+ } catch (Throwable t) {
+ log.warn().exception(t).log("Unexpected error during TLS material poll");
+ }
+ }
+
+ private <R> CompletableFuture<R> runAsync(Callable<R> task) {
+ CompletableFuture<R> future = new CompletableFuture<>();
+ TlsFactoryInitContext context = this.initContext;
+ // initialize() rejects a null blockingExecutor, so the caller-thread fallback is reachable only before
+ // initialize() has run — a direct-construction path (tests, or a component acquiring during its own
+ // startup) that is by definition not on a consumer event loop.
+ Executor executor = context != null ? context.blockingExecutor() : Runnable::run;
+ try {
+ executor.execute(() -> {
+ try {
+ R result = task.call();
+ if (!future.complete(result)) {
+ // The caller cancelled (or otherwise completed) the future while the acquisition was
+ // still running, so nothing will ever receive this handle. The task has already
+ // retained the context on its behalf, and with the finalizer-free OPENSSL_REFCNT
+ // engine an unbalanced retain is a permanent native leak — dispose the orphan here.
+ disposeOrphan(result);
+ }
+ } catch (Throwable t) {
+ future.completeExceptionally(t);
+ }
+ });
+ } catch (Throwable t) {
+ future.completeExceptionally(t);
+ }
+ return future;
+ }
+
+ /**
+ * Release a handle that was built but could not be delivered to its caller. Both acquisition forms
+ * produce an {@code Optional<TlsHandle<?>>}, and disposing it is exactly what the caller would have done:
+ * it drops the one-shot's retained reference, or unregisters the subscription and releases its borrows.
+ */
+ private static void disposeOrphan(Object result) {
+ if (result instanceof Optional<?> optional && optional.orElse(null) instanceof TlsHandle<?> handle) {
+ try {
+ handle.dispose();
+ } catch (Throwable t) {
+ log.warn().exception(t).log("Failed to dispose an undelivered TLS handle");
+ }
+ }
+ }
+
+ private static boolean isSupported(Class<?> instanceClass) {
+ return instanceClass == SslContext.class || instanceClass == SSLContext.class;
+ }
+
+ private static void retain(Object instance) {
+ if (instance != null) {
+ ReferenceCountUtil.retain(instance);
+ }
+ }
+
+ private static void release(Object instance) {
+ if (instance != null) {
+ ReferenceCountUtil.release(instance);
+ }
+ }
+
+ /**
+ * A configured purpose's material source together with the cached, factory-owned context instances
+ * and the active subscriptions. All state is guarded by the instance monitor.
+ */
+ private static final class RegisteredSource {
+ private final TlsPurpose purpose;
+ private final TlsPolicy policy;
+ // Null for the system-default source, whose constant material never rotates.
+ private final MaterialSource source;
+ private final CopyOnWriteArrayList<Subscription<?>> subscriptions = new CopyOnWriteArrayList<>();
+
+ private SslContext nettyContext;
+ private TlsMaterial nettyMaterial;
+ private SSLContext jdkContext;
+ private TlsMaterial jdkMaterial;
+ // Set when a rotation's rebuild/delivery to some subscriber failed, so the next poll re-attempts the
+ // rebuild even if the source now reports changed=false (PIP-478 L1 reload-wedge guard).
+ private boolean pendingRedeliver;
+
+ RegisteredSource(TlsPurpose purpose, TlsPolicy policy, MaterialSource source) {
+ this.purpose = purpose;
+ this.policy = policy;
+ this.source = source;
+ }
+
+ /**
+ * Refresh the material, reporting whether it changed in value. The system-default source has no
+ * backing files, so it never changes — its single context build is counted via the first-build check
+ * in {@link FileBasedTlsFactory#loadInitialInstance}.
+ */
+ synchronized MaterialSource.RefreshOutcome currentMaterial() throws Exception {
+ if (source == null) {
+ return new MaterialSource.RefreshOutcome(TlsMaterial.SYSTEM_DEFAULT, false);
+ }
+ return source.refresh();
+ }
+
+ /**
+ * Return the cached context of the requested class, rebuilding it (and releasing the superseded
+ * one) only when the material changed in value. The returned instance is the factory-owned memo;
+ * callers that hand it to a consumer {@link FileBasedTlsFactory#retain(Object) retain} it.
+ */
+ synchronized <T> T acquireInstance(Class<T> instanceClass, TlsMaterial material,
+ FileBasedTlsFactorySettings settings) throws Exception {
+ if (instanceClass == SslContext.class) {
+ if (nettyContext == null || !material.equals(nettyMaterial)) {
+ SslContext built = purpose.role() == TlsPurpose.Role.SERVER
+ ? TlsContexts.buildNettyServerContext(material, policy, settings.engineProvider(),
+ settings.requireTrustedClientCert())
+ : TlsContexts.buildNettyClientContext(material, policy, settings.engineProvider());
+ release(nettyContext);
+ nettyContext = built;
+ nettyMaterial = material;
+ }
+ return instanceClass.cast(nettyContext);
+ }
+ if (instanceClass == SSLContext.class) {
+ if (jdkContext == null || !material.equals(jdkMaterial)) {
+ jdkContext = TlsContexts.buildJdkContext(material, policy);
+ jdkMaterial = material;
+ }
+ return instanceClass.cast(jdkContext);
+ }
+ throw new IllegalArgumentException("Unsupported instance class " + instanceClass);
+ }
+
+ /**
+ * The last-good cached context of the requested class, or {@code null} if none has been built yet.
+ * Used by the keep-last-good one-shot path when a fresh load fails mid-rotation.
+ */
+ synchronized <T> T cachedInstance(Class<T> instanceClass) {
+ if (instanceClass == SslContext.class && nettyContext != null) {
+ return instanceClass.cast(nettyContext);
+ }
+ if (instanceClass == SSLContext.class && jdkContext != null) {
+ return instanceClass.cast(jdkContext);
+ }
+ return null;
+ }
+
+ synchronized void poll(FileBasedTlsFactorySettings settings, TlsReloadMetrics metrics) {
+ if (source == null || subscriptions.isEmpty()) {
+ return;
+ }
+ MaterialSource.RefreshOutcome outcome;
+ try {
+ outcome = source.refresh();
+ } catch (Exception e) {
+ // Keep-last-good: leave every subscription on its current instance and retry next change.
+ recordLoad(metrics, false);
+ log.warn().attr("purpose", purpose).exception(e)
+ .log("Failed to reload TLS material; keeping the last-good instance");
+ return;
+ }
+ // A poll that finds no change is not a reload — do not count it, so the reload counter and the
+ // last-success gauge reflect real (re)load events only. But if a prior rotation's rebuild/delivery
+ // to some subscriber failed (pendingRedeliver), retry it even when the source now reports
+ // changed=false: otherwise, once the source commits the new baseline, every later poll sees
+ // changed=false and that subscriber stays wedged on the old instance until the next file change
+ // (L1). The retry rebuilds against the current last-good material.
+ if (!outcome.changed() && !pendingRedeliver) {
+ return;
+ }
+ recordLoad(metrics, deliverToSubscribers(outcome.material(), settings));
+ }
+
+ /**
+ * Rebuild and hand {@code material} to every live subscription, reporting whether all succeeded. Called
+ * both by the background poll and by an acquisition that consumed the source's change signal first
+ * (see {@link FileBasedTlsFactory#loadInitialInstance}), so a rotation reaches the subscribers no matter
+ * which caller observed it. Records no metric itself — each caller counts the (re)load once.
+ *
+ * <p><b>Consumer callbacks run while this source's monitor is held</b>, which keeps a rotation's
+ * rebuild-and-publish atomic against a concurrent acquisition. The cost is a reentrancy constraint on
+ * consumers: a reload callback must not call {@code createInstance} for the same purpose and block on
+ * the returned future, because that acquisition needs this same monitor and would deadlock when the
+ * blocking executor runs it on another thread. Consumers are expected to do only a volatile store in
+ * the callback (swap the context they hand to new connections) and never to block in it.
+ */
+ synchronized boolean deliverToSubscribers(TlsMaterial material, FileBasedTlsFactorySettings settings) {
+ boolean allRebuilt = true;
+ for (Subscription<?> subscription : subscriptions) {
+ try {
+ Object rebuilt = acquireInstance(subscription.instanceClass, material, settings);
+ subscription.deliverErased(rebuilt);
+ } catch (Exception e) {
+ allRebuilt = false;
+ log.warn().attr("purpose", purpose).attr("class", subscription.instanceClass.getName())
+ .exception(e).log("Failed to rebuild rotated TLS instance; keeping the last-good one");
+ }
+ }
+ // Re-attempt on the next poll until every subscriber has the rotated instance (L1).
+ pendingRedeliver = !allRebuilt;
+ return allRebuilt;
+ }
+
+ private void recordLoad(TlsReloadMetrics metrics, boolean success) {
+ if (metrics != null) {
+ metrics.recordLoad(purpose, success);
+ }
+ }
+
+ /**
+ * Arm the redeliver retry for a rotation whose change signal was consumed but whose fan-out never
+ * ran (the context build failed first). The next poll — or, when polling is disabled, the next
+ * acquisition — then re-attempts the rebuild even though the source now reports {@code changed=false}.
+ */
+ synchronized void armRedeliver() {
+ pendingRedeliver = true;
+ }
+
+ /** @return whether a rotation still owes its subscribers a rebuilt instance. */
+ synchronized boolean pendingRedeliver() {
+ return pendingRedeliver;
+ }
+
+ synchronized void removeSubscription(Subscription<?> subscription) {
+ if (subscriptions.remove(subscription)) {
+ subscription.releaseCurrent();
+ }
+ }
+
+ synchronized void releaseAll() {
+ for (Subscription<?> subscription : subscriptions) {
+ subscription.releaseCurrent();
+ }
+ subscriptions.clear();
+ release(nettyContext);
+ nettyContext = null;
+ nettyMaterial = null;
+ jdkContext = null;
+ jdkMaterial = null;
+ }
+ }
+
+ /** A live server-side subscription: its instance class, callback, and last-delivered instances. */
+ private static final class Subscription<T> {
+ private final Class<T> instanceClass;
+ private final Consumer<T> callback;
+ // Volatile: written under the source monitor (deliver), but read lock-free by SubscriptionHandle.get()
+ // from arbitrary consumer threads — the handle contract promises the most recent delivery, which
+ // needs the happens-before edge (a stale read can outlive the deferred-release window below).
+ private volatile T current;
+ // Deferred release (PIP-478 use-after-free): the instance superseded by the most recent delivery
+ // is kept alive one extra generation rather than released immediately. Consumers hold a bare volatile
+ // borrow of the delivered instance and later call newHandler/newEngine on it off a different thread;
+ // releasing the superseded Netty/OpenSSL context to refcount 0 on the poll thread the instant the new
+ // one is published would free the native SSL_CTX out from under such an in-flight borrow. Retaining it
+ // for one further rotation gives every reader a full poll interval to finish. Pairs with per-use
+ // pinning at the consumers (see TlsContextAcquisition.withPinnedContext) for the descheduling case.
+ private T previous;
+
+ Subscription(Class<T> instanceClass, Consumer<T> callback) {
+ this.instanceClass = instanceClass;
+ this.callback = callback;
+ }
+
+ void deliver(T instance) {
+ retain(instance);
+ // Release the instance delivered two rotations ago (N-1) on this (N+1th) delivery, not the one
+ // just superseded, so the just-superseded instance survives one more generation for readers.
+ release(previous);
+ previous = current;
+ current = instance;
+ safeInvoke(instance);
+ }
+
+ @SuppressWarnings("unchecked")
+ void deliverErased(Object instance) {
+ deliver((T) instance);
+ }
+
+ T current() {
+ return current;
+ }
+
+ void releaseCurrent() {
+ release(current);
+ current = null;
+ release(previous);
+ previous = null;
+ }
+
+ private void safeInvoke(T instance) {
+ try {
+ callback.accept(instance);
+ } catch (Throwable t) {
+ // A throwing consumer callback must not kill the subscription; later deliveries proceed.
+ log.warn().exception(t).log("TLS reload callback threw; subscription stays live");
+ }
+ }
+ }
+
+ /** A one-shot handle: exposes the built instance and releases its retained reference on dispose. */
+ private static final class OneShotHandle<T> implements TlsHandle<T> {
+ private final T instance;
+ // FIX E: an AtomicBoolean, not a volatile flag — a plain check-then-set lets two concurrent
+ // dispose() callers both pass the guard and over-decrement the cached context's refcount.
+ private final AtomicBoolean disposed = new AtomicBoolean(false);
+
+ OneShotHandle(T instance) {
+ this.instance = instance;
+ }
+
+ @Override
+ public T get() {
+ return instance;
+ }
+
+ @Override
+ public void dispose() {
+ if (disposed.compareAndSet(false, true)) {
+ release(instance);
+ }
+ }
+ }
+
+ /** A subscribing handle: exposes the most-recently-delivered instance and unregisters on dispose. */
+ private static final class SubscriptionHandle<T> implements TlsHandle<T> {
+ private final RegisteredSource source;
+ private final Subscription<T> subscription;
+ private volatile boolean disposed;
Review Comment:
Asymmetry with `OneShotHandle`: that one deliberately uses an `AtomicBoolean` with a comment ("FIX E: ... a plain check-then-set lets two concurrent `dispose()` callers both pass the guard and over-decrement"), while this is a plain volatile check-then-set.
It happens to be safe, but only because `removeSubscription` is guarded by `subscriptions.remove(subscription)` returning `true` — the `disposed` flag isn't doing the work. Given the comment two classes up says the opposite pattern is a bug, I'd either make this an `AtomicBoolean` too or note that the real guard is the `remove()` return value, so the next reader doesn't conclude one of the two is wrong.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/util/tls/JcaProviders.java:
##########
@@ -0,0 +1,474 @@
+/*
+ * 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.common.util.tls;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.security.NoSuchAlgorithmException;
+import java.security.Provider;
+import java.security.Security;
+import java.util.Iterator;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.ServiceConfigurationError;
+import java.util.ServiceLoader;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+
+/**
+ * Resolves the JCA/JCE security providers Pulsar relies on: a named provider for the PIP-478
+ * {@code jsseProvider} / {@code jcaProvider} axes, the Bouncy Castle provider (FIPS or non-FIPS), and the
+ * optional Conscrypt (OpenSSL) provider. This is the single provider-resolution primitive extracted from the
+ * {@code SecurityUtility} grab-bag (PIP-478).
+ *
+ * <p><b>Bouncy Castle is resolved lazily and is optional.</b> Loading this class must not require it: the
+ * class exists mainly to resolve <em>named</em> providers for the two TLS provider axes, which every TLS
+ * policy does, whereas Bouncy Castle is needed only by the code that actually asks for it (message
+ * encryption, and a deployment that pins {@code jcaProvider=BC}/{@code BCFIPS}). The provider is therefore
+ * looked up on first use through {@link #bouncyCastleProvider()} — which reports absence as
+ * {@link Optional#empty()} rather than failing — and only a caller that genuinely needs it, via
+ * {@link #requireBouncyCastleProvider()}, turns absence into an error. Resolving it does install it
+ * process-wide via {@code Security.addProvider}, as before.
+ *
+ * <p>Conscrypt, by contrast, is resolved during class initialization ({@link #CONSCRYPT_PROVIDER}) and
+ * installed process-wide when present; it reports absence as {@code null} and never fails class loading.
+ */
+@CustomLog
+public final class JcaProviders {
+
+ public static final String BC_FIPS_PROVIDER_CLASS = "org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider";
+ public static final String BC_NON_FIPS_PROVIDER_CLASS = "org.bouncycastle.jce.provider.BouncyCastleProvider";
+ public static final String BC_JSSE_PROVIDER_CLASS = "org.bouncycastle.jsse.provider.BouncyCastleJsseProvider";
+ public static final String CONSCRYPT_PROVIDER_CLASS = "org.conscrypt.OpenSSLProvider";
+ public static final Provider CONSCRYPT_PROVIDER = loadConscryptProvider();
+
+ // Security.getProvider("BC") / Security.getProvider("BCFIPS").
+ // also used to get Factories. e.g. CertificateFactory.getInstance("X.509", "BCFIPS")
+ public static final String BC_FIPS = "BCFIPS";
+ public static final String BC = "BC";
+
+ /**
+ * The name BouncyCastle's JSSE provider registers under — the same in FIPS and non-FIPS mode, because
+ * the mode is a constructor argument rather than part of the provider identity.
+ */
+ public static final String BC_JSSE = "BCJSSE";
+
+ private JcaProviders() {
+ }
+
+ /**
+ * A resolved Bouncy Castle provider together with which of the two artifacts it came from. The flavour
+ * travels with the provider because callers that care (FIPS-approved-only algorithm choices) would
+ * otherwise have to re-derive it from the provider's class name, and because the answer is fixed once
+ * the provider is resolved.
+ *
+ * @param provider the resolved, process-wide registered provider
+ * @param fips whether it is the FIPS-certified artifact ({@code bc-fips}, registered as
+ * {@code BCFIPS}) rather than the general-purpose one ({@code bcprov}, registered as
+ * {@code BC})
+ */
+ public record ResolvedBouncyCastleProvider(Provider provider, boolean fips) {
+ public ResolvedBouncyCastleProvider {
+ Objects.requireNonNull(provider, "provider must not be null");
+ }
+ }
+
+ /**
+ * Lazily resolves Bouncy Castle on first access, so that merely loading {@link JcaProviders} — which
+ * every named-provider resolution does — never requires Bouncy Castle to be on the classpath.
+ */
+ private static final class BouncyCastleHolder {
+ private static final ResolvedBouncyCastleProvider RESOLVED = loadBouncyCastleProvider();
+ }
+
+ /**
+ * The Bouncy Castle provider, installed process-wide on first resolution:
+ * <ol>
+ * <li>an already-registered {@code BC} or {@code BCFIPS} provider, if any;</li>
+ * <li>otherwise loaded from the classpath (non-FIPS preferred, FIPS as fallback) and registered via
+ * {@code Security.addProvider}.</li>
+ * </ol>
+ *
+ * @return the resolved provider and its flavour, or {@link Optional#empty()} when Bouncy Castle is not
+ * available. Callers that cannot proceed without it should use
+ * {@link #requireBouncyCastleProvider()}, so the failure names them rather than surfacing as a
+ * class-initialization error somewhere unrelated.
+ */
+ public static Optional<ResolvedBouncyCastleProvider> bouncyCastleProvider() {
+ return Optional.ofNullable(BouncyCastleHolder.RESOLVED);
+ }
+
+ /**
+ * As {@link #bouncyCastleProvider()}, for callers whose functionality genuinely requires Bouncy Castle.
+ *
+ * @return the resolved provider and its flavour
+ * @throws IllegalStateException when Bouncy Castle is not on the classpath
+ */
+ public static ResolvedBouncyCastleProvider requireBouncyCastleProvider() {
+ return bouncyCastleProvider().orElseThrow(() -> new IllegalStateException(
+ "No Bouncy Castle provider is available: neither an already-registered " + BC + "/" + BC_FIPS
+ + " provider nor " + BC_NON_FIPS_PROVIDER_CLASS + " / " + BC_FIPS_PROVIDER_CLASS
+ + " on the classpath. Add the bcprov (or bc-fips) dependency to use this feature."));
+ }
+
+ private static ResolvedBouncyCastleProvider loadBouncyCastleProvider() {
+ Provider installed = Security.getProvider(BC);
+ if (installed == null) {
+ installed = Security.getProvider(BC_FIPS);
+ }
+ if (installed != null) {
+ log.debug().attr("provider", installed.getName()).log("Already instantiated Bouncy Castle provider");
+ return toResolvedProvider(installed);
+ }
+ // Not installed, try to load from the classpath. Absence is not an error here — it is only an error
+ // for a caller that needs Bouncy Castle, which requireBouncyCastleProvider() reports.
+ try {
+ return toResolvedProvider(getBCProviderFromClassPath());
+ } catch (Exception e) {
+ log.debug().exception(e)
+ .log("No Bouncy Castle provider (FIPS or non-FIPS) on the classpath");
+ return null;
+ }
+ }
+
+ /**
+ * Lazily resolves BouncyCastle's JSSE provider on first access, registering it from the classpath when
+ * the operator has not installed it themselves.
+ */
+ private static final class BouncyCastleJsseHolder {
+ private static final ResolvedBouncyCastleProvider RESOLVED = loadBouncyCastleJsseProvider();
+ }
+
+ /**
+ * BouncyCastle's JSSE provider ({@value #BC_JSSE}), the provider a FIPS TLS deployment pins as
+ * {@code jsseProvider}.
+ *
+ * <p>Unlike every other provider this class resolves, {@value #BC_JSSE} cannot be discovered: {@code bctls}
+ * ships no {@code META-INF/services/java.security.Provider} entry, so an unregistered one is invisible to
+ * {@link ServiceLoader}. And it cannot simply be default-constructed either, because its FIPS mode is a
+ * constructor argument fixed at construction — the provider registers under the same name either way, so
+ * a no-arg instance would quietly be the non-FIPS one. This resolves it explicitly instead:
+ *
+ * <ol>
+ * <li>an instance the operator already registered wins, whatever mode they built it in;</li>
+ * <li>otherwise, when {@code bctls} is on the classpath, it is constructed and registered here — in
+ * FIPS mode bound to the FIPS JCA provider when {@link #bouncyCastleProvider()} resolved that one,
+ * and in the default mode otherwise, so the TLS stack follows whichever BouncyCastle artifact the
+ * deployment actually ships;</li>
+ * <li>otherwise it is absent, and pinning {@code jsseProvider=BCJSSE} fails loudly.</li>
+ * </ol>
+ *
+ * @return the resolved provider and whether it is in FIPS mode, or {@link Optional#empty()} when
+ * {@code bctls} is not on the classpath
+ */
+ public static Optional<ResolvedBouncyCastleProvider> bouncyCastleJsseProvider() {
+ return Optional.ofNullable(BouncyCastleJsseHolder.RESOLVED);
+ }
+
+ private static ResolvedBouncyCastleProvider loadBouncyCastleJsseProvider() {
+ Provider registered = Security.getProvider(BC_JSSE);
+ if (registered != null) {
+ log.debug().attr("provider", BC_JSSE).log("Already instantiated BouncyCastle JSSE provider");
+ return new ResolvedBouncyCastleProvider(registered, isJsseFipsMode(registered));
+ }
+ Class<?> providerClass;
+ try {
+ providerClass = Class.forName(BC_JSSE_PROVIDER_CLASS);
+ } catch (ClassNotFoundException e) {
+ log.debug().attr("class", BC_JSSE_PROVIDER_CLASS)
+ .log("No BouncyCastle JSSE provider on the classpath");
+ return null;
+ }
+ // Resolving the JCA provider first also installs it, which the FIPS configuration below needs: the
+ // JSSE provider looks its crypto provider up by name while constructing.
+ String config = jsseProviderConfig(bouncyCastleProvider().orElse(null));
+ try {
+ Provider provider = config == null
+ ? (Provider) providerClass.getDeclaredConstructor().newInstance()
+ : (Provider) providerClass.getDeclaredConstructor(String.class).newInstance(config);
+ Security.addProvider(provider);
+ boolean fips = isJsseFipsMode(provider);
+ log.info().attr("provider", provider.getName()).attr("fips", fips)
+ .log("Registered the BouncyCastle JSSE provider");
+ return new ResolvedBouncyCastleProvider(provider, fips);
+ } catch (ReflectiveOperationException | RuntimeException e) {
+ log.warn().attr("class", BC_JSSE_PROVIDER_CLASS).attr("config", config).exception(e)
+ .log("Failed to register the BouncyCastle JSSE provider");
+ return null;
+ }
+ }
+
+ /**
+ * The constructor argument for a self-registered {@value #BC_JSSE}: {@code "fips:<name>"} binds it to a
+ * FIPS JCA provider and turns FIPS mode on, while {@code null} selects the no-arg (default, non-FIPS)
+ * constructor. FIPS mode is chosen only when the resolved BouncyCastle JCA provider is itself the FIPS
+ * artifact — pairing a FIPS JSSE provider with a non-validated crypto provider would be FIPS-shaped
+ * rather than FIPS-compliant, which is exactly what the two provider axes exist to prevent.
+ *
+ * @param jcaProvider the resolved BouncyCastle JCA provider, or {@code null} when there is none
+ * @return the constructor argument, or {@code null} to use the no-arg constructor
+ */
+ @VisibleForTesting
+ static String jsseProviderConfig(ResolvedBouncyCastleProvider jcaProvider) {
+ if (jcaProvider == null || !jcaProvider.fips()) {
+ return null;
+ }
+ return "fips:" + jcaProvider.provider().getName();
+ }
+
+ /** Query a JSSE provider's FIPS mode reflectively, so this class never needs {@code bctls} to compile. */
+ private static boolean isJsseFipsMode(Provider provider) {
+ try {
+ return Boolean.TRUE.equals(provider.getClass().getMethod("isFipsMode").invoke(provider));
+ } catch (ReflectiveOperationException | RuntimeException e) {
+ log.debug().attr("provider", provider.getName()).exception(e)
+ .log("Provider exposes no isFipsMode(); assuming non-FIPS");
+ return false;
+ }
+ }
+
+ /**
+ * Classify a resolved provider. Both the registered name and the implementation class are checked: the
+ * FIPS artifact registers as {@code BCFIPS}, and matching the class as well keeps the classification
+ * right for a provider registered under a non-standard name.
+ */
+ private static ResolvedBouncyCastleProvider toResolvedProvider(Provider provider) {
+ boolean fips = BC_FIPS.equals(provider.getName())
+ || BC_FIPS_PROVIDER_CLASS.equals(provider.getClass().getCanonicalName());
+ return new ResolvedBouncyCastleProvider(provider, fips);
+ }
+
+ private static Provider loadConscryptProvider() {
+ Class<?> conscryptClazz;
+
+ try {
+ conscryptClazz = Class.forName("org.conscrypt.Conscrypt");
+ conscryptClazz.getMethod("checkAvailability").invoke(null);
+ } catch (Throwable e) {
+ if (e instanceof ClassNotFoundException) {
+ log.debug("Conscrypt isn't available in the classpath. Using JDK default security provider.");
+ } else if (e.getCause() instanceof UnsatisfiedLinkError) {
+ log.debug().attr("os", System.getProperty("os.name")).attr("arch", System.getProperty("os.arch"))
+ .log("Conscrypt isn't available. Using JDK default security provider");
+ } else {
+ log.debug().attr("cause", e.getCause()).attr("reason", e.getMessage())
+ .log("Conscrypt isn't available. Using JDK default security provider");
+ }
+ return null;
+ }
+
+ Provider provider;
+ try {
+ provider = (Provider) Class.forName(CONSCRYPT_PROVIDER_CLASS).getDeclaredConstructor().newInstance();
+ } catch (ReflectiveOperationException e) {
+ log.debug().attr("class", CONSCRYPT_PROVIDER_CLASS).exception(e)
+ .log("Unable to get security provider");
+ return null;
+ }
+
+ // Unlike the PIP-337 loader this one installs NO custom hostname verifier, so Conscrypt keeps its
+ // built-in default: standard RFC 2818 (SAN-based) verification, matching PIP-478's removal of the
+ // deprecated CN-based matching. The bug-1015 workaround in processConscryptTrustManager propagates
+ // whatever Conscrypt's DEFAULT verifier is onto each TrustManager.
+ //
+ // CAVEAT while both TLS stacks coexist: Conscrypt.setDefaultHostnameVerifier is process-global, and
+ // SecurityUtility's static initializer (still the wired PIP-337 path) sets it to the CN-tolerant
+ // TlsHostnameVerifier. Whenever that class has been loaded, the "default" propagated above is that
+ // relaxed verifier, not Conscrypt's own. Nothing routes through this class yet so no deployment is
+ // affected today; the PR that turns SAN-only hostname verification on by default must neutralize that
+ // global (or land together with SecurityUtility's removal) for the SAN-only guarantee to hold on a
Review Comment:
This caveat deserves a tracking issue rather than only a code comment. Restated: `Conscrypt.setDefaultHostnameVerifier` is process-global, `SecurityUtility`'s static initializer (still the wired path) sets it to the CN-tolerant `TlsHostnameVerifier`, so whenever that class has been loaded the "default" propagated here is the relaxed verifier — and the SAN-only guarantee this class is written to provide silently doesn't hold on a Conscrypt-pinned deployment.
The comment correctly notes nothing routes here yet. But it's a cross-PR constraint on a PR that isn't written yet, expressed only as a comment in a file that PR may not touch. An issue linked from PIP-478 would be more durable.
##########
pulsar-common/src/main/java/org/apache/pulsar/common/tls/impl/FileBasedTlsFactory.java:
##########
@@ -0,0 +1,768 @@
+/*
+ * 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.common.tls.impl;
+
+import io.netty.handler.ssl.SslContext;
+import io.netty.util.ReferenceCountUtil;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+import javax.net.ssl.SSLContext;
+import lombok.CustomLog;
+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.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsEndpoint;
+import org.apache.pulsar.tls.TlsFactoryInitContext;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPolicy;
+import org.apache.pulsar.tls.TlsPurpose;
+
+/**
+ * The default, file-based {@link PulsarTlsFactory} (PIP-478).
+ *
+ * <p>Immutable after construction: the complete {@code TlsPurpose -> TlsPolicy} map and the
+ * factory-wide {@link FileBasedTlsFactorySettings} are fixed by the constructor and never mutated. The
+ * owning component (the v5 client builder, or {@code DefaultBrokerTlsFactory} on the server side)
+ * composes the final map before constructing the factory.
+ *
+ * <p>Natively supplies the Netty {@code SslContext} (on the configured engine — JDK or OpenSSL) and the
+ * JDK {@code SSLContext}; returns {@code empty()} for every other class (notably Jetty's
+ * {@code SslContextFactory.Server} and {@code SslContextFactory.Client}), which the framework synthesizes
+ * from the JDK {@code SSLContext}. It also
+ * returns {@code empty()} for the {@code javax.net.ssl.SSLParameters} companion (PIP-478): its engine policy
+ * (protocols, ciphers, client-auth mode, hostname verification) is baked natively into the Netty contexts it
+ * builds, so it exposes no separate baseline for the framework to overlay on those.
+ *
+ * <p>A JDK {@code SSLContext} cannot itself carry that policy — enabled protocols and cipher suites,
+ * algorithm constraints and the endpoint-identification algorithm are all per-engine {@code SSLParameters}
+ * settings — so the JDK context this factory returns is a <em>material carrier</em>: it holds the key and
+ * trust managers (built through the pinned providers) and nothing else. Every consumer of it applies the
+ * engine policy itself from the same {@link TlsPolicy}, which is what {@code JettyTlsFactory} does. A
+ * consumer that instead created engines straight from this {@code SSLContext} would get the provider defaults,
+ * so consumers must not do that.
+ *
+ * <p><b>Purpose resolution.</b> A request resolves the requested purpose directly against the configured
+ * {@code TlsPurpose -> TlsPolicy} map. When nothing is configured for the purpose, a {@code CLIENT}-role
+ * purpose resolves to the system default (OS trust store, no client certificate) and a {@code SERVER}-role
+ * purpose fails the request. A resolved-but-unbuildable request completes the future <em>exceptionally</em>
+ * — never {@code empty()}, which strictly means "unsupported {@code (purpose, class)} combination".
+ *
+ * <p><b>Rotation.</b> One {@link TlsMaterialSource} is shared per configured purpose. Server-side
+ * subscribers are pushed rebuilt instances by a background poll (interval from the settings, on the
+ * framework scheduler); client-side one-shot callers re-stat on each request and pick up rotation
+ * naturally. Because a re-stat consumes the source's change signal, an acquisition that observes a change
+ * first also fans it out to that purpose's subscribers, so a rotation is never swallowed by whoever happened
+ * to look first. A failed rebuild keeps the last-good instance, logs at WARN, and retries on the next
+ * change; a subscriber callback that throws is caught and logged, and the subscription stays live.
+ */
+@CustomLog
+public class FileBasedTlsFactory implements PulsarTlsFactory {
+
+ private final Map<TlsPurpose, RegisteredSource> registry;
+ private final FileBasedTlsFactorySettings settings;
+
+ private volatile TlsFactoryInitContext initContext;
+ private volatile TlsReloadMetrics metrics;
+ private volatile RegisteredSource systemDefaultSource;
+ private volatile ScheduledFuture<?> pollFuture;
+ private volatile boolean closed;
+
+ /**
+ * Construct an immutable file-based factory.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings) {
+ this(policies, settings, Map.of());
+ }
+
+ /**
+ * Construct an immutable file-based factory that additionally folds an authentication plugin's TLS
+ * material over the configured file policy for the named purposes (the server-side {@code BROKER_CLIENT}
+ * fold — PIP-478). For a purpose present in {@code authMaterialSuppliers}, the supplier's
+ * {@code Authentication} material overrides the file policy's key/cert per
+ * {@link AuthProvidedMaterialSource} (auth-cert-wins); other purposes use the file policy unchanged.
+ *
+ * @param policies the complete purpose→policy map (defensively copied)
+ * @param settings the factory-wide engine/refresh settings
+ * @param authMaterialSuppliers per-purpose broker-client authentication material suppliers (may be empty)
+ */
+ public FileBasedTlsFactory(Map<TlsPurpose, TlsPolicy> policies, FileBasedTlsFactorySettings settings,
+ Map<TlsPurpose, Supplier<AuthenticationDataProvider>> authMaterialSuppliers) {
+ Objects.requireNonNull(policies, "policies must not be null");
+ this.settings = Objects.requireNonNull(settings, "settings must not be null");
+ Objects.requireNonNull(authMaterialSuppliers, "authMaterialSuppliers must not be null");
+ Map<TlsPurpose, RegisteredSource> built = new LinkedHashMap<>();
+ for (Map.Entry<TlsPurpose, TlsPolicy> entry : policies.entrySet()) {
+ TlsPurpose purpose = Objects.requireNonNull(entry.getKey(), "purpose key must not be null");
+ TlsPolicy policy = Objects.requireNonNull(entry.getValue(), "policy must not be null");
+ TlsMaterialSource fileSource = new TlsMaterialSource(policy);
+ Supplier<AuthenticationDataProvider> authSupplier = authMaterialSuppliers.get(purpose);
+ MaterialSource source = authSupplier == null
+ ? fileSource
+ : new AuthProvidedMaterialSource(fileSource, authSupplier);
+ built.put(purpose, new RegisteredSource(purpose, policy, source));
+ }
+ this.registry = Map.copyOf(built);
+ }
+
+ /**
+ * Adapt a component's broker-client {@link Authentication} to a per-refresh
+ * {@link AuthenticationDataProvider} supplier for use with the {@code BROKER_CLIENT} fold constructor.
+ * The supplier re-reads {@code getAuthData()} on each poll so credential rotation is observed; a checked
+ * {@link PulsarClientException} is rethrown unchecked and handled by the factory's keep-last-good poll.
+ *
+ * @param authentication the broker-client authentication plugin (never {@code null})
+ * @return a supplier of the plugin's current authentication data
+ */
+ public static Supplier<AuthenticationDataProvider> authMaterialSupplier(Authentication authentication) {
+ Objects.requireNonNull(authentication, "authentication must not be null");
+ return () -> {
+ try {
+ return resolveAuthData(authentication);
+ } catch (PulsarClientException e) {
+ throw new RuntimeException("Failed to obtain broker-client authentication TLS material", e);
+ }
+ };
+ }
+
+ // The BROKER_CLIENT TLS fold is host-agnostic — TLS key material does not vary by peer — so the
+ // host-less getAuthData() is exactly what we want; isolate its deprecation here.
+ @SuppressWarnings("deprecation")
+ private static AuthenticationDataProvider resolveAuthData(Authentication authentication)
+ throws PulsarClientException {
+ return authentication.getAuthData();
+ }
+
+ @Override
+ public CompletableFuture<Void> initialize(TlsFactoryInitContext context) {
+ try {
+ Objects.requireNonNull(context, "context must not be null");
+ // Required, not optional: every acquisition path in this factory reads files and parses key
+ // material. Without an executor the work would run inline on the caller's thread, which the SPI
+ // contract says may be a consumer event loop. Fail at wiring time rather than stalling a channel.
+ Objects.requireNonNull(context.blockingExecutor(),
+ "TlsFactoryInitContext.blockingExecutor() must not be null: FileBasedTlsFactory performs "
+ + "blocking file and key-material loading and must never run it on a consumer thread");
+ this.initContext = context;
+ // Cancel any poll scheduled by a prior initialize() so a second call does not orphan the first:
+ // the field is overwritten below and the old task would otherwise run forever.
+ ScheduledFuture<?> previousPoll = this.pollFuture;
+ if (previousPoll != null) {
+ previousPoll.cancel(false);
+ }
+ // Same reasoning for the metrics: a prior initialize() registered an observable gauge that stays
+ // registered on the meter until close(), so overwriting the field without closing it would leave
+ // an orphaned callback reporting stale per-purpose timestamps forever.
+ TlsReloadMetrics previousMetrics = this.metrics;
+ if (previousMetrics != null) {
+ previousMetrics.close();
+ }
+ this.metrics = TlsReloadMetrics.create(context.openTelemetry(), context.clock());
+ int interval = settings.refreshIntervalSeconds();
+ if (interval > 0 && context.scheduler() != null) {
+ this.pollFuture = context.scheduler().scheduleWithFixedDelay(
+ this::pollSafely, interval, interval, TimeUnit.SECONDS);
+ }
+ log.debug().attr("purposes", registry.keySet()).attr("refreshIntervalSeconds", interval)
+ .log("Initialized FileBasedTlsFactory");
+ return CompletableFuture.completedFuture(null);
+ } catch (Throwable t) {
+ return CompletableFuture.failedFuture(t);
+ }
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(TlsPurpose purpose, Class<T> instanceClass) {
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, TlsEndpoint endpoint, Class<T> instanceClass) {
+ // The default file-based factory serves purpose-scoped material and ignores the endpoint hint.
+ return createOneShot(purpose, instanceClass);
+ }
+
+ @Override
+ public <T> CompletableFuture<Optional<TlsHandle<T>>> createInstance(
+ TlsPurpose purpose, Class<T> instanceClass, Consumer<T> onLoadOrReload) {
+ if (onLoadOrReload == null) {
+ // SPI contract: argument-validation failures complete the returned future exceptionally — this
+ // method never throws on the calling thread.
+ return CompletableFuture.failedFuture(new NullPointerException("onLoadOrReload must not be null"));
+ }
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ synchronized (source) {
+ // FIX F: close() runs releaseAll() under this same source lock, and may have completed after
+ // the outer closed-check but before this task acquired the lock. Re-check here so we never
+ // build+cache+deliver a context (and register a subscription) whose factory-owned reference
+ // would then never be released — that would leak past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ Subscription<T> subscription = new Subscription<>(instanceClass, onLoadOrReload);
+ // Initial delivery happens-before the returned future completes (same thread, ordered).
+ subscription.deliver(instance);
+ source.subscriptions.add(subscription);
+ return Optional.of((TlsHandle<T>) new SubscriptionHandle<>(source, subscription));
+ }
+ });
+ }
+
+ private <T> CompletableFuture<Optional<TlsHandle<T>>> createOneShot(TlsPurpose purpose, Class<T> instanceClass) {
+ if (!isSupported(instanceClass)) {
+ return CompletableFuture.completedFuture(Optional.empty());
+ }
+ if (closed) {
+ return CompletableFuture.failedFuture(new IllegalStateException("FileBasedTlsFactory is closed"));
+ }
+ return runAsync(() -> {
+ RegisteredSource source = resolve(purpose);
+ synchronized (source) {
+ // FIX F: re-check under the source lock (see createInstance above) so a task racing a
+ // concurrent close()/releaseAll() never builds+retains a context that then leaks past shutdown.
+ if (closed) {
+ throw new IllegalStateException("FileBasedTlsFactory is closed");
+ }
+ T instance = loadInitialInstance(source, instanceClass);
+ retain(instance);
+ return Optional.of((TlsHandle<T>) new OneShotHandle<>(instance));
+ }
+ });
+ }
+
+ /**
+ * Load (or reuse the cached) instance of {@code instanceClass} for the resolved source, recording a
+ * {@code pulsar.tls.reload} attempt for the source's purpose. A resolution failure upstream (an
+ * unconfigured server purpose) is a startup configuration error and is not counted here — only actual
+ * material loads are. Must be called while holding the source monitor.
+ *
+ * <p>Success is counted only for a <em>real</em> (re)load, mirroring the poll path: the first build of a
+ * context class for this source, or a refresh that found changed material. A repeat one-shot acquisition
+ * that re-serves the memoized context (every new connection, on the acquire-per-connection paths) is not a
+ * reload — counting it would inflate {@code pulsar.tls.reload} and keep advancing
+ * {@code pulsar.tls.last_reload_success}, masking exactly the stalled rotation the Monitoring section
+ * alerts on. Failures stay unconditional: an attempt that threw is always worth counting.
+ */
+ private <T> T loadInitialInstance(RegisteredSource source, Class<T> instanceClass) throws Exception {
+ // Hoisted out of the try so the catch can tell whether this call already CONSUMED a rotation before
+ // failing (see the comment on the catch below). Null means currentMaterial() itself threw, which
+ // commits no baseline and so consumes nothing.
+ MaterialSource.RefreshOutcome outcome = null;
+ try {
+ outcome = source.currentMaterial();
+ // Sampled before acquireInstance, which is what populates the memo (both calls run under the
+ // source monitor held by the caller, so no other acquisition can interleave).
+ boolean firstBuild = source.cachedInstance(instanceClass) == null;
+ T instance = source.acquireInstance(instanceClass, outcome.material(), settings);
+ // Rotation fan-out: currentMaterial() CONSUMES the source's change signal (refresh() commits the new
+ // mtime baseline), so whoever refreshes first is the only caller that ever sees changed=true. Without
+ // this, a one-shot acquisition (or an initial subscribing acquisition) that observes a rotation first
+ // leaves every later poll reporting changed=false and the subscribers on this same purpose wedged on
+ // the pre-rotation instance forever — e.g. an https:// client whose FrameworkHttpClientFactory
+ // subscribes to CLIENT_DEFAULT while another path acquires one-shot on it. Deliver the observed
+ // change here, exactly as the poll would have; a delivery failure arms pendingRedeliver so the next
+ // poll retries. No extra metric is recorded — this shares the single recordLoad below.
+ // Also drive the retry when a previous rotation's fan-out failed: the poll is the usual driver,
+ // but it is disabled entirely when refreshIntervalSeconds <= 0, and even when enabled an
+ // acquisition may get here first. Without this, a subscriber wedged by a failed rebuild would
+ // stay on the pre-rotation instance until the files changed again.
+ boolean retryPending = source.pendingRedeliver();
+ boolean delivered = true;
+ if (outcome.changed() || retryPending) {
+ delivered = source.deliverToSubscribers(outcome.material(), settings);
+ }
+ if (outcome.changed() || retryPending || firstBuild) {
+ recordLoad(source.purpose, delivered);
+ }
+ return instance;
+ } catch (Exception e) {
+ recordLoad(source.purpose, false);
+ // The material parsed (the baseline is committed) but building or delivering the context failed.
+ // currentMaterial() has therefore already CONSUMED this rotation's change signal, so every later
+ // poll would report changed=false and — without arming the redeliver flag here — return early,
+ // leaving the subscribers wedged on the pre-rotation instance until the files change again.
+ // deliverToSubscribers arms the flag itself on a partial delivery failure; this covers the case
+ // where the failure happened before it was ever reached.
+ if (outcome != null && outcome.changed()) {
+ source.armRedeliver();
+ }
+ // Keep-last-good (PIP-478): a one-shot (or initial subscribing) acquisition during a
+ // non-atomic rotation window — e.g. the cert file briefly unreadable while it is being replaced —
+ // must not fail when a prior load already built a context of this class. Serve that last-good
+ // instance and WARN; the reload-failure metric was recorded above. Fail only when there is no
+ // last-good to fall back on (a genuine startup misconfiguration, per the fail-fast contract).
+ T cached = source.cachedInstance(instanceClass);
+ if (cached != null) {
+ log.warn().attr("purpose", source.purpose).exception(e)
+ .log("Failed to load TLS material; serving the last-good instance");
+ return cached;
+ }
+ throw e;
+ }
+ }
+
+ private void recordLoad(TlsPurpose purpose, boolean success) {
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.recordLoad(purpose, success);
+ }
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ ScheduledFuture<?> poll = this.pollFuture;
+ if (poll != null) {
+ poll.cancel(false);
+ }
+ for (RegisteredSource source : registry.values()) {
+ source.releaseAll();
+ }
+ RegisteredSource systemDefault = this.systemDefaultSource;
+ if (systemDefault != null) {
+ systemDefault.releaseAll();
+ }
+ TlsReloadMetrics m = this.metrics;
+ if (m != null) {
+ m.close();
+ }
+ }
+
+ /**
+ * Resolve a requested purpose to the {@link RegisteredSource} that owns its material, applying the
+ * role's terminal-resolution rule when nothing is configured for the purpose.
+ *
+ * @throws TlsMaterialUnavailableException when a server-role purpose has no material configured
+ */
+ private RegisteredSource resolve(TlsPurpose purpose) {
+ Objects.requireNonNull(purpose, "purpose must not be null");
+ RegisteredSource source = registry.get(purpose);
+ if (source != null) {
+ return source;
+ }
+ if (purpose.role() == TlsPurpose.Role.CLIENT) {
+ return systemDefaultSource();
+ }
+ throw new TlsMaterialUnavailableException(
+ "No TLS material configured for server purpose " + purpose);
+ }
+
+ private RegisteredSource systemDefaultSource() {
+ RegisteredSource existing = this.systemDefaultSource;
+ if (existing != null) {
+ return existing;
+ }
+ synchronized (this) {
+ if (this.systemDefaultSource == null) {
+ // System default: verify hostnames, OS trust store, no client certificate. A constant
+ // source (no files, never rotates).
+ TlsPolicy defaultPolicy = TlsPolicy.builder().build();
+ this.systemDefaultSource = new RegisteredSource(
+ TlsPurpose.CLIENT_DEFAULT, defaultPolicy, null);
+ }
+ return this.systemDefaultSource;
+ }
+ }
+
+ private void pollSafely() {
+ if (closed) {
+ return;
+ }
+ try {
+ for (RegisteredSource source : registry.values()) {
+ source.poll(settings, metrics);
Review Comment:
`pollSafely` runs on `context.scheduler()`, and `RegisteredSource.poll` synchronously stats files, parses PEM/keystores and rebuilds contexts — all under the source monitor.
`initialize()` (line 173) rejects a null `blockingExecutor` with exactly this rationale: "every acquisition path in this factory reads files and parses key material... Without an executor the work would run inline on the caller's thread." The same argument applies to the poll. With several purposes and key material on a slow or NFS-backed mount, this occupies a shared framework scheduler thread for the duration. Could the scheduled task just dispatch to `blockingExecutor`?
##########
pulsar-common/src/test/resources/META-INF/services/java.security.Provider:
##########
@@ -0,0 +1 @@
+org.apache.pulsar.common.util.tls.ServiceLoadableTestProvider
Review Comment:
This registers `ServiceLoadableTestProvider` for the *whole* `pulsar-common` test source set, so any other test that walks `ServiceLoader<Provider>` or enumerates providers now sees it — including, indirectly, `JcaProviders.resolveNamedProvider` itself in unrelated tests.
Low risk given what the provider does, but it's a global test-classpath side effect from a fixture that only two test classes need. Is there a way to scope it (a dedicated source set, or installing it via `Security.addProvider` in a `@BeforeClass` instead)?
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/JettyTlsFactory.java:
##########
@@ -0,0 +1,586 @@
+/*
+ * 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.jetty.tls;
+
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.tls.impl.TlsContexts;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * The framework's Jetty integration for the PIP-478 TLS SPI. Both {@link SslContextFactory.Server} and
+ * {@link SslContextFactory.Client} are well-known SPI classes: the framework first asks the
+ * {@link PulsarTlsFactory} to supply one natively (a custom factory may build and own it, reload
+ * included); only when the factory returns {@code empty()} for the Jetty class does the framework
+ * synthesize a <em>vanilla</em> (never subclassed) one from an {@code SSLContext} subscription. The
+ * default {@code FileBasedTlsFactory} returns {@code empty()} for the Jetty classes, so the synthesized
+ * path is the usual one.
+ *
+ * <p><b>Factory-supplied (native) instances.</b> When the factory supplies the Jetty factory directly it
+ * is handed back <em>unstarted</em> (the connector / {@code HttpClient} starts it), is the factory's
+ * same-instance-per-purpose, and the factory owns its reload on material rotation. The framework only
+ * holds the returned {@link TlsHandle} for disposal and never drives {@code setSslContext}/{@code reload}
+ * or overlays consumer configuration on such an instance.
+ *
+ * <p>This deliberately abandons the unsound {@code getSslContext()} override of the superseded PIP-337
+ * {@code JettySslContextFactory}. Instead it uses
+ * Jetty's documented hot-reload API — the same one {@code KeyStoreScanner} uses: an {@code SSLContext}
+ * subscription drives {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each
+ * later delivery (once started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context and re-selects
+ * protocols/ciphers. Existing connections keep their sessions; new connections use the new context.
+ *
+ * <p><b>{@code SSLParameters} companion (PIP-478).</b> Because these are synthesized paths (the factory
+ * returned {@code empty()} for the Jetty class and supplies only the {@code SSLContext}), the framework also
+ * asks the factory for its optional {@code javax.net.ssl.SSLParameters} companion — the engine-level baseline
+ * a bare {@code SSLContext} cannot express — and maps its non-null members onto the Jetty setters: enabled
+ * protocols ({@link SslContextFactory#setIncludeProtocols}) and cipher suites
+ * ({@link SslContextFactory#setIncludeCipherSuites}), and (server side, merge rule 4) the authoritative
+ * client-auth mode ({@link SslContextFactory.Server#setNeedClientAuth} /
+ * {@link SslContextFactory.Server#setWantClientAuth}). The initial companion is overlaid before start (at build
+ * time); on each subsequent <em>rotation</em> delivery it is re-requested <em>asynchronously</em> — the reload
+ * callback composes {@code createInstance(purpose, SSLParameters.class)} with {@code whenComplete} and only then
+ * calls {@code reload(...)}, so engine policy rotates with material (pip-478.md:736) yet the companion is
+ * <b>never joined on the delivery thread</b>. Joining there would self-deadlock a custom factory that dispatches
+ * companion creation to the same single-thread scheduler that runs the poll delivery — the exact hazard
+ * {@code TlsContextAcquisition.SynthesizingSubscription} avoids by composing the companion asynchronously.
+ *
+ * <p>Because those asynchronous re-requests complete on arbitrary threads and may finish out of order, the
+ * synthesized reload mirrors the two ordering guarantees of {@code SynthesizingSubscription} (see
+ * {@code JettyReloadCoordinator}): each delivery captures a strictly increasing <em>generation</em> and applies
+ * its {@code reload(...)} only while that generation is still the latest, so a companion superseded by a newer
+ * rotation is dropped rather than pinning the listener to a stale context/baseline; and the last
+ * successfully-resolved companion is <em>retained</em> (seeded from the build-time baseline) so a transient
+ * companion-fetch failure during rotation reloads with that last-good baseline rather than downgrading engine
+ * policy (protocols/ciphers and, server side, client-auth) to consumer defaults. Consumer defaults are still
+ * re-applied <em>in full</em> first inside every {@code reload(...)} lambda — protocols, cipher suites and, server
+ * side, client-auth are each re-pinned or cleared unconditionally, since the long-lived {@code SslContextFactory}
+ * persists setter state across {@code reload()} — so any companion member legitimately dropped by a newer delivery
+ * reverts to the consumer default rather than staying stuck from the previous companion.
+ * {@code empty()} leaves the consumer's configuration in force, exactly as before.
+ */
+@CustomLog
+public final class JettyTlsFactory {
+
+ static {
+ // DO NOT EDIT - Load Conscrypt provider
+ if (JcaProviders.CONSCRYPT_PROVIDER != null) {
+ }
+ }
+
+ private JettyTlsFactory() {
+ }
+
+ /**
+ * A Jetty server factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the web service stops.
+ *
+ * @param sslContextFactory the (unstarted) Jetty server factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableServerTls(SslContextFactory.Server sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * A Jetty client factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the owning HTTP client
+ * / servlet is destroyed.
+ *
+ * @param sslContextFactory the (unstarted) Jetty client factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableClientTls(SslContextFactory.Client sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * Build a self-reloading {@link SslContextFactory.Server} for a purpose, handed back <em>unstarted</em>
+ * (Jetty starts it with the connector lifecycle) with its initial {@code SSLContext} already set.
+ *
+ * @param factory the TLS factory to subscribe to
+ * @param purpose the server purpose (e.g. {@link TlsPurpose#WEB})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param requireTrustedClientCert whether to require (vs. request) a trusted client certificate
+ * @param allowInsecureConnection whether an untrusted client cert is accepted under optional client auth
+ * @param ciphers enabled cipher suites, or {@code null} for defaults
+ * @param protocols enabled protocols, or {@code null} for defaults
+ * @return the reloading factory and its subscription handle
+ */
+ public static ReloadableServerTls createReloadingServerFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString,
+ boolean requireTrustedClientCert,
+ boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ // Ask the factory first: a custom factory may natively supply the Jetty server factory (a
+ // well-known class). When it does, hand it back unstarted with the factory owning its reload and
+ // configuration; the framework overlays no consumer config on it. The default file-based factory
+ // returns empty() here, so the synthesized, self-reloading fallback below runs (the usual path).
+ Optional<TlsHandle<SslContextFactory.Server>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Server.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Server> handle = nativeFactory.get();
+ return new ReloadableServerTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
+ // Consumer config plus the factory's engine-policy companion (if any), before start. The resolved
+ // companion seeds the coordinator's last-good baseline so a companion-fetch failure on the very first
+ // rotation retains it rather than downgrading to consumer defaults.
+ SSLParameters initialBaseline = configureServerBaseline(sslContextFactory, factory, purpose,
+ sslProviderString, requireTrustedClientCert, allowInsecureConnection, ciphers, protocols);
+
+ // Each rotation re-requests the companion asynchronously (off the delivery thread) and applies it under
+ // a generation guard so an out-of-order companion cannot pin a stale context, retaining the last-good
+ // baseline across a transient companion failure. See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, sslContextFactory,
+ initialBaseline, (newContext, baseline) -> {
+ sslContextFactory.setSslContext(newContext);
+ // Re-apply the consumer defaults first so a companion member dropped by this delivery
+ // (notably client-auth) reverts to the consumer default rather than staying stuck from the
+ // previous companion, then overlay the generation-guarded, last-good companion.
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert,
+ allowInsecureConnection, ciphers, protocols);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery)
+ .join()
+ .orElseThrow(() -> new IllegalStateException(
+ "TLS factory supplied no SSLContext for purpose " + purpose));
+ return new ReloadableServerTls(sslContextFactory, coordinator.bind(subscription));
+ }
+
+ /**
+ * Build an {@link SslContextFactory.Client} for a purpose (used by the proxy's {@code AdminProxyHandler},
+ * whose Jetty {@code HttpClient} outlives broker-client material rotation), handed back
+ * <em>unstarted</em>. Mirroring {@link #createReloadingServerFactory}, the framework first asks the
+ * factory to supply the Jetty client factory natively; a custom factory that does so owns its reload and
+ * endpoint identification, and the framework overlays nothing on it. Otherwise a vanilla, self-reloading
+ * one is synthesized: an {@code SSLContext} subscription drives
+ * {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each later delivery (once
+ * started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context so new connections use
+ * the rotated material. Dispose the returned {@link ReloadableClientTls#subscription()} when the owning
+ * client is destroyed.
+ *
+ * @param factory the TLS factory to acquire from / subscribe to
+ * @param purpose the client purpose (e.g. {@link TlsPurpose#BROKER_CLIENT})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param enableHostnameVerification whether to verify the peer hostname; when {@code false} the
+ * synthesized client's endpoint identification is disabled (a
+ * factory-supplied native client owns this itself and is left untouched)
+ * @return the client factory and the handle backing it
+ */
+ public static ReloadableClientTls createReloadingClientFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString,
+ boolean enableHostnameVerification) {
+ // Ask the factory first: a custom factory may natively supply the Jetty client factory (a well-known
+ // class, mirroring the Server variant) to customize proxy->broker admin TLS. When it does, hand it
+ // back unstarted with the factory owning its reload and its own endpoint identification; the
+ // framework overlays no consumer config on it. The default file-based factory returns empty() here,
+ // so the SSLContext-synthesized, self-reloading fallback below runs (the usual path, including
+ // rotation of the long-lived admin HttpClient's broker-client material).
+ Optional<TlsHandle<SslContextFactory.Client>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Client.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Client> handle = nativeFactory.get();
+ return new ReloadableClientTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Client client = new SslContextFactory.Client();
+ if (StringUtils.isNotBlank(sslProviderString)) {
+ client.setProvider(sslProviderString);
+ }
+ // Pin the {TLSv1.3, TLSv1.2} floor and overlay the factory's engine-policy companion (if any), before
+ // start; the resolved companion seeds the coordinator's last-good baseline (see the Server variant).
+ SSLParameters initialBaseline = configureClientBaseline(client, factory, purpose);
+ // Hostname verification is a consumer (proxy) concern on the synthesized path: disable endpoint
+ // identification when the consumer has it off (a native factory, handled above, owns this itself). This
+ // is a per-consumer setting applied once at build, not part of the per-delivery companion overlay.
+ if (!enableHostnameVerification) {
+ client.setEndpointIdentificationAlgorithm(null);
+ }
+
+ // Rotations re-request the companion asynchronously (off the delivery thread) and apply it under a
+ // generation guard, retaining the last-good baseline across a transient companion failure (client-auth
+ // is a server concept; endpoint identification stays as set at build). See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, client, initialBaseline,
+ (newContext, baseline) -> {
+ client.setSslContext(newContext);
+ // Re-apply the consumer defaults first (the {TLSv1.3, TLSv1.2} floor and an unrestricted cipher
+ // list), then overlay the generation-guarded, last-good companion so a companion member dropped
+ // by this delivery reverts to those defaults rather than staying stuck from the previous one.
+ applyClientConfig(client);
+ if (baseline != null) {
+ applyClientBaseline(client, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery)
+ .join()
+ .orElseThrow(() -> new IllegalStateException(
+ "TLS factory supplied no SSLContext for purpose " + purpose));
+ return new ReloadableClientTls(client, coordinator.bind(subscription));
+ }
+
+ /**
+ * Apply the consumer config, then overlay the factory's engine-policy companion, onto a synthesized server
+ * factory — at build time only (off any event loop; the companion is joined here). Each subsequent rotation
+ * delivery re-requests the companion asynchronously and re-applies it inside the {@code reload(...)} lambda
+ * (see {@link JettyReloadCoordinator}), never joined on the delivery thread.
+ *
+ * @return the resolved companion baseline, or {@code null} when the factory supplied none — used to seed the
+ * coordinator's retained last-good baseline.
+ */
+ private static SSLParameters configureServerBaseline(SslContextFactory.Server sslContextFactory,
+ PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString, boolean requireTrustedClientCert,
+ boolean allowInsecureConnection, Set<String> ciphers,
+ Set<String> protocols) {
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert, allowInsecureConnection,
+ ciphers, protocols);
+ SSLParameters baseline = resolveBaselineParameters(factory, purpose).orElse(null);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ return baseline;
+ }
+
+ /**
+ * Pin the {@code {TLSv1.3, TLSv1.2}} floor, then overlay the factory companion's protocols/ciphers, onto a
+ * synthesized client factory — at build time only (off any event loop; the companion is joined here). Each
+ * subsequent rotation delivery re-requests the companion asynchronously and re-pins the floor + overlays it
+ * inside the {@code reload(...)} lambda (see {@link JettyReloadCoordinator}), never joined on the delivery
+ * thread. Client-auth is a server concept and is not mapped here; endpoint identification is a per-consumer
+ * setting applied once at build.
+ *
+ * @return the resolved companion baseline, or {@code null} when the factory supplied none — used to seed the
+ * coordinator's retained last-good baseline.
+ */
+ private static SSLParameters configureClientBaseline(SslContextFactory.Client client, PulsarTlsFactory factory,
+ TlsPurpose purpose) {
+ applyClientConfig(client);
+ SSLParameters baseline = resolveBaselineParameters(factory, purpose).orElse(null);
+ if (baseline != null) {
+ applyClientBaseline(client, baseline);
+ }
+ return baseline;
+ }
+
+ /**
+ * The synthesized client's consumer defaults, shared by the build-time overlay and every reload lambda so both
+ * agree on what a dropped companion member reverts to: the {@code {TLSv1.3, TLSv1.2}} floor, and an unrestricted
+ * cipher list (an empty include list means "no restriction" in Jetty). Both are cleared/re-pinned unconditionally
+ * because the factory is long-lived and persists setter state across {@code reload()}. The provider and endpoint
+ * identification are per-consumer settings applied once at build, not part of this per-delivery reset.
+ */
+ private static void applyClientConfig(SslContextFactory.Client client) {
+ client.setIncludeProtocols(TlsContexts.DEFAULT_ENABLED_PROTOCOLS.toArray(new String[0]));
+ client.setIncludeCipherSuites();
+ }
+
+ private static void applyServerConfig(SslContextFactory.Server sslContextFactory, String sslProviderString,
+ boolean requireTrustedClientCertOnConnect, boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ if (ciphers != null && !ciphers.isEmpty()) {
+ sslContextFactory.setIncludeCipherSuites(ciphers.toArray(new String[0]));
+ } else {
+ // Clear the include list explicitly (not just rely on the fresh-factory default), for the same reason
+ // needClientAuth is reset below: this method is re-applied on each reload of a long-lived factory, so a
+ // prior companion delivery that pinned cipher suites must revert to the consumer default before a later
+ // companion (or its absence) is overlaid. An empty include list means "no restriction" in Jetty --
+ // SslContextFactory.processIncludeExcludePatterns falls back to the SSLContext's enabled suites.
+ sslContextFactory.setIncludeCipherSuites();
+ }
+ // Pin the enabled protocols even when unconfigured, matching the {TLSv1.3, TLSv1.2} floor the native
+ // Netty path applies rather than deferring to the provider default. A factory-supplied companion,
+ // applied afterwards by applyServerBaseline, still overrides this.
+ if (protocols != null && !protocols.isEmpty()) {
+ sslContextFactory.setIncludeProtocols(protocols.toArray(new String[0]));
+ } else {
+ sslContextFactory.setIncludeProtocols(TlsContexts.DEFAULT_ENABLED_PROTOCOLS.toArray(new String[0]));
+ }
+ if (StringUtils.isNotBlank(sslProviderString)) {
+ sslContextFactory.setProvider(sslProviderString);
+ }
+ if (requireTrustedClientCertOnConnect) {
+ sslContextFactory.setNeedClientAuth(true);
+ sslContextFactory.setTrustAll(false);
+ } else {
+ // PIP-478: optional client auth requests but does not require a client cert. An untrusted
+ // client cert is accepted at the handshake only when tlsAllowInsecureConnection=true, aligning the
+ // web listener with the Netty binary listener's semantics and diverging from the pre-5.0 Jetty
+ // path, which trusted any presented client cert whenever client auth was optional (see PIP-478
+ // Security Considerations).
+ //
+ // The actual enforcement is the trust managers baked into the SSLContext the framework hands to
+ // Jetty via setSslContext (built from the WEB TlsPolicy's allowInsecureConnection: CA-validating
+ // when secure, insecure-trust-all when insecure). Jetty's own setTrustAll only takes effect when
+ // Jetty builds the SSLContext itself, so it is inert on this setSslContext path; we still scope it
+ // to the insecure flag so the two never disagree (defence in depth) rather than leaving the
+ // inherited unconditional setTrustAll(true).
+ // Clear needClientAuth explicitly (not just rely on the fresh-factory default): this method is
+ // re-applied on each reload, so a prior companion delivery that set needClientAuth must be reset to
+ // the consumer default here before a later companion (or its absence) is overlaid.
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(true);
+ sslContextFactory.setTrustAll(allowInsecureConnection);
+ }
+ // https://jetty.org/docs/jetty/12.1/operations-guide/protocols/index.html#ssl-sni
+ // Set to false for backwards compatibility with Jetty 9.x
+ sslContextFactory.setSniRequired(false);
+ }
+
+ /**
+ * Ask the factory to supply a native Jetty {@code jettyClass} for {@code purpose} (one-shot). Jetty's
+ * {@link SslContextFactory.Server} and {@link SslContextFactory.Client} are well-known SPI classes, so a
+ * custom factory MAY build one directly; the default {@code FileBasedTlsFactory} returns
+ * {@link Optional#empty()}, in which case the caller synthesizes the factory from an {@code SSLContext}
+ * subscription. A supplied instance is the factory's own (unstarted, same-instance-per-purpose,
+ * factory-driven reload) — the caller returns it verbatim and keeps the {@link TlsHandle} for disposal.
+ * Resolved at factory-build time (off any event loop), mirroring {@link #resolveBaselineParameters}.
+ */
+ private static <T extends SslContextFactory> Optional<TlsHandle<T>> acquireNativeJettyFactory(
+ PulsarTlsFactory factory, TlsPurpose purpose, Class<T> jettyClass) {
+ return factory.createInstance(purpose, jettyClass).join();
+ }
+
+ /**
+ * Request the factory's optional {@code SSLParameters} companion for a purpose (one-shot) at factory-build
+ * time, joining off any event loop, and return the supplied instance or {@link Optional#empty()} when the
+ * factory supplies none. Rotation deliveries do NOT use this: they re-request the companion asynchronously
+ * inside {@link JettyReloadCoordinator} (never joined on the delivery thread) and unwrap it via
+ * {@link #extractBaseline}.
+ */
+ private static Optional<SSLParameters> resolveBaselineParameters(PulsarTlsFactory factory, TlsPurpose purpose) {
+ return Optional.ofNullable(extractBaseline(factory.createInstance(purpose, SSLParameters.class).join()));
+ }
+
+ /**
+ * Unwrap the factory's {@code SSLParameters} companion from its handle, disposing the handle afterwards (a
+ * companion carries no reference-counted state). Returns {@code null} when the factory supplied none
+ * ({@link Optional#empty()}). Used both by the build-time {@link #resolveBaselineParameters} and by the
+ * asynchronous per-rotation re-request in {@link JettyReloadCoordinator}.
+ */
+ private static SSLParameters extractBaseline(Optional<TlsHandle<SSLParameters>> handle) {
+ if (handle.isEmpty()) {
+ return null;
+ }
+ TlsHandle<SSLParameters> paramsHandle = handle.get();
+ try {
+ return paramsHandle.get();
+ } finally {
+ paramsHandle.dispose();
+ }
+ }
+
+ /**
+ * Overlay a factory-supplied engine baseline onto a synthesized server factory (PIP-478 merge order):
+ * enabled protocols/cipher suites when the companion sets them, and the companion's client-auth mode as
+ * authoritative (rule 4) — {@code needClientAuth} wins over {@code wantClientAuth}, neither means none.
+ */
+ private static void applyServerBaseline(SslContextFactory.Server sslContextFactory, SSLParameters baseline) {
+ if (baseline.getProtocols() != null) {
+ sslContextFactory.setIncludeProtocols(baseline.getProtocols());
+ }
+ if (baseline.getCipherSuites() != null) {
+ sslContextFactory.setIncludeCipherSuites(baseline.getCipherSuites());
+ }
+ if (baseline.getNeedClientAuth()) {
+ sslContextFactory.setNeedClientAuth(true);
+ } else if (baseline.getWantClientAuth()) {
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(true);
+ } else {
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(false);
+ }
+ }
+
+ /**
+ * Overlay a factory-supplied engine baseline onto a synthesized client factory: enabled protocols/cipher
+ * suites only (client-auth is a server concept; SNI/hostname verification remain per-connection).
+ */
+ private static void applyClientBaseline(SslContextFactory.Client client, SSLParameters baseline) {
+ if (baseline.getProtocols() != null) {
+ client.setIncludeProtocols(baseline.getProtocols());
+ }
+ if (baseline.getCipherSuites() != null) {
+ client.setIncludeCipherSuites(baseline.getCipherSuites());
+ }
+ }
+
+ /**
+ * Per-subscription reload coordinator for the synthesized Jetty paths. It ports the two ordering guarantees
+ * of {@code TlsContextAcquisition.SynthesizingSubscription} to Jetty's hot-reload API, which the naive
+ * "compose {@code createInstance(SSLParameters)} then {@code reload}" delivery lacked:
+ *
+ * <ul>
+ * <li><b>Generation guard.</b> Each delivery captures a strictly increasing generation (deliveries are
+ * serial per subscription, per the SPI contract). A rotation's companion re-request is composed
+ * asynchronously and may complete on an arbitrary thread and out of order, so its {@code reload(...)}
+ * is applied — under a lock — only while its generation is still the latest; a companion superseded
+ * by a newer rotation is dropped rather than pinning the listener to a stale context/baseline.</li>
+ * <li><b>Last-good baseline retention.</b> The last successfully-resolved companion is retained (seeded
+ * from the build-time baseline). A transient companion-fetch failure during rotation reloads with that
+ * last-good baseline rather than consumer defaults, so it cannot silently drop protocols/ciphers or
+ * (server side) client-auth. The retained baseline is updated only for a successfully-resolved,
+ * non-superseded companion, under the same lock.</li>
+ * </ul>
+ *
+ * <p>The companion is never joined on the delivery thread (the self-deadlock hazard described on the class
+ * javadoc); only the <em>first</em> delivery — which fires synchronously inside the subscribe call, before the
+ * built factory is even returned — sets the already-overlaid context directly, mirroring
+ * {@code SynthesizingSubscription}'s pre-fetched first delivery. Every later delivery is a rotation and
+ * re-requests the companion, <em>including one that arrives before the connector/client starts</em>; whether
+ * the factory is started only decides how the result is applied (Jetty's {@code reload(...)} once started, the
+ * same setters directly before), so a factory started after such a rotation starts with that rotation's
+ * material AND its companion policy rather than the stale build-time baseline.
+ */
+ private static final class JettyReloadCoordinator {
+
+ private final PulsarTlsFactory factory;
+ private final TlsPurpose purpose;
+ private final SslContextFactory target;
+ // Applies the rotated context + (nullable) companion baseline inside Jetty's reload lambda.
+ private final BiConsumer<SSLContext, SSLParameters> applyReload;
+ // Last successfully-resolved companion, seeded from the pre-fetched build-time baseline. Retained across
+ // a transient companion-fetch failure so a rotation cannot silently downgrade engine policy.
+ private volatile SSLParameters lastBaseline;
+ // One-shot: only the first (synchronous, pre-fetched) delivery reuses the build-time baseline; every
+ // later delivery is a rotation and re-requests the companion, started or not.
+ private final AtomicBoolean firstDelivery = new AtomicBoolean(true);
+ private final AtomicLong deliveryGeneration = new AtomicLong();
+ private long lastPublishedGeneration;
+ // A rotation's companion request is composed asynchronously, so its completion can land after the
+ // owner disposed the subscription (and, on the server path, after Jetty stopped the connector).
+ // Reloading a stopped/abandoned factory then would be a pointless mutation at best.
+ private final AtomicBoolean disposed = new AtomicBoolean();
+
+ JettyReloadCoordinator(PulsarTlsFactory factory, TlsPurpose purpose, SslContextFactory target,
+ SSLParameters initialBaseline, BiConsumer<SSLContext, SSLParameters> applyReload) {
+ this.factory = factory;
+ this.purpose = purpose;
+ this.target = target;
+ this.lastBaseline = initialBaseline;
+ this.applyReload = applyReload;
+ }
+
+ /**
+ * Wrap the backing subscription so disposing it also stops this coordinator. Synchronized on the same
+ * monitor as {@link #publish}, so dispose returns only once any in-flight publish has finished —
+ * setting the flag alone would still let a publisher that had already passed the check reload a
+ * factory its owner has torn down.
+ */
+ TlsHandle<SSLContext> bind(TlsHandle<SSLContext> subscription) {
+ return new TlsHandle<>() {
+ @Override
+ public SSLContext get() {
+ return subscription.get();
+ }
+
+ @Override
+ public void dispose() {
+ synchronized (JettyReloadCoordinator.this) {
+ disposed.set(true);
+ }
+ subscription.dispose();
+ }
+ };
+ }
+
+ // Serial per subscription (SPI contract), so each delivery gets a strictly increasing generation.
+ void onDelivery(SSLContext newContext) {
+ long generation = deliveryGeneration.incrementAndGet();
+ if (firstDelivery.compareAndSet(true, false)) {
+ // The first delivery fires synchronously inside the subscribe call, before the built factory is
+ // returned (let alone started): the build-time companion was already overlaid and seeds
+ // lastBaseline, so only the context is missing — set it directly, mirroring
+ // SynthesizingSubscription's pre-fetched first delivery.
+ target.setSslContext(newContext);
+ return;
+ }
+ // Rotation delivery. Re-request the companion so engine policy rotates WITH the material
+ // (pip-478.md:736), resolved ASYNCHRONOUSLY off this delivery thread and never joined here (the
+ // self-deadlock hazard). This runs for rotations delivered BEFORE start too — those must refresh the
+ // companion as well, otherwise the connector would start with the rotated context but the stale
+ // build-time baseline; only the mechanism used to apply the result differs (see publish). The
+ // generation guard in publish drops a superseded companion; the last-good baseline is maintained
+ // there, never here, so a superseded companion completing late cannot regress it.
+ factory.createInstance(purpose, SSLParameters.class).whenComplete((companion, err) ->
+ publish(newContext, err != null ? null : extractBaseline(companion), generation, err == null));
+ }
+
+ // Apply the rotation for `generation`, dropping a result already superseded by a newer delivery.
+ // Synchronized because rotation companions may complete on arbitrary threads and out of order; the guard
+ // keeps the applied context, the reload callback, AND the retained last-good baseline monotonic in
+ // delivery order.
+ private synchronized void publish(SSLContext newContext, SSLParameters baseline, long generation,
+ boolean baselineResolved) {
+ if (generation < lastPublishedGeneration || disposed.get()) {
+ return;
+ }
+ lastPublishedGeneration = generation;
+ if (baselineResolved) {
+ lastBaseline = baseline;
+ } else {
+ // A transient companion-fetch failure must not downgrade engine policy: reload with the last-good
+ // baseline, read under the same guard so a stale companion can never have regressed it.
+ baseline = lastBaseline;
+ }
+ final SSLParameters effectiveBaseline = baseline;
+ try {
+ if (target.isStarted()) {
Review Comment:
TOCTOU between `isStarted()` and the apply. If the connector starts in that window, the `else` branch mutates an already-started factory without going through `reload()` — so `unload()`/`load()` never runs, the rotated `SSLContext` is silently not picked up, and the listener keeps serving pre-rotation material with no exception and no failure metric.
The window is build → start. Narrow with the 300s default `tlsCertRefreshCheckDurationSec`, but reachable with a short interval and wide open under test. Since the failure mode is silent (the operator sees a successful reload metric and stale material on the wire), it seems worth closing — either by always attempting `reload(...)` and handling the not-started case from its failure, or by performing the check and the apply under the same lock Jetty uses.
##########
pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/JettyTlsFactory.java:
##########
@@ -0,0 +1,586 @@
+/*
+ * 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.jetty.tls;
+
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+import lombok.CustomLog;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.common.tls.impl.TlsContexts;
+import org.apache.pulsar.common.util.tls.JcaProviders;
+import org.apache.pulsar.tls.PulsarTlsFactory;
+import org.apache.pulsar.tls.TlsHandle;
+import org.apache.pulsar.tls.TlsPurpose;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * The framework's Jetty integration for the PIP-478 TLS SPI. Both {@link SslContextFactory.Server} and
+ * {@link SslContextFactory.Client} are well-known SPI classes: the framework first asks the
+ * {@link PulsarTlsFactory} to supply one natively (a custom factory may build and own it, reload
+ * included); only when the factory returns {@code empty()} for the Jetty class does the framework
+ * synthesize a <em>vanilla</em> (never subclassed) one from an {@code SSLContext} subscription. The
+ * default {@code FileBasedTlsFactory} returns {@code empty()} for the Jetty classes, so the synthesized
+ * path is the usual one.
+ *
+ * <p><b>Factory-supplied (native) instances.</b> When the factory supplies the Jetty factory directly it
+ * is handed back <em>unstarted</em> (the connector / {@code HttpClient} starts it), is the factory's
+ * same-instance-per-purpose, and the factory owns its reload on material rotation. The framework only
+ * holds the returned {@link TlsHandle} for disposal and never drives {@code setSslContext}/{@code reload}
+ * or overlays consumer configuration on such an instance.
+ *
+ * <p>This deliberately abandons the unsound {@code getSslContext()} override of the superseded PIP-337
+ * {@code JettySslContextFactory}. Instead it uses
+ * Jetty's documented hot-reload API — the same one {@code KeyStoreScanner} uses: an {@code SSLContext}
+ * subscription drives {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each
+ * later delivery (once started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context and re-selects
+ * protocols/ciphers. Existing connections keep their sessions; new connections use the new context.
+ *
+ * <p><b>{@code SSLParameters} companion (PIP-478).</b> Because these are synthesized paths (the factory
+ * returned {@code empty()} for the Jetty class and supplies only the {@code SSLContext}), the framework also
+ * asks the factory for its optional {@code javax.net.ssl.SSLParameters} companion — the engine-level baseline
+ * a bare {@code SSLContext} cannot express — and maps its non-null members onto the Jetty setters: enabled
+ * protocols ({@link SslContextFactory#setIncludeProtocols}) and cipher suites
+ * ({@link SslContextFactory#setIncludeCipherSuites}), and (server side, merge rule 4) the authoritative
+ * client-auth mode ({@link SslContextFactory.Server#setNeedClientAuth} /
+ * {@link SslContextFactory.Server#setWantClientAuth}). The initial companion is overlaid before start (at build
+ * time); on each subsequent <em>rotation</em> delivery it is re-requested <em>asynchronously</em> — the reload
+ * callback composes {@code createInstance(purpose, SSLParameters.class)} with {@code whenComplete} and only then
+ * calls {@code reload(...)}, so engine policy rotates with material (pip-478.md:736) yet the companion is
+ * <b>never joined on the delivery thread</b>. Joining there would self-deadlock a custom factory that dispatches
+ * companion creation to the same single-thread scheduler that runs the poll delivery — the exact hazard
+ * {@code TlsContextAcquisition.SynthesizingSubscription} avoids by composing the companion asynchronously.
+ *
+ * <p>Because those asynchronous re-requests complete on arbitrary threads and may finish out of order, the
+ * synthesized reload mirrors the two ordering guarantees of {@code SynthesizingSubscription} (see
+ * {@code JettyReloadCoordinator}): each delivery captures a strictly increasing <em>generation</em> and applies
+ * its {@code reload(...)} only while that generation is still the latest, so a companion superseded by a newer
+ * rotation is dropped rather than pinning the listener to a stale context/baseline; and the last
+ * successfully-resolved companion is <em>retained</em> (seeded from the build-time baseline) so a transient
+ * companion-fetch failure during rotation reloads with that last-good baseline rather than downgrading engine
+ * policy (protocols/ciphers and, server side, client-auth) to consumer defaults. Consumer defaults are still
+ * re-applied <em>in full</em> first inside every {@code reload(...)} lambda — protocols, cipher suites and, server
+ * side, client-auth are each re-pinned or cleared unconditionally, since the long-lived {@code SslContextFactory}
+ * persists setter state across {@code reload()} — so any companion member legitimately dropped by a newer delivery
+ * reverts to the consumer default rather than staying stuck from the previous companion.
+ * {@code empty()} leaves the consumer's configuration in force, exactly as before.
+ */
+@CustomLog
+public final class JettyTlsFactory {
+
+ static {
+ // DO NOT EDIT - Load Conscrypt provider
+ if (JcaProviders.CONSCRYPT_PROVIDER != null) {
+ }
+ }
+
+ private JettyTlsFactory() {
+ }
+
+ /**
+ * A Jetty server factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the web service stops.
+ *
+ * @param sslContextFactory the (unstarted) Jetty server factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableServerTls(SslContextFactory.Server sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * A Jetty client factory (factory-supplied native, or framework-synthesized and self-reloading)
+ * together with the handle backing it; dispose the {@link #subscription()} when the owning HTTP client
+ * / servlet is destroyed.
+ *
+ * @param sslContextFactory the (unstarted) Jetty client factory
+ * @param subscription the backing handle — the {@code SSLContext} reload subscription on the
+ * synthesized path, or the native-instance handle when the factory supplied it
+ */
+ public record ReloadableClientTls(SslContextFactory.Client sslContextFactory,
+ TlsHandle<?> subscription) {
+ }
+
+ /**
+ * Build a self-reloading {@link SslContextFactory.Server} for a purpose, handed back <em>unstarted</em>
+ * (Jetty starts it with the connector lifecycle) with its initial {@code SSLContext} already set.
+ *
+ * @param factory the TLS factory to subscribe to
+ * @param purpose the server purpose (e.g. {@link TlsPurpose#WEB})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param requireTrustedClientCert whether to require (vs. request) a trusted client certificate
+ * @param allowInsecureConnection whether an untrusted client cert is accepted under optional client auth
+ * @param ciphers enabled cipher suites, or {@code null} for defaults
+ * @param protocols enabled protocols, or {@code null} for defaults
+ * @return the reloading factory and its subscription handle
+ */
+ public static ReloadableServerTls createReloadingServerFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString,
+ boolean requireTrustedClientCert,
+ boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ // Ask the factory first: a custom factory may natively supply the Jetty server factory (a
+ // well-known class). When it does, hand it back unstarted with the factory owning its reload and
+ // configuration; the framework overlays no consumer config on it. The default file-based factory
+ // returns empty() here, so the synthesized, self-reloading fallback below runs (the usual path).
+ Optional<TlsHandle<SslContextFactory.Server>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Server.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Server> handle = nativeFactory.get();
+ return new ReloadableServerTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
+ // Consumer config plus the factory's engine-policy companion (if any), before start. The resolved
+ // companion seeds the coordinator's last-good baseline so a companion-fetch failure on the very first
+ // rotation retains it rather than downgrading to consumer defaults.
+ SSLParameters initialBaseline = configureServerBaseline(sslContextFactory, factory, purpose,
+ sslProviderString, requireTrustedClientCert, allowInsecureConnection, ciphers, protocols);
+
+ // Each rotation re-requests the companion asynchronously (off the delivery thread) and applies it under
+ // a generation guard so an out-of-order companion cannot pin a stale context, retaining the last-good
+ // baseline across a transient companion failure. See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, sslContextFactory,
+ initialBaseline, (newContext, baseline) -> {
+ sslContextFactory.setSslContext(newContext);
+ // Re-apply the consumer defaults first so a companion member dropped by this delivery
+ // (notably client-auth) reverts to the consumer default rather than staying stuck from the
+ // previous companion, then overlay the generation-guarded, last-good companion.
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert,
+ allowInsecureConnection, ciphers, protocols);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery)
+ .join()
+ .orElseThrow(() -> new IllegalStateException(
+ "TLS factory supplied no SSLContext for purpose " + purpose));
+ return new ReloadableServerTls(sslContextFactory, coordinator.bind(subscription));
+ }
+
+ /**
+ * Build an {@link SslContextFactory.Client} for a purpose (used by the proxy's {@code AdminProxyHandler},
+ * whose Jetty {@code HttpClient} outlives broker-client material rotation), handed back
+ * <em>unstarted</em>. Mirroring {@link #createReloadingServerFactory}, the framework first asks the
+ * factory to supply the Jetty client factory natively; a custom factory that does so owns its reload and
+ * endpoint identification, and the framework overlays nothing on it. Otherwise a vanilla, self-reloading
+ * one is synthesized: an {@code SSLContext} subscription drives
+ * {@link SslContextFactory#setSslContext(SSLContext)} before start, and on each later delivery (once
+ * started) {@link SslContextFactory#reload(Consumer)} atomically swaps the context so new connections use
+ * the rotated material. Dispose the returned {@link ReloadableClientTls#subscription()} when the owning
+ * client is destroyed.
+ *
+ * @param factory the TLS factory to acquire from / subscribe to
+ * @param purpose the client purpose (e.g. {@link TlsPurpose#BROKER_CLIENT})
+ * @param sslProviderString the legacy engine/JSSE provider string passed to Jetty's
+ * {@code SslContextFactory}, or {@code null}/empty for the default. Jetty is
+ * handed a pre-built {@code SSLContext}, so it never loads key material
+ * itself and takes no PIP-478 {@code jcaProvider}.
+ * @param enableHostnameVerification whether to verify the peer hostname; when {@code false} the
+ * synthesized client's endpoint identification is disabled (a
+ * factory-supplied native client owns this itself and is left untouched)
+ * @return the client factory and the handle backing it
+ */
+ public static ReloadableClientTls createReloadingClientFactory(PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString,
+ boolean enableHostnameVerification) {
+ // Ask the factory first: a custom factory may natively supply the Jetty client factory (a well-known
+ // class, mirroring the Server variant) to customize proxy->broker admin TLS. When it does, hand it
+ // back unstarted with the factory owning its reload and its own endpoint identification; the
+ // framework overlays no consumer config on it. The default file-based factory returns empty() here,
+ // so the SSLContext-synthesized, self-reloading fallback below runs (the usual path, including
+ // rotation of the long-lived admin HttpClient's broker-client material).
+ Optional<TlsHandle<SslContextFactory.Client>> nativeFactory =
+ acquireNativeJettyFactory(factory, purpose, SslContextFactory.Client.class);
+ if (nativeFactory.isPresent()) {
+ TlsHandle<SslContextFactory.Client> handle = nativeFactory.get();
+ return new ReloadableClientTls(handle.get(), handle);
+ }
+
+ SslContextFactory.Client client = new SslContextFactory.Client();
+ if (StringUtils.isNotBlank(sslProviderString)) {
+ client.setProvider(sslProviderString);
+ }
+ // Pin the {TLSv1.3, TLSv1.2} floor and overlay the factory's engine-policy companion (if any), before
+ // start; the resolved companion seeds the coordinator's last-good baseline (see the Server variant).
+ SSLParameters initialBaseline = configureClientBaseline(client, factory, purpose);
+ // Hostname verification is a consumer (proxy) concern on the synthesized path: disable endpoint
+ // identification when the consumer has it off (a native factory, handled above, owns this itself). This
+ // is a per-consumer setting applied once at build, not part of the per-delivery companion overlay.
+ if (!enableHostnameVerification) {
+ client.setEndpointIdentificationAlgorithm(null);
+ }
+
+ // Rotations re-request the companion asynchronously (off the delivery thread) and apply it under a
+ // generation guard, retaining the last-good baseline across a transient companion failure (client-auth
+ // is a server concept; endpoint identification stays as set at build). See JettyReloadCoordinator.
+ JettyReloadCoordinator coordinator = new JettyReloadCoordinator(factory, purpose, client, initialBaseline,
+ (newContext, baseline) -> {
+ client.setSslContext(newContext);
+ // Re-apply the consumer defaults first (the {TLSv1.3, TLSv1.2} floor and an unrestricted cipher
+ // list), then overlay the generation-guarded, last-good companion so a companion member dropped
+ // by this delivery reverts to those defaults rather than staying stuck from the previous one.
+ applyClientConfig(client);
+ if (baseline != null) {
+ applyClientBaseline(client, baseline);
+ }
+ });
+
+ TlsHandle<SSLContext> subscription =
+ factory.createInstance(purpose, SSLContext.class, coordinator::onDelivery)
+ .join()
+ .orElseThrow(() -> new IllegalStateException(
+ "TLS factory supplied no SSLContext for purpose " + purpose));
+ return new ReloadableClientTls(client, coordinator.bind(subscription));
+ }
+
+ /**
+ * Apply the consumer config, then overlay the factory's engine-policy companion, onto a synthesized server
+ * factory — at build time only (off any event loop; the companion is joined here). Each subsequent rotation
+ * delivery re-requests the companion asynchronously and re-applies it inside the {@code reload(...)} lambda
+ * (see {@link JettyReloadCoordinator}), never joined on the delivery thread.
+ *
+ * @return the resolved companion baseline, or {@code null} when the factory supplied none — used to seed the
+ * coordinator's retained last-good baseline.
+ */
+ private static SSLParameters configureServerBaseline(SslContextFactory.Server sslContextFactory,
+ PulsarTlsFactory factory, TlsPurpose purpose,
+ String sslProviderString, boolean requireTrustedClientCert,
+ boolean allowInsecureConnection, Set<String> ciphers,
+ Set<String> protocols) {
+ applyServerConfig(sslContextFactory, sslProviderString, requireTrustedClientCert, allowInsecureConnection,
+ ciphers, protocols);
+ SSLParameters baseline = resolveBaselineParameters(factory, purpose).orElse(null);
+ if (baseline != null) {
+ applyServerBaseline(sslContextFactory, baseline);
+ }
+ return baseline;
+ }
+
+ /**
+ * Pin the {@code {TLSv1.3, TLSv1.2}} floor, then overlay the factory companion's protocols/ciphers, onto a
+ * synthesized client factory — at build time only (off any event loop; the companion is joined here). Each
+ * subsequent rotation delivery re-requests the companion asynchronously and re-pins the floor + overlays it
+ * inside the {@code reload(...)} lambda (see {@link JettyReloadCoordinator}), never joined on the delivery
+ * thread. Client-auth is a server concept and is not mapped here; endpoint identification is a per-consumer
+ * setting applied once at build.
+ *
+ * @return the resolved companion baseline, or {@code null} when the factory supplied none — used to seed the
+ * coordinator's retained last-good baseline.
+ */
+ private static SSLParameters configureClientBaseline(SslContextFactory.Client client, PulsarTlsFactory factory,
+ TlsPurpose purpose) {
+ applyClientConfig(client);
+ SSLParameters baseline = resolveBaselineParameters(factory, purpose).orElse(null);
+ if (baseline != null) {
+ applyClientBaseline(client, baseline);
+ }
+ return baseline;
+ }
+
+ /**
+ * The synthesized client's consumer defaults, shared by the build-time overlay and every reload lambda so both
+ * agree on what a dropped companion member reverts to: the {@code {TLSv1.3, TLSv1.2}} floor, and an unrestricted
+ * cipher list (an empty include list means "no restriction" in Jetty). Both are cleared/re-pinned unconditionally
+ * because the factory is long-lived and persists setter state across {@code reload()}. The provider and endpoint
+ * identification are per-consumer settings applied once at build, not part of this per-delivery reset.
+ */
+ private static void applyClientConfig(SslContextFactory.Client client) {
+ client.setIncludeProtocols(TlsContexts.DEFAULT_ENABLED_PROTOCOLS.toArray(new String[0]));
+ client.setIncludeCipherSuites();
+ }
+
+ private static void applyServerConfig(SslContextFactory.Server sslContextFactory, String sslProviderString,
+ boolean requireTrustedClientCertOnConnect, boolean allowInsecureConnection,
+ Set<String> ciphers, Set<String> protocols) {
+ if (ciphers != null && !ciphers.isEmpty()) {
+ sslContextFactory.setIncludeCipherSuites(ciphers.toArray(new String[0]));
+ } else {
+ // Clear the include list explicitly (not just rely on the fresh-factory default), for the same reason
+ // needClientAuth is reset below: this method is re-applied on each reload of a long-lived factory, so a
+ // prior companion delivery that pinned cipher suites must revert to the consumer default before a later
+ // companion (or its absence) is overlaid. An empty include list means "no restriction" in Jetty --
+ // SslContextFactory.processIncludeExcludePatterns falls back to the SSLContext's enabled suites.
+ sslContextFactory.setIncludeCipherSuites();
+ }
+ // Pin the enabled protocols even when unconfigured, matching the {TLSv1.3, TLSv1.2} floor the native
+ // Netty path applies rather than deferring to the provider default. A factory-supplied companion,
+ // applied afterwards by applyServerBaseline, still overrides this.
+ if (protocols != null && !protocols.isEmpty()) {
+ sslContextFactory.setIncludeProtocols(protocols.toArray(new String[0]));
+ } else {
+ sslContextFactory.setIncludeProtocols(TlsContexts.DEFAULT_ENABLED_PROTOCOLS.toArray(new String[0]));
+ }
+ if (StringUtils.isNotBlank(sslProviderString)) {
+ sslContextFactory.setProvider(sslProviderString);
+ }
+ if (requireTrustedClientCertOnConnect) {
+ sslContextFactory.setNeedClientAuth(true);
+ sslContextFactory.setTrustAll(false);
+ } else {
+ // PIP-478: optional client auth requests but does not require a client cert. An untrusted
+ // client cert is accepted at the handshake only when tlsAllowInsecureConnection=true, aligning the
+ // web listener with the Netty binary listener's semantics and diverging from the pre-5.0 Jetty
+ // path, which trusted any presented client cert whenever client auth was optional (see PIP-478
+ // Security Considerations).
+ //
+ // The actual enforcement is the trust managers baked into the SSLContext the framework hands to
+ // Jetty via setSslContext (built from the WEB TlsPolicy's allowInsecureConnection: CA-validating
+ // when secure, insecure-trust-all when insecure). Jetty's own setTrustAll only takes effect when
+ // Jetty builds the SSLContext itself, so it is inert on this setSslContext path; we still scope it
+ // to the insecure flag so the two never disagree (defence in depth) rather than leaving the
+ // inherited unconditional setTrustAll(true).
+ // Clear needClientAuth explicitly (not just rely on the fresh-factory default): this method is
+ // re-applied on each reload, so a prior companion delivery that set needClientAuth must be reset to
+ // the consumer default here before a later companion (or its absence) is overlaid.
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(true);
+ sslContextFactory.setTrustAll(allowInsecureConnection);
+ }
+ // https://jetty.org/docs/jetty/12.1/operations-guide/protocols/index.html#ssl-sni
+ // Set to false for backwards compatibility with Jetty 9.x
+ sslContextFactory.setSniRequired(false);
+ }
+
+ /**
+ * Ask the factory to supply a native Jetty {@code jettyClass} for {@code purpose} (one-shot). Jetty's
+ * {@link SslContextFactory.Server} and {@link SslContextFactory.Client} are well-known SPI classes, so a
+ * custom factory MAY build one directly; the default {@code FileBasedTlsFactory} returns
+ * {@link Optional#empty()}, in which case the caller synthesizes the factory from an {@code SSLContext}
+ * subscription. A supplied instance is the factory's own (unstarted, same-instance-per-purpose,
+ * factory-driven reload) — the caller returns it verbatim and keeps the {@link TlsHandle} for disposal.
+ * Resolved at factory-build time (off any event loop), mirroring {@link #resolveBaselineParameters}.
+ */
+ private static <T extends SslContextFactory> Optional<TlsHandle<T>> acquireNativeJettyFactory(
+ PulsarTlsFactory factory, TlsPurpose purpose, Class<T> jettyClass) {
+ return factory.createInstance(purpose, jettyClass).join();
+ }
+
+ /**
+ * Request the factory's optional {@code SSLParameters} companion for a purpose (one-shot) at factory-build
+ * time, joining off any event loop, and return the supplied instance or {@link Optional#empty()} when the
+ * factory supplies none. Rotation deliveries do NOT use this: they re-request the companion asynchronously
+ * inside {@link JettyReloadCoordinator} (never joined on the delivery thread) and unwrap it via
+ * {@link #extractBaseline}.
+ */
+ private static Optional<SSLParameters> resolveBaselineParameters(PulsarTlsFactory factory, TlsPurpose purpose) {
+ return Optional.ofNullable(extractBaseline(factory.createInstance(purpose, SSLParameters.class).join()));
+ }
+
+ /**
+ * Unwrap the factory's {@code SSLParameters} companion from its handle, disposing the handle afterwards (a
+ * companion carries no reference-counted state). Returns {@code null} when the factory supplied none
+ * ({@link Optional#empty()}). Used both by the build-time {@link #resolveBaselineParameters} and by the
+ * asynchronous per-rotation re-request in {@link JettyReloadCoordinator}.
+ */
+ private static SSLParameters extractBaseline(Optional<TlsHandle<SSLParameters>> handle) {
+ if (handle.isEmpty()) {
+ return null;
+ }
+ TlsHandle<SSLParameters> paramsHandle = handle.get();
+ try {
+ return paramsHandle.get();
+ } finally {
+ paramsHandle.dispose();
+ }
+ }
+
+ /**
+ * Overlay a factory-supplied engine baseline onto a synthesized server factory (PIP-478 merge order):
+ * enabled protocols/cipher suites when the companion sets them, and the companion's client-auth mode as
+ * authoritative (rule 4) — {@code needClientAuth} wins over {@code wantClientAuth}, neither means none.
+ */
+ private static void applyServerBaseline(SslContextFactory.Server sslContextFactory, SSLParameters baseline) {
+ if (baseline.getProtocols() != null) {
+ sslContextFactory.setIncludeProtocols(baseline.getProtocols());
+ }
+ if (baseline.getCipherSuites() != null) {
+ sslContextFactory.setIncludeCipherSuites(baseline.getCipherSuites());
+ }
+ if (baseline.getNeedClientAuth()) {
+ sslContextFactory.setNeedClientAuth(true);
+ } else if (baseline.getWantClientAuth()) {
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(true);
+ } else {
+ sslContextFactory.setNeedClientAuth(false);
+ sslContextFactory.setWantClientAuth(false);
+ }
+ }
+
+ /**
+ * Overlay a factory-supplied engine baseline onto a synthesized client factory: enabled protocols/cipher
+ * suites only (client-auth is a server concept; SNI/hostname verification remain per-connection).
+ */
+ private static void applyClientBaseline(SslContextFactory.Client client, SSLParameters baseline) {
+ if (baseline.getProtocols() != null) {
+ client.setIncludeProtocols(baseline.getProtocols());
+ }
+ if (baseline.getCipherSuites() != null) {
+ client.setIncludeCipherSuites(baseline.getCipherSuites());
+ }
+ }
+
+ /**
+ * Per-subscription reload coordinator for the synthesized Jetty paths. It ports the two ordering guarantees
+ * of {@code TlsContextAcquisition.SynthesizingSubscription} to Jetty's hot-reload API, which the naive
+ * "compose {@code createInstance(SSLParameters)} then {@code reload}" delivery lacked:
+ *
+ * <ul>
+ * <li><b>Generation guard.</b> Each delivery captures a strictly increasing generation (deliveries are
+ * serial per subscription, per the SPI contract). A rotation's companion re-request is composed
+ * asynchronously and may complete on an arbitrary thread and out of order, so its {@code reload(...)}
+ * is applied — under a lock — only while its generation is still the latest; a companion superseded
+ * by a newer rotation is dropped rather than pinning the listener to a stale context/baseline.</li>
+ * <li><b>Last-good baseline retention.</b> The last successfully-resolved companion is retained (seeded
+ * from the build-time baseline). A transient companion-fetch failure during rotation reloads with that
+ * last-good baseline rather than consumer defaults, so it cannot silently drop protocols/ciphers or
+ * (server side) client-auth. The retained baseline is updated only for a successfully-resolved,
+ * non-superseded companion, under the same lock.</li>
+ * </ul>
+ *
+ * <p>The companion is never joined on the delivery thread (the self-deadlock hazard described on the class
+ * javadoc); only the <em>first</em> delivery — which fires synchronously inside the subscribe call, before the
+ * built factory is even returned — sets the already-overlaid context directly, mirroring
+ * {@code SynthesizingSubscription}'s pre-fetched first delivery. Every later delivery is a rotation and
+ * re-requests the companion, <em>including one that arrives before the connector/client starts</em>; whether
+ * the factory is started only decides how the result is applied (Jetty's {@code reload(...)} once started, the
+ * same setters directly before), so a factory started after such a rotation starts with that rotation's
+ * material AND its companion policy rather than the stale build-time baseline.
+ */
+ private static final class JettyReloadCoordinator {
+
+ private final PulsarTlsFactory factory;
+ private final TlsPurpose purpose;
+ private final SslContextFactory target;
+ // Applies the rotated context + (nullable) companion baseline inside Jetty's reload lambda.
+ private final BiConsumer<SSLContext, SSLParameters> applyReload;
+ // Last successfully-resolved companion, seeded from the pre-fetched build-time baseline. Retained across
+ // a transient companion-fetch failure so a rotation cannot silently downgrade engine policy.
+ private volatile SSLParameters lastBaseline;
+ // One-shot: only the first (synchronous, pre-fetched) delivery reuses the build-time baseline; every
+ // later delivery is a rotation and re-requests the companion, started or not.
+ private final AtomicBoolean firstDelivery = new AtomicBoolean(true);
+ private final AtomicLong deliveryGeneration = new AtomicLong();
+ private long lastPublishedGeneration;
+ // A rotation's companion request is composed asynchronously, so its completion can land after the
+ // owner disposed the subscription (and, on the server path, after Jetty stopped the connector).
+ // Reloading a stopped/abandoned factory then would be a pointless mutation at best.
+ private final AtomicBoolean disposed = new AtomicBoolean();
+
+ JettyReloadCoordinator(PulsarTlsFactory factory, TlsPurpose purpose, SslContextFactory target,
+ SSLParameters initialBaseline, BiConsumer<SSLContext, SSLParameters> applyReload) {
+ this.factory = factory;
+ this.purpose = purpose;
+ this.target = target;
+ this.lastBaseline = initialBaseline;
+ this.applyReload = applyReload;
+ }
+
+ /**
+ * Wrap the backing subscription so disposing it also stops this coordinator. Synchronized on the same
+ * monitor as {@link #publish}, so dispose returns only once any in-flight publish has finished —
+ * setting the flag alone would still let a publisher that had already passed the check reload a
+ * factory its owner has torn down.
+ */
+ TlsHandle<SSLContext> bind(TlsHandle<SSLContext> subscription) {
+ return new TlsHandle<>() {
+ @Override
+ public SSLContext get() {
+ return subscription.get();
+ }
+
+ @Override
+ public void dispose() {
+ synchronized (JettyReloadCoordinator.this) {
+ disposed.set(true);
+ }
+ subscription.dispose();
+ }
+ };
+ }
+
+ // Serial per subscription (SPI contract), so each delivery gets a strictly increasing generation.
+ void onDelivery(SSLContext newContext) {
+ long generation = deliveryGeneration.incrementAndGet();
+ if (firstDelivery.compareAndSet(true, false)) {
+ // The first delivery fires synchronously inside the subscribe call, before the built factory is
+ // returned (let alone started): the build-time companion was already overlaid and seeds
+ // lastBaseline, so only the context is missing — set it directly, mirroring
+ // SynthesizingSubscription's pre-fetched first delivery.
+ target.setSslContext(newContext);
+ return;
+ }
+ // Rotation delivery. Re-request the companion so engine policy rotates WITH the material
+ // (pip-478.md:736), resolved ASYNCHRONOUSLY off this delivery thread and never joined here (the
+ // self-deadlock hazard). This runs for rotations delivered BEFORE start too — those must refresh the
+ // companion as well, otherwise the connector would start with the rotated context but the stale
+ // build-time baseline; only the mechanism used to apply the result differs (see publish). The
+ // generation guard in publish drops a superseded companion; the last-good baseline is maintained
+ // there, never here, so a superseded companion completing late cannot regress it.
+ factory.createInstance(purpose, SSLParameters.class).whenComplete((companion, err) ->
Review Comment:
For the **default** factory this whole design collapses to a synchronous call on the delivery thread, which I think undoes what the coordinator is built for.
`FileBasedTlsFactory.isSupported()` returns true only for `SslContext` and `SSLContext`, so `createInstance(purpose, SSLParameters.class)` returns an *already-completed* future (FileBasedTlsFactory.java:251) and this `whenComplete` runs inline on the calling thread. That thread is inside `RegisteredSource.deliverToSubscribers`, which is `synchronized`. So:
```
deliverToSubscribers (synchronized on RegisteredSource)
└─ Subscription.deliver → coordinator.onDelivery
└─ createInstance(purpose, SSLParameters.class) → completedFuture
└─ whenComplete runs INLINE
└─ publish(...) (synchronized on the coordinator)
└─ target.reload(...) → Jetty AutoLock + unload()/load()
(SSLContext rebuild, cipher/protocol re-selection)
```
The javadoc's guarantee — "never joined on the delivery thread" — holds literally: nothing calls `join()`. But the path that actually ships does the entire Jetty reload there anyway, so the asynchronous structure buys nothing for the default factory, while the callback contract stated on `deliverToSubscribers` ("a cheap non-blocking store") is broken by the framework's own first consumer. Every acquisition and every poll for that purpose is blocked for the duration of a Jetty `SSLContext` rebuild.
It also establishes a three-lock chain across a third-party lock — source monitor → coordinator monitor → Jetty's factory lock — implicitly rather than by design. I looked for the reverse order and did not find it, so I am not claiming a deadlock exists today; I am claiming the ordering is now load-bearing and undocumented.
Related to my comment on `FileBasedTlsFactory.java:597` — this is the concrete instance of it. Would dispatching `publish` to the factory's blocking executor (rather than relying on the companion future to be asynchronous, which for the default factory it never is) address both?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org