From da74fee8a1d2c3207da5b2c920ae057dd2594e47 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Thu, 3 Dec 2026 18:26:36 +0000 Subject: [PATCH 1/4] feat(gax-httpjson): add global Conscrypt opt-out and preferred TLS provider auto-detection Add a global opt-out for Conscrypt in HttpJsonConscryptUtils via the com.google.api.gax.httpjson.disableConscrypt system property or GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT environment variable (system property takes precedence), and automatically skip Conscrypt when the JVM's preferred SSLContext.TLS provider is neither SunJSSE nor Conscrypt. Also make HttpJsonConscryptUtils.getConscryptProvider() public (remaining @InternalApi) for downstream transport follow-ups and document the global opt-out and FIPS 140-3 configuration in docs/post_quantum_cryptography_guide.md. Fixes #15053 --- docs/post_quantum_cryptography_guide.md | 51 ++- .../gax/httpjson/HttpJsonConscryptUtils.java | 69 +++- .../httpjson/HttpJsonConscryptUtilsTest.java | 303 +++++++++++++++++- 3 files changed, 409 insertions(+), 14 deletions(-) diff --git a/docs/post_quantum_cryptography_guide.md b/docs/post_quantum_cryptography_guide.md index c8f2aa0fde57..43db73493f86 100644 --- a/docs/post_quantum_cryptography_guide.md +++ b/docs/post_quantum_cryptography_guide.md @@ -111,12 +111,14 @@ FINE: Selecting JDK with provider SunJSSE version ... Channels continue to operate normally with classical TLS, but post-quantum protection will be absent. ### 2.4 HTTP/JSON Fallback Behavior -- **Silent Fallback to Standard JDK TLS (`SunJSSE`)**: If Conscrypt native libraries fail to load (or are unavailable on the host platform), `gax-httpjson` catches the linkage error, logs a debug message at `Level.FINE`, and silently defaults to standard JDK TLS (`SunJSSE`): +- **Silent Fallback to Default JVM TLS**: If Conscrypt is unavailable, disabled, or skipped, `gax-httpjson` logs a debug message at `Level.FINE` and falls back to the JVM's default TLS provider: ```text FINE: Conscrypt native library unavailable. Falling back to default JDK TLS. ``` See [Section 3](#3-how-to-verify-pqc-negotiation) for instructions on enabling internal logging or tracing TLS handshakes to verify whether your application is using PQC. -- **Common Host Triggers**: +- **Common Host and Configuration Triggers**: + - **Non-Default Preferred TLS Provider (Auto-Detected)**: If the JVM's preferred `SSLContext.TLS` provider is neither `SunJSSE` nor `Conscrypt` (for example, `BCJSSE` in a Bouncy Castle FIPS configuration or `IBMJSSE2` on IBM JDK 8), `gax-httpjson` skips Conscrypt and uses the JVM's preferred provider instead. PQC over HTTP/JSON is off in this case unless Conscrypt is configured as the preferred provider. + - **Explicit Opt-Out Flag**: Setting `-Dcom.google.api.gax.httpjson.disableConscrypt=true` or `GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true` skips loading Conscrypt globally for HTTP/JSON transports (see [Section 4.2](#42-custom-httpjson-configurations) and [Section 4.3](#43-fips-140-3-environments)). - **Alpine Linux (`musl` libc)**: Precompiled Conscrypt binaries require `glibc`. On `musl`-based distributions (e.g., `alpine`), Conscrypt cannot load and falls back to classical TLS. Use a `glibc`-compatible base image (such as Debian, Ubuntu, or Wolfi) for PQC. - **Hardened Filesystems (`noexec /tmp`)**: If `/tmp` is mounted with `noexec` or is read-only, Conscrypt cannot load extracted native libraries. To enable PQC, specify an executable directory via `-Dorg.conscrypt.native.workdir=/path/to/executable/dir`. @@ -177,6 +179,12 @@ Logger.getLogger("com.google.api.gax.httpjson.HttpJsonConscryptUtils").setLevel( FINE: Conscrypt native library unavailable. Falling back to default JDK TLS. FINE: Conscrypt initialization failed with exception: java.lang.UnsatisfiedLinkError: ... ``` +- **When Conscrypt is disabled or skipped**: You will observe a `FINE` message naming the opt-out flag or the detected preferred TLS provider: + ```text + FINE: Conscrypt disabled via system property com.google.api.gax.httpjson.disableConscrypt. Using JVM default TLS provider. + FINE: Conscrypt disabled via environment variable GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT. Using JVM default TLS provider. + FINE: Skipping Conscrypt because preferred JVM TLS provider is BCJSSE. + ``` #### Method 2: JVM TLS Handshake Tracing (`-Djavax.net.debug`) To inspect the actual cryptographic parameters negotiated during the TLS 1.3 handshake with Google Cloud servers, start your Java application with the standard JSSE debug flag: @@ -295,7 +303,20 @@ try (SecretManagerServiceClient client = SecretManagerServiceClient.create(setti ### 4.2 Custom HTTP/JSON Configurations -#### Option 1: Forcing Classical-Only Key Exchange (Disabling PQC) +#### Option 1: Disabling Conscrypt Globally +To disable Conscrypt across all HTTP/JSON transports created by `gax-httpjson` and `google-cloud-core-http` (including handwritten clients, GAPIC REST channels, and mTLS transports) without changing application code, set either the JVM system property or environment variable before creating clients: + +```bash +# Via JVM system property (takes precedence if both are set) +java -Dcom.google.api.gax.httpjson.disableConscrypt=true -jar my-application.jar + +# Or via environment variable +GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true java -jar my-application.jar +``` + +When enabled, `gax-httpjson` skips loading Conscrypt and leaves TLS to the JVM's default configured security provider. Values are matched case-insensitively (`true` disables Conscrypt). Any other value (such as `false`) leaves the default auto-detection active, and setting the system property overrides the environment variable. + +#### Option 2: Forcing Classical-Only Key Exchange (Disabling PQC) If you need to use Conscrypt for high-performance TLS but want to explicitly disable post-quantum hybrid groups (see [Common Reasons to Disable PQC](#common-reasons-to-disable-pqc)): ```java @@ -332,8 +353,8 @@ try (SecretManagerServiceClient client = SecretManagerServiceClient.create(setti } ``` -#### Option 2: Bypassing Conscrypt to Use Standard JDK JSSE -If your deployment environment prohibits native JNI libraries or you prefer using the JVM's built-in cryptographic engine (`SunJSSE`): +#### Option 3: Bypassing Conscrypt Per Client to Use Standard JDK JSSE +If your deployment environment prohibits native JNI libraries or you prefer using the JVM's built-in cryptographic engine (`SunJSSE`) for a specific client: ```java // 1. Build a standard NetHttpTransport without Conscrypt configuration @@ -356,7 +377,7 @@ try (SecretManagerServiceClient client = SecretManagerServiceClient.create(setti } ``` -#### Option 3: Configuring a Third-Party Security Provider (e.g., Bouncy Castle) +#### Option 4: Configuring a Third-Party Security Provider (e.g., Bouncy Castle) If your enterprise utilizes an alternative cryptographic provider (such as Bouncy Castle), configure it directly on the `NetHttpTransport.Builder`: ```java @@ -391,6 +412,22 @@ try (SecretManagerServiceClient client = SecretManagerServiceClient.create(setti --- +### 4.3 FIPS 140-3 Environments + +In FIPS 140-3 deployments where all TLS connections must use the JVM's configured FIPS cryptographic provider, disable bundled BoringSSL engines on both transports: + +```bash +java \ + -Dcom.google.api.gax.httpjson.disableConscrypt=true \ + -Dio.grpc.netty.shaded.io.netty.handler.ssl.noOpenSsl=true \ + -jar my-application.jar +``` + +- **HTTP/JSON transport**: When a non-default provider such as `BCJSSE` (Bouncy Castle FIPS) is configured as the JVM's preferred `SSLContext.TLS` provider in `java.security`, `gax-httpjson` detects it automatically and skips Conscrypt. Environments such as RHEL FIPS mode keep `SunJSSE` as the preferred provider, so they are not auto-detected and require `-Dcom.google.api.gax.httpjson.disableConscrypt=true` (or `GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true`). Setting the flag explicitly is recommended in all FIPS deployments so Conscrypt is never loaded. +- **gRPC transport**: `-Dio.grpc.netty.shaded.io.netty.handler.ssl.noOpenSsl=true` disables Netty's shaded BoringSSL provider so gRPC falls back to the JVM's configured TLS provider. + +--- + ## 5. Environment & Runtime Considerations Because PQC negotiation relies on native BoringSSL C binaries (bundled in `grpc-netty-shaded` and `conscrypt-openjdk-uber`) loaded over JNI, compatibility depends on the underlying runtime environment. Most standard Linux (`glibc`), macOS, and Windows environments support native execution out of the box. @@ -409,7 +446,7 @@ We recommend using Google Cloud's `libraries-bom` (version `26.88.0+`), which ce The OpenJDK community is integrating standardized post-quantum algorithms directly into the Java platform: - **[JEP 496](https://openjdk.org/jeps/496) (ML-KEM)**: Introduces native implementations of NIST FIPS 203 (Module-Lattice-Based Key-Encapsulation Mechanism) into OpenJDK's standard security providers (`SunJSSE` and `SunJCE`), targeted for **JDK 27+**. -- **What this means for Google Cloud Java**: On JDK 27+, applications configuring standard JDK security providers (see **Option 2** in Section 4.1 and Section 4.2) will negotiate post-quantum TLS natively using `SunJSSE`, without requiring Conscrypt or JNI native shared libraries. +- **What this means for Google Cloud Java**: On JDK 27+, applications configuring standard JDK security providers (see **Option 2** in Section 4.1 and **Option 1** or **Option 3** in Section 4.2) will negotiate post-quantum TLS natively using `SunJSSE`, without requiring Conscrypt or JNI native shared libraries. --- diff --git a/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonConscryptUtils.java b/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonConscryptUtils.java index 722eabcdc9a4..92335d97b292 100644 --- a/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonConscryptUtils.java +++ b/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonConscryptUtils.java @@ -31,7 +31,9 @@ import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.core.InternalApi; +import com.google.common.annotations.VisibleForTesting; import java.security.Provider; +import java.security.Security; import java.util.logging.Level; import java.util.logging.Logger; import org.conscrypt.Conscrypt; @@ -42,6 +44,11 @@ public class HttpJsonConscryptUtils { private static final Logger LOG = Logger.getLogger(HttpJsonConscryptUtils.class.getName()); + static final String DISABLE_CONSCRYPT_PROPERTY = "com.google.api.gax.httpjson.disableConscrypt"; + static final String DISABLE_CONSCRYPT_ENV = "GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT"; + private static final String SUN_JSSE_PROVIDER_NAME = "SunJSSE"; + private static final String CONSCRYPT_PROVIDER_NAME = "Conscrypt"; + /** * Default TLS 1.3 named groups configured when Conscrypt security provider is present, organized * in client preference order: @@ -89,15 +96,17 @@ private static Provider createProvider() { /** * Configures the given {@link NetHttpTransport.Builder} with Conscrypt as the security provider - * by default if Conscrypt is available. Users can customize the {@link NetHttpTransport.Builder} - * to use a different security provider. + * by default when Conscrypt is enabled and available. Skips Conscrypt and leaves the builder + * unchanged if disabled via {@code -Dcom.google.api.gax.httpjson.disableConscrypt=true} or {@code + * GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true}, if the JVM's preferred TLS provider is neither {@code + * SunJSSE} nor {@code Conscrypt}, or if Conscrypt is unavailable. * * @param builder the {@link NetHttpTransport.Builder} to configure * @return the configured {@link NetHttpTransport.Builder} */ public static NetHttpTransport.Builder configureConscryptSecurityProvider( NetHttpTransport.Builder builder) { - Provider conscryptProvider = ConscryptProviderHolder.INSTANCE; + Provider conscryptProvider = getConscryptProvider(); if (conscryptProvider == null) { return builder; } @@ -125,13 +134,61 @@ public static NetHttpTransport.Builder configureConscryptSecurityProvider( } /** - * Returns the Conscrypt {@link Provider} instance, or {@code null} if Conscrypt is unavailable. + * Returns the Conscrypt {@link Provider} instance, or {@code null} if Conscrypt is disabled, + * skipped because a non-default JVM TLS provider is preferred, or unavailable. * - * @return the Conscrypt provider or null + * @return the Conscrypt provider or {@code null} */ - static Provider getConscryptProvider() { + public static Provider getConscryptProvider() { + if (!shouldUseConscrypt( + System.getProperty(DISABLE_CONSCRYPT_PROPERTY), + System.getenv(DISABLE_CONSCRYPT_ENV), + getPreferredTlsProviderName())) { + return null; + } return ConscryptProviderHolder.INSTANCE; } + @VisibleForTesting + static boolean shouldUseConscrypt( + String disableProperty, String disableEnv, String preferredTlsProvider) { + if (disableProperty != null && !disableProperty.isEmpty()) { + if ("true".equalsIgnoreCase(disableProperty)) { + LOG.log( + Level.FINE, + "Conscrypt disabled via system property {0}. Using JVM default TLS provider.", + DISABLE_CONSCRYPT_PROPERTY); + return false; + } + } else if ("true".equalsIgnoreCase(disableEnv)) { + LOG.log( + Level.FINE, + "Conscrypt disabled via environment variable {0}. Using JVM default TLS provider.", + DISABLE_CONSCRYPT_ENV); + return false; + } + + if (!SUN_JSSE_PROVIDER_NAME.equals(preferredTlsProvider) + && !CONSCRYPT_PROVIDER_NAME.equals(preferredTlsProvider)) { + LOG.log( + Level.FINE, + preferredTlsProvider == null + ? "Skipping Conscrypt because no preferred JVM TLS provider was found." + : "Skipping Conscrypt because preferred JVM TLS provider is {0}.", + preferredTlsProvider); + return false; + } + + return true; + } + + private static String getPreferredTlsProviderName() { + Provider[] providers = Security.getProviders("SSLContext.TLS"); + if (providers == null || providers.length == 0) { + return null; + } + return providers[0].getName(); + } + private HttpJsonConscryptUtils() {} } diff --git a/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonConscryptUtilsTest.java b/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonConscryptUtilsTest.java index cea5cae38512..bb38a050d878 100644 --- a/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonConscryptUtilsTest.java +++ b/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonConscryptUtilsTest.java @@ -31,8 +31,31 @@ import static com.google.common.truth.Truth.assertThat; +import com.google.api.client.http.GenericUrl; import com.google.api.client.http.javanet.NetHttpTransport; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.net.Socket; +import java.net.URL; import java.security.Provider; +import java.security.Security; +import java.security.cert.Certificate; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import org.conscrypt.Conscrypt; import org.junit.jupiter.api.Test; class HttpJsonConscryptUtilsTest { @@ -46,11 +69,21 @@ void testGetConscryptProvider_doesNotThrow() { } @Test - void testConfigureConscryptSecurityProvider() { + void testConfigureConscryptSecurityProvider() throws Exception { NetHttpTransport.Builder builder = new NetHttpTransport.Builder(); NetHttpTransport.Builder configured = HttpJsonConscryptUtils.configureConscryptSecurityProvider(builder); assertThat(configured).isSameInstanceAs(builder); + + Provider provider = HttpJsonConscryptUtils.getConscryptProvider(); + if (provider != null) { + SSLSocketFactory captured = captureConfiguredSslSocketFactory(); + assertThat(captured).isNotNull(); + try (Socket socket = captured.createSocket()) { + assertThat(socket).isInstanceOf(SSLSocket.class); + assertThat(Conscrypt.isConscrypt((SSLSocket) socket)).isTrue(); + } + } } @Test @@ -60,4 +93,272 @@ void testDefaultConscryptNamedGroups_containsExpectedGroups() { .containsExactly("X25519MLKEM768", "MLKEM1024", "X25519", "secp256r1", "secp384r1") .inOrder(); } + + @Test + void testShouldUseConscrypt_unsetFlagUsesAutoDetect() { + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "SunJSSE")).isTrue(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "Conscrypt")).isTrue(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "BCJSSE")).isFalse(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "IBMJSSE2")).isFalse(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, null)).isFalse(); + } + + @Test + void testShouldUseConscrypt_systemPropertyDisablesCaseInsensitively() { + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("true", null, "SunJSSE")).isFalse(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("TRUE", null, "SunJSSE")).isFalse(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("True", "false", "Conscrypt")).isFalse(); + } + + @Test + void testShouldUseConscrypt_envVarDisablesWhenPropertyUnsetOrEmpty() { + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "true", "SunJSSE")).isFalse(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "TRUE", "Conscrypt")).isFalse(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("", "true", "SunJSSE")).isFalse(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "false", "SunJSSE")).isTrue(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "invalid", "SunJSSE")).isTrue(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "", "SunJSSE")).isTrue(); + } + + @Test + void testShouldUseConscrypt_systemPropertyTakesPrecedenceOverEnvVar() { + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("false", "true", "SunJSSE")).isTrue(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("invalid", "true", "SunJSSE")).isTrue(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("false", "true", "BCJSSE")).isFalse(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("false", null, "BCJSSE")).isFalse(); + } + + @Test + void testGetConscryptProvider_disabledBySystemProperty_returnsNullAndSkipsTransportConfig() + throws Exception { + String previous = System.getProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY); + System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "true"); + try { + assertThat(HttpJsonConscryptUtils.getConscryptProvider()).isNull(); + assertThat(captureConfiguredSslSocketFactory()).isNull(); + } finally { + restoreProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, previous); + } + } + + @Test + void testGetConscryptProvider_skippedWhenCustomTlsProviderPreferred() throws Exception { + Provider customProvider = createTestTlsProvider("TestFipsJSSE"); + Security.insertProviderAt(customProvider, 1); + try { + assertThat(HttpJsonConscryptUtils.getConscryptProvider()).isNull(); + assertThat(captureConfiguredSslSocketFactory()).isNull(); + } finally { + Security.removeProvider(customProvider.getName()); + } + } + + @Test + void testDisabledBySystemProperty_doesNotLoadConscryptClasses() throws Exception { + String previous = System.getProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY); + System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "true"); + try { + assertConscryptNotLoadedInIsolatedClassLoader(); + } finally { + restoreProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, previous); + } + } + + @Test + void testCustomTlsProviderPreferred_doesNotLoadConscryptClasses() throws Exception { + Provider customProvider = createTestTlsProvider("TestFipsJSSE"); + Security.insertProviderAt(customProvider, 1); + try { + assertConscryptNotLoadedInIsolatedClassLoader(); + } finally { + Security.removeProvider(customProvider.getName()); + } + } + + @Test + void testShouldUseConscrypt_logsReasonAtFineLevel() { + Logger logger = Logger.getLogger(HttpJsonConscryptUtils.class.getName()); + Level previousLevel = logger.getLevel(); + List messages = new ArrayList<>(); + Handler handler = + new Handler() { + @Override + public void publish(LogRecord record) { + if (record.getLevel().equals(Level.FINE)) { + String message = record.getMessage(); + if (record.getParameters() != null && record.getParameters().length > 0) { + message = MessageFormat.format(message, record.getParameters()); + } + messages.add(message); + } + } + + @Override + public void flush() {} + + @Override + public void close() {} + }; + logger.setLevel(Level.FINE); + logger.addHandler(handler); + try { + HttpJsonConscryptUtils.shouldUseConscrypt("true", null, "SunJSSE"); + HttpJsonConscryptUtils.shouldUseConscrypt(null, "true", "SunJSSE"); + HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "BCJSSE"); + HttpJsonConscryptUtils.shouldUseConscrypt(null, null, null); + } finally { + logger.removeHandler(handler); + logger.setLevel(previousLevel); + } + + assertThat(messages).hasSize(4); + assertThat(messages.get(0)).contains(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY); + assertThat(messages.get(1)).contains(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_ENV); + assertThat(messages.get(2)).contains("BCJSSE"); + assertThat(messages.get(3)).contains("no preferred JVM TLS provider"); + } + + private static SSLSocketFactory captureConfiguredSslSocketFactory() throws IOException { + CapturingHttpsURLConnection connection = + new CapturingHttpsURLConnection(new URL("https://example.com")); + NetHttpTransport transport = + HttpJsonConscryptUtils.configureConscryptSecurityProvider( + new NetHttpTransport.Builder().setConnectionFactory(url -> connection)) + .build(); + transport + .createRequestFactory() + .buildGetRequest(new GenericUrl("https://example.com")) + .execute(); + return connection.configuredSslSocketFactory; + } + + private static final class CapturingHttpsURLConnection extends HttpsURLConnection { + SSLSocketFactory configuredSslSocketFactory; + + CapturingHttpsURLConnection(URL url) { + super(url); + } + + @Override + public void setSSLSocketFactory(SSLSocketFactory sf) { + this.configuredSslSocketFactory = sf; + } + + @Override + public int getResponseCode() { + return 200; + } + + @Override + public Map> getHeaderFields() { + return Collections.emptyMap(); + } + + @Override + public InputStream getInputStream() { + return new ByteArrayInputStream(new byte[0]); + } + + @Override + public String getCipherSuite() { + return ""; + } + + @Override + public Certificate[] getLocalCertificates() { + return null; + } + + @Override + public Certificate[] getServerCertificates() { + return null; + } + + @Override + public void disconnect() {} + + @Override + public boolean usingProxy() { + return false; + } + + @Override + public void connect() {} + } + + private static void assertConscryptNotLoadedInIsolatedClassLoader() throws Exception { + ClassLoader loader = + new ConscryptBlockingClassLoader(HttpJsonConscryptUtils.class.getClassLoader()); + Class utilsClass = loader.loadClass(HttpJsonConscryptUtils.class.getName()); + Method getProvider = utilsClass.getMethod("getConscryptProvider"); + assertThat(getProvider.invoke(null)).isNull(); + + NetHttpTransport.Builder builder = new NetHttpTransport.Builder(); + Method configure = + utilsClass.getMethod("configureConscryptSecurityProvider", NetHttpTransport.Builder.class); + Object result = configure.invoke(null, builder); + assertThat(result).isSameInstanceAs(builder); + assertThat(builder.build()).isNotNull(); + } + + @SuppressWarnings("deprecation") + private static Provider createTestTlsProvider(String name) { + return new Provider(name, 1.0, "Test TLS provider") { + { + put("SSLContext.TLS", "com.example.UnusedSslContextSpi"); + } + }; + } + + private static void restoreProperty(String key, String previousValue) { + if (previousValue == null) { + System.clearProperty(key); + } else { + System.setProperty(key, previousValue); + } + } + + private static final class ConscryptBlockingClassLoader extends ClassLoader { + ConscryptBlockingClassLoader(ClassLoader parent) { + super(parent); + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (name.startsWith("org.conscrypt.")) { + throw new AssertionError("Unexpected load of Conscrypt class: " + name); + } + if (name.equals(HttpJsonConscryptUtils.class.getName()) + || name.startsWith(HttpJsonConscryptUtils.class.getName() + "$")) { + Class loaded = findLoadedClass(name); + if (loaded == null) { + loaded = defineFromParentResource(name); + } + if (resolve) { + resolveClass(loaded); + } + return loaded; + } + return super.loadClass(name, resolve); + } + + private Class defineFromParentResource(String name) throws ClassNotFoundException { + String resource = name.replace('.', '/') + ".class"; + try (InputStream in = getParent().getResourceAsStream(resource)) { + if (in == null) { + throw new ClassNotFoundException(name); + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int bytesRead; + while ((bytesRead = in.read(buffer)) != -1) { + out.write(buffer, 0, bytesRead); + } + byte[] bytes = out.toByteArray(); + return defineClass(name, bytes, 0, bytes.length); + } catch (IOException e) { + throw new ClassNotFoundException(name, e); + } + } + } } From 7b5e25659efc52583d71286d69cb063548154c04 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Thu, 3 Dec 2026 18:42:12 +0000 Subject: [PATCH 2/4] fix(gax-httpjson): handle SecurityException when reading Conscrypt opt-out config --- .../gax/httpjson/HttpJsonConscryptUtils.java | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonConscryptUtils.java b/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonConscryptUtils.java index 92335d97b292..0636d15fd4b4 100644 --- a/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonConscryptUtils.java +++ b/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonConscryptUtils.java @@ -141,8 +141,8 @@ public static NetHttpTransport.Builder configureConscryptSecurityProvider( */ public static Provider getConscryptProvider() { if (!shouldUseConscrypt( - System.getProperty(DISABLE_CONSCRYPT_PROPERTY), - System.getenv(DISABLE_CONSCRYPT_ENV), + getSystemProperty(DISABLE_CONSCRYPT_PROPERTY), + getEnv(DISABLE_CONSCRYPT_ENV), getPreferredTlsProviderName())) { return null; } @@ -182,6 +182,24 @@ static boolean shouldUseConscrypt( return true; } + private static String getSystemProperty(String name) { + try { + return System.getProperty(name); + } catch (SecurityException e) { + LOG.log(Level.FINE, "SecurityException reading system property " + name, e); + return null; + } + } + + private static String getEnv(String name) { + try { + return System.getenv(name); + } catch (SecurityException e) { + LOG.log(Level.FINE, "SecurityException reading environment variable " + name, e); + return null; + } + } + private static String getPreferredTlsProviderName() { Provider[] providers = Security.getProviders("SSLContext.TLS"); if (providers == null || providers.length == 0) { From 1af0feff97d2140565151dc3b0d20ef014097e3b Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Thu, 3 Dec 2026 18:58:39 +0000 Subject: [PATCH 3/4] chore(gax-httpjson): clarify PQC guide and streamline Conscrypt opt-out tests --- docs/post_quantum_cryptography_guide.md | 12 +- .../httpjson/HttpJsonConscryptUtilsTest.java | 300 ++++++------------ 2 files changed, 112 insertions(+), 200 deletions(-) diff --git a/docs/post_quantum_cryptography_guide.md b/docs/post_quantum_cryptography_guide.md index 43db73493f86..8fd1bcdedc1f 100644 --- a/docs/post_quantum_cryptography_guide.md +++ b/docs/post_quantum_cryptography_guide.md @@ -115,10 +115,12 @@ Channels continue to operate normally with classical TLS, but post-quantum prote ```text FINE: Conscrypt native library unavailable. Falling back to default JDK TLS. ``` + On a standard JDK, this is the built-in `SunJSSE` provider. If another JSSE provider (such as `BCJSSE`) is configured ahead of `SunJSSE` in the JVM's security provider list, the JVM uses that provider instead. To check which provider your JVM selects for TLS, inspect the `security.provider.` order in `$JAVA_HOME/conf/security/java.security` (or `$JAVA_HOME/jre/lib/security/java.security` on JDK 8, plus any file passed via `-Djava.security.properties`), or check at runtime with `Security.getProviders("SSLContext.TLS")[0].getName()`. + See [Section 3](#3-how-to-verify-pqc-negotiation) for instructions on enabling internal logging or tracing TLS handshakes to verify whether your application is using PQC. - **Common Host and Configuration Triggers**: - - **Non-Default Preferred TLS Provider (Auto-Detected)**: If the JVM's preferred `SSLContext.TLS` provider is neither `SunJSSE` nor `Conscrypt` (for example, `BCJSSE` in a Bouncy Castle FIPS configuration or `IBMJSSE2` on IBM JDK 8), `gax-httpjson` skips Conscrypt and uses the JVM's preferred provider instead. PQC over HTTP/JSON is off in this case unless Conscrypt is configured as the preferred provider. - - **Explicit Opt-Out Flag**: Setting `-Dcom.google.api.gax.httpjson.disableConscrypt=true` or `GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true` skips loading Conscrypt globally for HTTP/JSON transports (see [Section 4.2](#42-custom-httpjson-configurations) and [Section 4.3](#43-fips-140-3-environments)). + - **Non-Default Preferred TLS Provider (Auto-Detected)**: If the JVM's preferred `SSLContext.TLS` provider is neither `SunJSSE` nor `Conscrypt` (for example, `BCJSSE` or `IBMJSSE2` on IBM JDK 8), `gax-httpjson` skips Conscrypt and uses the JVM's preferred provider instead. PQC over HTTP/JSON is off in this case unless Conscrypt is configured as the preferred provider. + - **Explicit Opt-Out Flag**: Setting `-Dcom.google.api.gax.httpjson.disableConscrypt=true` or `GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true` skips loading Conscrypt globally for HTTP/JSON transports (see [Section 4.2](#42-custom-httpjson-configurations) and [Section 4.3](#43-controlling-the-jvm-security-provider-across-both-transports)). - **Alpine Linux (`musl` libc)**: Precompiled Conscrypt binaries require `glibc`. On `musl`-based distributions (e.g., `alpine`), Conscrypt cannot load and falls back to classical TLS. Use a `glibc`-compatible base image (such as Debian, Ubuntu, or Wolfi) for PQC. - **Hardened Filesystems (`noexec /tmp`)**: If `/tmp` is mounted with `noexec` or is read-only, Conscrypt cannot load extracted native libraries. To enable PQC, specify an executable directory via `-Dorg.conscrypt.native.workdir=/path/to/executable/dir`. @@ -412,9 +414,9 @@ try (SecretManagerServiceClient client = SecretManagerServiceClient.create(setti --- -### 4.3 FIPS 140-3 Environments +### 4.3 Controlling the JVM Security Provider Across Both Transports -In FIPS 140-3 deployments where all TLS connections must use the JVM's configured FIPS cryptographic provider, disable bundled BoringSSL engines on both transports: +If you want all Google Cloud client TLS connections to use the JVM's configured `java.security` provider instead of bundled BoringSSL engines (for example, to enforce a specific JCA provider or meet compliance requirements such as FIPS), disable native BoringSSL on both transports: ```bash java \ @@ -423,7 +425,7 @@ java \ -jar my-application.jar ``` -- **HTTP/JSON transport**: When a non-default provider such as `BCJSSE` (Bouncy Castle FIPS) is configured as the JVM's preferred `SSLContext.TLS` provider in `java.security`, `gax-httpjson` detects it automatically and skips Conscrypt. Environments such as RHEL FIPS mode keep `SunJSSE` as the preferred provider, so they are not auto-detected and require `-Dcom.google.api.gax.httpjson.disableConscrypt=true` (or `GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true`). Setting the flag explicitly is recommended in all FIPS deployments so Conscrypt is never loaded. +- **HTTP/JSON transport**: When a non-default provider (such as `BCJSSE`) is configured as the JVM's preferred `SSLContext.TLS` provider in `java.security`, `gax-httpjson` detects it automatically and skips Conscrypt. Set `-Dcom.google.api.gax.httpjson.disableConscrypt=true` (or `GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true`) whenever you want to guarantee Conscrypt is never loaded, including in environments where `SunJSSE` remains the preferred provider (such as RHEL FIPS mode). - **gRPC transport**: `-Dio.grpc.netty.shaded.io.netty.handler.ssl.noOpenSsl=true` disables Netty's shaded BoringSSL provider so gRPC falls back to the JVM's configured TLS provider. --- diff --git a/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonConscryptUtilsTest.java b/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonConscryptUtilsTest.java index bb38a050d878..3ef204c61e36 100644 --- a/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonConscryptUtilsTest.java +++ b/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonConscryptUtilsTest.java @@ -30,36 +30,52 @@ package com.google.api.gax.httpjson; import static com.google.common.truth.Truth.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.javanet.NetHttpTransport; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; +import com.google.common.io.ByteStreams; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.Socket; -import java.net.URL; import java.security.Provider; import java.security.Security; -import java.security.cert.Certificate; -import java.text.MessageFormat; -import java.util.ArrayList; import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.Logger; +import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import org.conscrypt.Conscrypt; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class HttpJsonConscryptUtilsTest { + private static final String TEST_TLS_PROVIDER_NAME = "TestCustomJSSE"; + + private String previousDisableProperty; + + @BeforeEach + void setUp() { + previousDisableProperty = System.getProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY); + } + + @AfterEach + void tearDown() { + if (previousDisableProperty == null) { + System.clearProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY); + } else { + System.setProperty( + HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, previousDisableProperty); + } + Security.removeProvider(TEST_TLS_PROVIDER_NAME); + } + @Test void testGetConscryptProvider_doesNotThrow() { Provider provider = HttpJsonConscryptUtils.getConscryptProvider(); @@ -69,20 +85,23 @@ void testGetConscryptProvider_doesNotThrow() { } @Test - void testConfigureConscryptSecurityProvider() throws Exception { + void testConfigureConscryptSecurityProvider_returnsSameBuilder() { NetHttpTransport.Builder builder = new NetHttpTransport.Builder(); NetHttpTransport.Builder configured = HttpJsonConscryptUtils.configureConscryptSecurityProvider(builder); assertThat(configured).isSameInstanceAs(builder); + } - Provider provider = HttpJsonConscryptUtils.getConscryptProvider(); - if (provider != null) { - SSLSocketFactory captured = captureConfiguredSslSocketFactory(); - assertThat(captured).isNotNull(); - try (Socket socket = captured.createSocket()) { - assertThat(socket).isInstanceOf(SSLSocket.class); - assertThat(Conscrypt.isConscrypt((SSLSocket) socket)).isTrue(); - } + @Test + void testConfigureConscryptSecurityProvider_usesConscryptWhenAvailable() throws Exception { + if (HttpJsonConscryptUtils.getConscryptProvider() == null) { + return; + } + SSLSocketFactory captured = captureConfiguredSslSocketFactory(); + assertThat(captured).isNotNull(); + try (Socket socket = captured.createSocket()) { + assertThat(socket).isInstanceOf(SSLSocket.class); + assertThat(Conscrypt.isConscrypt((SSLSocket) socket)).isTrue(); } } @@ -95,132 +114,106 @@ void testDefaultConscryptNamedGroups_containsExpectedGroups() { } @Test - void testShouldUseConscrypt_unsetFlagUsesAutoDetect() { + void testShouldUseConscrypt_allowsSunJsseWhenUnset() { assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "SunJSSE")).isTrue(); + } + + @Test + void testShouldUseConscrypt_allowsConscryptWhenUnset() { assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "Conscrypt")).isTrue(); + } + + @Test + void testShouldUseConscrypt_skipsNonDefaultTlsProvider() { assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "BCJSSE")).isFalse(); assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "IBMJSSE2")).isFalse(); + } + + @Test + void testShouldUseConscrypt_skipsWhenNoTlsProviderFound() { assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, null)).isFalse(); } @Test - void testShouldUseConscrypt_systemPropertyDisablesCaseInsensitively() { + void testShouldUseConscrypt_disabledBySystemProperty() { assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("true", null, "SunJSSE")).isFalse(); - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("TRUE", null, "SunJSSE")).isFalse(); - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("True", "false", "Conscrypt")).isFalse(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("TRUE", "false", "Conscrypt")).isFalse(); } @Test - void testShouldUseConscrypt_envVarDisablesWhenPropertyUnsetOrEmpty() { + void testShouldUseConscrypt_disabledByEnvVarWhenPropertyUnsetOrEmpty() { assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "true", "SunJSSE")).isFalse(); - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "TRUE", "Conscrypt")).isFalse(); - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("", "true", "SunJSSE")).isFalse(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("", "TRUE", "Conscrypt")).isFalse(); + } + + @Test + void testShouldUseConscrypt_ignoresNonTrueEnvVarValues() { assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "false", "SunJSSE")).isTrue(); assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "invalid", "SunJSSE")).isTrue(); assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "", "SunJSSE")).isTrue(); } @Test - void testShouldUseConscrypt_systemPropertyTakesPrecedenceOverEnvVar() { + void testShouldUseConscrypt_systemPropertyOverridesEnvVar() { assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("false", "true", "SunJSSE")).isTrue(); assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("invalid", "true", "SunJSSE")).isTrue(); - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("false", "true", "BCJSSE")).isFalse(); - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("false", null, "BCJSSE")).isFalse(); } @Test - void testGetConscryptProvider_disabledBySystemProperty_returnsNullAndSkipsTransportConfig() - throws Exception { - String previous = System.getProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY); - System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "true"); - try { - assertThat(HttpJsonConscryptUtils.getConscryptProvider()).isNull(); - assertThat(captureConfiguredSslSocketFactory()).isNull(); - } finally { - restoreProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, previous); - } + void testShouldUseConscrypt_falseSystemPropertyStillRespectsAutoDetect() { + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("false", null, "BCJSSE")).isFalse(); + assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("false", "true", "BCJSSE")).isFalse(); } @Test - void testGetConscryptProvider_skippedWhenCustomTlsProviderPreferred() throws Exception { - Provider customProvider = createTestTlsProvider("TestFipsJSSE"); - Security.insertProviderAt(customProvider, 1); - try { - assertThat(HttpJsonConscryptUtils.getConscryptProvider()).isNull(); - assertThat(captureConfiguredSslSocketFactory()).isNull(); - } finally { - Security.removeProvider(customProvider.getName()); - } + void testGetConscryptProvider_disabledBySystemProperty_returnsNull() { + System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "true"); + assertThat(HttpJsonConscryptUtils.getConscryptProvider()).isNull(); } @Test - void testDisabledBySystemProperty_doesNotLoadConscryptClasses() throws Exception { - String previous = System.getProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY); + void testConfigureConscryptSecurityProvider_disabledBySystemProperty_skipsConscrypt() + throws Exception { System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "true"); - try { - assertConscryptNotLoadedInIsolatedClassLoader(); - } finally { - restoreProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, previous); - } + assertThat(captureConfiguredSslSocketFactory()).isNull(); } @Test - void testCustomTlsProviderPreferred_doesNotLoadConscryptClasses() throws Exception { - Provider customProvider = createTestTlsProvider("TestFipsJSSE"); - Security.insertProviderAt(customProvider, 1); - try { - assertConscryptNotLoadedInIsolatedClassLoader(); - } finally { - Security.removeProvider(customProvider.getName()); - } + void testGetConscryptProvider_customTlsProviderPreferred_returnsNull() { + Security.insertProviderAt(createTestTlsProvider(), 1); + assertThat(HttpJsonConscryptUtils.getConscryptProvider()).isNull(); } @Test - void testShouldUseConscrypt_logsReasonAtFineLevel() { - Logger logger = Logger.getLogger(HttpJsonConscryptUtils.class.getName()); - Level previousLevel = logger.getLevel(); - List messages = new ArrayList<>(); - Handler handler = - new Handler() { - @Override - public void publish(LogRecord record) { - if (record.getLevel().equals(Level.FINE)) { - String message = record.getMessage(); - if (record.getParameters() != null && record.getParameters().length > 0) { - message = MessageFormat.format(message, record.getParameters()); - } - messages.add(message); - } - } - - @Override - public void flush() {} - - @Override - public void close() {} - }; - logger.setLevel(Level.FINE); - logger.addHandler(handler); - try { - HttpJsonConscryptUtils.shouldUseConscrypt("true", null, "SunJSSE"); - HttpJsonConscryptUtils.shouldUseConscrypt(null, "true", "SunJSSE"); - HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "BCJSSE"); - HttpJsonConscryptUtils.shouldUseConscrypt(null, null, null); - } finally { - logger.removeHandler(handler); - logger.setLevel(previousLevel); - } + void testConfigureConscryptSecurityProvider_customTlsProviderPreferred_skipsConscrypt() + throws Exception { + Security.insertProviderAt(createTestTlsProvider(), 1); + assertThat(captureConfiguredSslSocketFactory()).isNull(); + } - assertThat(messages).hasSize(4); - assertThat(messages.get(0)).contains(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY); - assertThat(messages.get(1)).contains(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_ENV); - assertThat(messages.get(2)).contains("BCJSSE"); - assertThat(messages.get(3)).contains("no preferred JVM TLS provider"); + @Test + void testGetConscryptProvider_disabledBySystemProperty_doesNotLoadConscrypt() throws Exception { + System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "true"); + ClassLoader loader = + new ConscryptBlockingClassLoader(HttpJsonConscryptUtils.class.getClassLoader()); + Class utilsClass = loader.loadClass(HttpJsonConscryptUtils.class.getName()); + Method getProvider = utilsClass.getMethod("getConscryptProvider"); + assertThat(getProvider.invoke(null)).isNull(); } private static SSLSocketFactory captureConfiguredSslSocketFactory() throws IOException { - CapturingHttpsURLConnection connection = - new CapturingHttpsURLConnection(new URL("https://example.com")); + AtomicReference captured = new AtomicReference<>(); + HttpsURLConnection connection = mock(HttpsURLConnection.class); + doAnswer( + invocation -> { + captured.set(invocation.getArgument(0)); + return null; + }) + .when(connection) + .setSSLSocketFactory(any(SSLSocketFactory.class)); + when(connection.getResponseCode()).thenReturn(200); + when(connection.getHeaderFields()).thenReturn(Collections.emptyMap()); + NetHttpTransport transport = HttpJsonConscryptUtils.configureConscryptSecurityProvider( new NetHttpTransport.Builder().setConnectionFactory(url -> connection)) @@ -229,95 +222,18 @@ private static SSLSocketFactory captureConfiguredSslSocketFactory() throws IOExc .createRequestFactory() .buildGetRequest(new GenericUrl("https://example.com")) .execute(); - return connection.configuredSslSocketFactory; - } - - private static final class CapturingHttpsURLConnection extends HttpsURLConnection { - SSLSocketFactory configuredSslSocketFactory; - - CapturingHttpsURLConnection(URL url) { - super(url); - } - - @Override - public void setSSLSocketFactory(SSLSocketFactory sf) { - this.configuredSslSocketFactory = sf; - } - - @Override - public int getResponseCode() { - return 200; - } - - @Override - public Map> getHeaderFields() { - return Collections.emptyMap(); - } - - @Override - public InputStream getInputStream() { - return new ByteArrayInputStream(new byte[0]); - } - - @Override - public String getCipherSuite() { - return ""; - } - - @Override - public Certificate[] getLocalCertificates() { - return null; - } - - @Override - public Certificate[] getServerCertificates() { - return null; - } - - @Override - public void disconnect() {} - - @Override - public boolean usingProxy() { - return false; - } - - @Override - public void connect() {} - } - - private static void assertConscryptNotLoadedInIsolatedClassLoader() throws Exception { - ClassLoader loader = - new ConscryptBlockingClassLoader(HttpJsonConscryptUtils.class.getClassLoader()); - Class utilsClass = loader.loadClass(HttpJsonConscryptUtils.class.getName()); - Method getProvider = utilsClass.getMethod("getConscryptProvider"); - assertThat(getProvider.invoke(null)).isNull(); - - NetHttpTransport.Builder builder = new NetHttpTransport.Builder(); - Method configure = - utilsClass.getMethod("configureConscryptSecurityProvider", NetHttpTransport.Builder.class); - Object result = configure.invoke(null, builder); - assertThat(result).isSameInstanceAs(builder); - assertThat(builder.build()).isNotNull(); + return captured.get(); } @SuppressWarnings("deprecation") - private static Provider createTestTlsProvider(String name) { - return new Provider(name, 1.0, "Test TLS provider") { + private static Provider createTestTlsProvider() { + return new Provider(TEST_TLS_PROVIDER_NAME, 1.0, "Test TLS provider") { { put("SSLContext.TLS", "com.example.UnusedSslContextSpi"); } }; } - private static void restoreProperty(String key, String previousValue) { - if (previousValue == null) { - System.clearProperty(key); - } else { - System.setProperty(key, previousValue); - } - } - private static final class ConscryptBlockingClassLoader extends ClassLoader { ConscryptBlockingClassLoader(ClassLoader parent) { super(parent); @@ -332,7 +248,7 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE || name.startsWith(HttpJsonConscryptUtils.class.getName() + "$")) { Class loaded = findLoadedClass(name); if (loaded == null) { - loaded = defineFromParentResource(name); + loaded = defineFromParent(name); } if (resolve) { resolveClass(loaded); @@ -342,19 +258,13 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE return super.loadClass(name, resolve); } - private Class defineFromParentResource(String name) throws ClassNotFoundException { + private Class defineFromParent(String name) throws ClassNotFoundException { String resource = name.replace('.', '/') + ".class"; try (InputStream in = getParent().getResourceAsStream(resource)) { if (in == null) { throw new ClassNotFoundException(name); } - ByteArrayOutputStream out = new ByteArrayOutputStream(); - byte[] buffer = new byte[4096]; - int bytesRead; - while ((bytesRead = in.read(buffer)) != -1) { - out.write(buffer, 0, bytesRead); - } - byte[] bytes = out.toByteArray(); + byte[] bytes = ByteStreams.toByteArray(in); return defineClass(name, bytes, 0, bytes.length); } catch (IOException e) { throw new ClassNotFoundException(name, e); From 6c36f180bf28456c90592d80860a6db2aa99d312 Mon Sep 17 00:00:00 2001 From: Lawrence Qiu Date: Fri, 4 Dec 2026 07:06:10 +0000 Subject: [PATCH 4/4] fix(gax-httpjson): harden Conscrypt opt-out parsing, lookup, docs, and tests - Trim opt-out flag values, warn on unrecognized values, and avoid letting invalid system property values override GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true - Short-circuit config and preferred TLS provider checks, deduplicate skip/warning logs, and resolve the Conscrypt provider once in InstantiatingHttpJsonChannelProvider - Fix ErrorProne DoubleBraceInitialization in HttpJsonConscryptUtilsTest, improve test isolation, and add mTLS and classloading opt-out coverage - Clarify PQC guide minimum version (gax-httpjson 2.92.0+ / libraries-bom 26.95.0+), verification logs, BCJSSE snippet, gRPC asymmetry, and BigQuery JDBC follow-up note --- docs/post_quantum_cryptography_guide.md | 38 ++-- .../gax/httpjson/HttpJsonConscryptUtils.java | 137 +++++++++--- .../InstantiatingHttpJsonChannelProvider.java | 30 +-- .../httpjson/HttpJsonConscryptUtilsTest.java | 209 ++++++++++++++---- ...tantiatingHttpJsonChannelProviderTest.java | 174 +++++++++++++++ 5 files changed, 483 insertions(+), 105 deletions(-) diff --git a/docs/post_quantum_cryptography_guide.md b/docs/post_quantum_cryptography_guide.md index 8fd1bcdedc1f..f5721b16b479 100644 --- a/docs/post_quantum_cryptography_guide.md +++ b/docs/post_quantum_cryptography_guide.md @@ -111,16 +111,18 @@ FINE: Selecting JDK with provider SunJSSE version ... Channels continue to operate normally with classical TLS, but post-quantum protection will be absent. ### 2.4 HTTP/JSON Fallback Behavior -- **Silent Fallback to Default JVM TLS**: If Conscrypt is unavailable, disabled, or skipped, `gax-httpjson` logs a debug message at `Level.FINE` and falls back to the JVM's default TLS provider: +- **Silent Fallback to Default JVM TLS**: If Conscrypt is unavailable, disabled, or skipped, `gax-httpjson` logs a debug message at `Level.FINE` and falls back to the JVM's default TLS provider. For example, when the native library cannot load: ```text FINE: Conscrypt native library unavailable. Falling back to default JDK TLS. ``` - On a standard JDK, this is the built-in `SunJSSE` provider. If another JSSE provider (such as `BCJSSE`) is configured ahead of `SunJSSE` in the JVM's security provider list, the JVM uses that provider instead. To check which provider your JVM selects for TLS, inspect the `security.provider.` order in `$JAVA_HOME/conf/security/java.security` (or `$JAVA_HOME/jre/lib/security/java.security` on JDK 8, plus any file passed via `-Djava.security.properties`), or check at runtime with `Security.getProviders("SSLContext.TLS")[0].getName()`. + When disabled via configuration or skipped for a non-default provider, `gax-httpjson` logs the specific flag or provider name instead (see [Section 3.2](#32-verifying-httpjson-connections)). + + On a standard JDK, the fallback is the built-in `SunJSSE` provider. If another JSSE provider (such as `BCJSSE`) is configured ahead of `SunJSSE` in the JVM's security provider list, the JVM uses that provider instead. To check which provider your JVM selects for TLS, inspect the `security.provider.` order in `$JAVA_HOME/conf/security/java.security` (or `$JAVA_HOME/jre/lib/security/java.security` on JDK 8, plus any file passed via `-Djava.security.properties`), or check at runtime with `Security.getProviders("SSLContext.TLS")[0].getName()`. See [Section 3](#3-how-to-verify-pqc-negotiation) for instructions on enabling internal logging or tracing TLS handshakes to verify whether your application is using PQC. - **Common Host and Configuration Triggers**: - - **Non-Default Preferred TLS Provider (Auto-Detected)**: If the JVM's preferred `SSLContext.TLS` provider is neither `SunJSSE` nor `Conscrypt` (for example, `BCJSSE` or `IBMJSSE2` on IBM JDK 8), `gax-httpjson` skips Conscrypt and uses the JVM's preferred provider instead. PQC over HTTP/JSON is off in this case unless Conscrypt is configured as the preferred provider. - - **Explicit Opt-Out Flag**: Setting `-Dcom.google.api.gax.httpjson.disableConscrypt=true` or `GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true` skips loading Conscrypt globally for HTTP/JSON transports (see [Section 4.2](#42-custom-httpjson-configurations) and [Section 4.3](#43-controlling-the-jvm-security-provider-across-both-transports)). + - **Non-Default Preferred TLS Provider (Auto-Detected, `gax-httpjson` `2.92.0+`)**: If the JVM's preferred `SSLContext.TLS` provider is neither `SunJSSE` nor `Conscrypt` (for example, `BCJSSE` or `IBMJSSE2` on IBM JDK 8), `gax-httpjson` skips Conscrypt and uses the JVM's preferred provider instead. PQC over HTTP/JSON is off in this case unless Conscrypt is configured as the preferred provider. This auto-detection applies only to HTTP/JSON (`gax-httpjson`). gRPC (`grpc-netty-shaded`) does not auto-detect `BCJSSE` and still uses bundled BoringSSL unless `-Dio.grpc.netty.shaded.io.netty.handler.ssl.noOpenSsl=true` is set. + - **Explicit Opt-Out Flag (`gax-httpjson` `2.92.0+`)**: Setting `-Dcom.google.api.gax.httpjson.disableConscrypt=true` or `GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true` skips loading Conscrypt globally for HTTP/JSON transports (see [Section 4.2](#42-custom-httpjson-configurations) and [Section 4.3](#43-controlling-the-jvm-security-provider-across-both-transports)). - **Alpine Linux (`musl` libc)**: Precompiled Conscrypt binaries require `glibc`. On `musl`-based distributions (e.g., `alpine`), Conscrypt cannot load and falls back to classical TLS. Use a `glibc`-compatible base image (such as Debian, Ubuntu, or Wolfi) for PQC. - **Hardened Filesystems (`noexec /tmp`)**: If `/tmp` is mounted with `noexec` or is read-only, Conscrypt cannot load extracted native libraries. To enable PQC, specify an executable directory via `-Dorg.conscrypt.native.workdir=/path/to/executable/dir`. @@ -134,7 +136,7 @@ To confirm whether your application is actively negotiating post-quantum hybrid | :--- | :--- | :--- | :--- | | **gRPC** | Shaded Netty BoringSSL (JNI) | `-Dio.grpc.netty.shaded.io.netty.handler.ssl=DEBUG` | Handshake logs showing `HANDSHAKEN: TLS_AES_128_GCM_SHA256` | | **HTTP/JSON** | Conscrypt BoringSSL (`SSLContext`) | `-Djavax.net.debug=ssl:handshake` | `ClientHello` offering `X25519MLKEM768` (`0x11ec`), `ServerHello` selecting `X25519MLKEM768` | -| **HTTP/JSON** | `gax-httpjson` Provider Bridge | `HttpJsonConscryptUtils` (`Level.FINE`) | Absence of fallback log (`FINE: Conscrypt native library unavailable...`) | +| **HTTP/JSON** | `gax-httpjson` Provider Bridge | `HttpJsonConscryptUtils` (`Level.FINE`) | Absence of any fallback, disabled, or skipped `FINE` log (`Conscrypt native library unavailable...`, `Conscrypt disabled via...`, or `Skipping Conscrypt...`) | > [!NOTE] > **Why gRPC ignores `-Djavax.net.debug`**: @@ -175,11 +177,11 @@ import java.util.logging.Logger; Logger.getLogger("com.google.api.gax.httpjson.HttpJsonConscryptUtils").setLevel(Level.FINE); ``` -- **When Conscrypt initializes successfully**: No fallback messages appear in the log. -- **When fallback occurs**: You will observe: +- **When Conscrypt initializes successfully**: No fallback, disabled, or skipped messages appear in the log. +- **When fallback occurs**: You will observe a `FINE` log entry with the underlying exception stack trace: ```text FINE: Conscrypt native library unavailable. Falling back to default JDK TLS. - FINE: Conscrypt initialization failed with exception: java.lang.UnsatisfiedLinkError: ... + java.lang.UnsatisfiedLinkError: ... ``` - **When Conscrypt is disabled or skipped**: You will observe a `FINE` message naming the opt-out flag or the detected preferred TLS provider: ```text @@ -306,7 +308,9 @@ try (SecretManagerServiceClient client = SecretManagerServiceClient.create(setti ### 4.2 Custom HTTP/JSON Configurations #### Option 1: Disabling Conscrypt Globally -To disable Conscrypt across all HTTP/JSON transports created by `gax-httpjson` and `google-cloud-core-http` (including handwritten clients, GAPIC REST channels, and mTLS transports) without changing application code, set either the JVM system property or environment variable before creating clients: +Requires `gax-httpjson` `2.92.0+` (`libraries-bom` `26.95.0+`). Older versions silently ignore unknown system properties and environment variables, so verify that Conscrypt is skipped with `FINE` logging (see [Section 3.2](#32-verifying-httpjson-connections)). + +To disable Conscrypt across HTTP/JSON transports created by `gax-httpjson` and `google-cloud-core-http` (including handwritten clients, GAPIC REST channels, and mTLS transports) without changing application code, set either the JVM system property or environment variable before creating clients: ```bash # Via JVM system property (takes precedence if both are set) @@ -316,7 +320,7 @@ java -Dcom.google.api.gax.httpjson.disableConscrypt=true -jar my-application.jar GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true java -jar my-application.jar ``` -When enabled, `gax-httpjson` skips loading Conscrypt and leaves TLS to the JVM's default configured security provider. Values are matched case-insensitively (`true` disables Conscrypt). Any other value (such as `false`) leaves the default auto-detection active, and setting the system property overrides the environment variable. +When enabled, `gax-httpjson` skips loading Conscrypt and leaves TLS to the JVM's default configured security provider. Values are trimmed and matched case-insensitively: `true` disables Conscrypt, `false` leaves default auto-detection active (and overrides `GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true` when set via the system property), and unrecognized non-blank values log a warning and are ignored. Note that `google-cloud-bigquery-jdbc` proxy and custom truststore transports are tracked in a separate follow-up and do not yet honor this opt-out. #### Option 2: Forcing Classical-Only Key Exchange (Disabling PQC) If you need to use Conscrypt for high-performance TLS but want to explicitly disable post-quantum hybrid groups (see [Common Reasons to Disable PQC](#common-reasons-to-disable-pqc)): @@ -383,8 +387,8 @@ try (SecretManagerServiceClient client = SecretManagerServiceClient.create(setti If your enterprise utilizes an alternative cryptographic provider (such as Bouncy Castle), configure it directly on the `NetHttpTransport.Builder`: ```java -// 1. Instantiate or lookup custom security provider -Provider customProvider = Security.getProvider("BC"); // e.g., BouncyCastleProvider +// 1. Instantiate or lookup custom JSSE security provider +Provider customProvider = Security.getProvider("BCJSSE"); // e.g., BouncyCastleJsseProvider // 2. Configure NetHttpTransport with the custom provider NetHttpTransport customTransport = @@ -416,7 +420,9 @@ try (SecretManagerServiceClient client = SecretManagerServiceClient.create(setti ### 4.3 Controlling the JVM Security Provider Across Both Transports -If you want all Google Cloud client TLS connections to use the JVM's configured `java.security` provider instead of bundled BoringSSL engines (for example, to enforce a specific JCA provider or meet compliance requirements such as FIPS), disable native BoringSSL on both transports: +Requires `gax-httpjson` `2.92.0+` (`libraries-bom` `26.95.0+`) for the HTTP/JSON opt-out and preferred-provider auto-detection. + +If you want Google Cloud client TLS connections to use the JVM's configured `java.security` provider instead of bundled BoringSSL engines (for example, to enforce a specific JCA provider or meet compliance requirements such as FIPS), disable native BoringSSL on both transports: ```bash java \ @@ -425,8 +431,8 @@ java \ -jar my-application.jar ``` -- **HTTP/JSON transport**: When a non-default provider (such as `BCJSSE`) is configured as the JVM's preferred `SSLContext.TLS` provider in `java.security`, `gax-httpjson` detects it automatically and skips Conscrypt. Set `-Dcom.google.api.gax.httpjson.disableConscrypt=true` (or `GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true`) whenever you want to guarantee Conscrypt is never loaded, including in environments where `SunJSSE` remains the preferred provider (such as RHEL FIPS mode). -- **gRPC transport**: `-Dio.grpc.netty.shaded.io.netty.handler.ssl.noOpenSsl=true` disables Netty's shaded BoringSSL provider so gRPC falls back to the JVM's configured TLS provider. +- **HTTP/JSON transport**: When a non-default provider (such as `BCJSSE`) is configured as the JVM's preferred `SSLContext.TLS` provider in `java.security`, `gax-httpjson` detects it automatically and skips Conscrypt. Set `-Dcom.google.api.gax.httpjson.disableConscrypt=true` (or `GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true`) whenever you want to guarantee Conscrypt is never loaded, including in environments where `SunJSSE` remains the preferred provider (such as RHEL FIPS mode). Note that `google-cloud-bigquery-jdbc` proxy and custom truststore transports are tracked in a separate follow-up and do not yet honor this opt-out. +- **gRPC transport**: Preferred-provider auto-detection applies only to HTTP/JSON (`gax-httpjson`). For gRPC, `-Dio.grpc.netty.shaded.io.netty.handler.ssl.noOpenSsl=true` is required even when `BCJSSE` is preferred so Netty's shaded BoringSSL provider is disabled and gRPC falls back to the JVM's configured TLS provider. --- @@ -438,7 +444,7 @@ Because PQC negotiation relies on native BoringSSL C binaries (bundled in `grpc- GraalVM Native Image compilation is supported for applications that include the appropriate reachability metadata and JNI configuration for Netty or Conscrypt native libraries. ### 5.2 Classpath Isolation & Version Skew Warning -If your project uses multiple dependencies that transitively pull in different versions of gRPC Netty components or Conscrypt, JNI ABI mismatches can occur during JVM classloading. Always ensure your build tool resolves compatible versions consistently. +If your project uses multiple dependencies that transitively pull in different versions of gRPC Netty components or Conscrypt, JNI ABI mismatches can occur during JVM classloading. Always ensure your build tool resolves compatible versions consistently. If you hit a Conscrypt JNI mismatch while resolving dependency skew, you can temporarily disable Conscrypt globally via `-Dcom.google.api.gax.httpjson.disableConscrypt=true` or `GOOGLE_SDK_JAVA_DISABLE_CONSCRYPT=true` (see [Section 4.2](#42-custom-httpjson-configurations) and [Section 4.3](#43-controlling-the-jvm-security-provider-across-both-transports)). We recommend using Google Cloud's `libraries-bom` (version `26.88.0+`), which centrally manages dependency versions and ensures consistent, compatible runtime dependencies across all Google Cloud client libraries. diff --git a/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonConscryptUtils.java b/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonConscryptUtils.java index 0636d15fd4b4..85faa6b4fb02 100644 --- a/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonConscryptUtils.java +++ b/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/HttpJsonConscryptUtils.java @@ -34,6 +34,7 @@ import com.google.common.annotations.VisibleForTesting; import java.security.Provider; import java.security.Security; +import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; import org.conscrypt.Conscrypt; @@ -49,6 +50,9 @@ public class HttpJsonConscryptUtils { private static final String SUN_JSSE_PROVIDER_NAME = "SunJSSE"; private static final String CONSCRYPT_PROVIDER_NAME = "Conscrypt"; + private static volatile String lastSkipLogMessage; + private static volatile String lastWarningLogMessage; + /** * Default TLS 1.3 named groups configured when Conscrypt security provider is present, organized * in client preference order: @@ -106,7 +110,11 @@ private static Provider createProvider() { */ public static NetHttpTransport.Builder configureConscryptSecurityProvider( NetHttpTransport.Builder builder) { - Provider conscryptProvider = getConscryptProvider(); + return configureConscryptSecurityProvider(builder, getConscryptProvider()); + } + + static NetHttpTransport.Builder configureConscryptSecurityProvider( + NetHttpTransport.Builder builder, Provider conscryptProvider) { if (conscryptProvider == null) { return builder; } @@ -140,46 +148,107 @@ public static NetHttpTransport.Builder configureConscryptSecurityProvider( * @return the Conscrypt provider or {@code null} */ public static Provider getConscryptProvider() { - if (!shouldUseConscrypt( - getSystemProperty(DISABLE_CONSCRYPT_PROPERTY), - getEnv(DISABLE_CONSCRYPT_ENV), - getPreferredTlsProviderName())) { + if (isDisabledByConfig() || !isDefaultOrConscryptTlsProvider(getPreferredTlsProviderName())) { return null; } + lastSkipLogMessage = null; return ConscryptProviderHolder.INSTANCE; } + private static boolean isDisabledByConfig() { + return isDisabledByConfig( + getSystemProperty(DISABLE_CONSCRYPT_PROPERTY), () -> getEnv(DISABLE_CONSCRYPT_ENV)); + } + @VisibleForTesting - static boolean shouldUseConscrypt( - String disableProperty, String disableEnv, String preferredTlsProvider) { - if (disableProperty != null && !disableProperty.isEmpty()) { - if ("true".equalsIgnoreCase(disableProperty)) { - LOG.log( - Level.FINE, - "Conscrypt disabled via system property {0}. Using JVM default TLS provider.", - DISABLE_CONSCRYPT_PROPERTY); - return false; + static boolean isDisabledByConfig(String disableProperty, String disableEnv) { + return isDisabledByConfig(disableProperty, () -> disableEnv); + } + + private static boolean isDisabledByConfig( + String disableProperty, Supplier disableEnvSupplier) { + Boolean propertyValue = + parseBooleanFlag(disableProperty, "system property", DISABLE_CONSCRYPT_PROPERTY); + if (propertyValue != null) { + if (propertyValue) { + logSkipOnce( + "Conscrypt disabled via system property " + + DISABLE_CONSCRYPT_PROPERTY + + ". Using JVM default TLS provider."); } - } else if ("true".equalsIgnoreCase(disableEnv)) { - LOG.log( - Level.FINE, - "Conscrypt disabled via environment variable {0}. Using JVM default TLS provider.", - DISABLE_CONSCRYPT_ENV); - return false; - } - - if (!SUN_JSSE_PROVIDER_NAME.equals(preferredTlsProvider) - && !CONSCRYPT_PROVIDER_NAME.equals(preferredTlsProvider)) { - LOG.log( - Level.FINE, - preferredTlsProvider == null - ? "Skipping Conscrypt because no preferred JVM TLS provider was found." - : "Skipping Conscrypt because preferred JVM TLS provider is {0}.", - preferredTlsProvider); - return false; - } - - return true; + return propertyValue; + } + + Boolean envValue = + parseBooleanFlag(disableEnvSupplier.get(), "environment variable", DISABLE_CONSCRYPT_ENV); + if (Boolean.TRUE.equals(envValue)) { + logSkipOnce( + "Conscrypt disabled via environment variable " + + DISABLE_CONSCRYPT_ENV + + ". Using JVM default TLS provider."); + return true; + } + return false; + } + + private static Boolean parseBooleanFlag(String rawValue, String sourceKind, String name) { + if (rawValue == null) { + return null; + } + String trimmed = rawValue.trim(); + if (trimmed.isEmpty()) { + return null; + } + if ("true".equalsIgnoreCase(trimmed)) { + return Boolean.TRUE; + } + if ("false".equalsIgnoreCase(trimmed)) { + return Boolean.FALSE; + } + logWarningOnce( + "Ignoring unrecognized boolean value \"" + + rawValue + + "\" for " + + sourceKind + + " " + + name + + ". Expected \"true\" or \"false\"."); + return null; + } + + @VisibleForTesting + static boolean isDefaultOrConscryptTlsProvider(String preferredTlsProvider) { + if (SUN_JSSE_PROVIDER_NAME.equals(preferredTlsProvider) + || CONSCRYPT_PROVIDER_NAME.equals(preferredTlsProvider)) { + return true; + } + if (preferredTlsProvider == null) { + logSkipOnce("Skipping Conscrypt because no preferred JVM TLS provider was found."); + } else { + logSkipOnce( + "Skipping Conscrypt because preferred JVM TLS provider is " + preferredTlsProvider + "."); + } + return false; + } + + private static void logSkipOnce(String message) { + if (!message.equals(lastSkipLogMessage)) { + lastSkipLogMessage = message; + LOG.log(Level.FINE, message); + } + } + + private static void logWarningOnce(String message) { + if (!message.equals(lastWarningLogMessage)) { + lastWarningLogMessage = message; + LOG.log(Level.WARNING, message); + } + } + + @VisibleForTesting + static void resetLogStateForTesting() { + lastSkipLogMessage = null; + lastWarningLogMessage = null; } private static String getSystemProperty(String name) { diff --git a/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/InstantiatingHttpJsonChannelProvider.java b/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/InstantiatingHttpJsonChannelProvider.java index 0766a8032df1..8a3a7bab875d 100644 --- a/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/InstantiatingHttpJsonChannelProvider.java +++ b/sdk-platform-java/gax-java/gax-httpjson/src/main/java/com/google/api/gax/httpjson/InstantiatingHttpJsonChannelProvider.java @@ -197,25 +197,30 @@ public TransportChannelProvider withCredentials(Credentials credentials) { HttpTransport createHttpTransport() throws IOException, GeneralSecurityException { NetHttpTransport.Builder builder = new NetHttpTransport.Builder(); - configureMtls(builder); - HttpJsonConscryptUtils.configureConscryptSecurityProvider(builder); + KeyStore mtlsKeyStore = getMtlsKeyStore(); + Provider conscryptProvider = HttpJsonConscryptUtils.getConscryptProvider(); + if (mtlsKeyStore != null) { + configureMtls(builder, mtlsKeyStore, conscryptProvider); + } + HttpJsonConscryptUtils.configureConscryptSecurityProvider(builder, conscryptProvider); return builder.build(); } - private NetHttpTransport.Builder configureMtls(NetHttpTransport.Builder builder) - throws IOException, GeneralSecurityException { + private KeyStore getMtlsKeyStore() throws IOException, GeneralSecurityException { if (mtlsProvider == null || !certificateBasedAccess.useMtlsClientCertificate()) { - return builder; - } - KeyStore mtlsKeyStore = mtlsProvider.getKeyStore(); - if (mtlsKeyStore == null) { - return builder; + return null; } + return mtlsProvider.getKeyStore(); + } + + private void configureMtls( + NetHttpTransport.Builder builder, KeyStore mtlsKeyStore, Provider conscryptProvider) + throws IOException, GeneralSecurityException { builder.trustCertificates(null, mtlsKeyStore, ""); - Provider conscryptProvider = HttpJsonConscryptUtils.getConscryptProvider(); if (conscryptProvider == null) { - // Fall back to standard JDK JSSE if Conscrypt provider is unavailable - return builder; + // Fall back to the JVM's default TLS provider if Conscrypt is disabled, skipped, or + // unavailable. + return; } // NetHttpTransport.Builder.trustCertificates() in google-http-client initializes with the // default SunX509 KeyManagerFactory (via SslUtils.getDefaultKeyManagerFactory()), which is not @@ -240,7 +245,6 @@ private NetHttpTransport.Builder configureMtls(NetHttpTransport.Builder builder) "", KeyManagerFactory.getInstance("PKIX", conscryptProvider)); builder.setSslSocketFactory(sslContext.getSocketFactory()); - return builder; } private HttpTransport createChannelHttpTransport() throws IOException, GeneralSecurityException { diff --git a/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonConscryptUtilsTest.java b/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonConscryptUtilsTest.java index 3ef204c61e36..72c8a86067ac 100644 --- a/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonConscryptUtilsTest.java +++ b/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/HttpJsonConscryptUtilsTest.java @@ -44,16 +44,27 @@ import java.net.Socket; import java.security.Provider; import java.security.Security; +import java.util.ArrayList; import java.util.Collections; +import java.util.List; import java.util.concurrent.atomic.AtomicReference; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import org.conscrypt.Conscrypt; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; +@ResourceLock(Resources.SYSTEM_PROPERTIES) +@ResourceLock("java.security.providers") class HttpJsonConscryptUtilsTest { private static final String TEST_TLS_PROVIDER_NAME = "TestCustomJSSE"; @@ -63,6 +74,8 @@ class HttpJsonConscryptUtilsTest { @BeforeEach void setUp() { previousDisableProperty = System.getProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY); + System.clearProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY); + HttpJsonConscryptUtils.resetLogStateForTesting(); } @AfterEach @@ -74,6 +87,7 @@ void tearDown() { HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, previousDisableProperty); } Security.removeProvider(TEST_TLS_PROVIDER_NAME); + HttpJsonConscryptUtils.resetLogStateForTesting(); } @Test @@ -94,9 +108,10 @@ void testConfigureConscryptSecurityProvider_returnsSameBuilder() { @Test void testConfigureConscryptSecurityProvider_usesConscryptWhenAvailable() throws Exception { - if (HttpJsonConscryptUtils.getConscryptProvider() == null) { - return; - } + System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "false"); + Assumptions.assumeTrue( + HttpJsonConscryptUtils.getConscryptProvider() != null, + "Conscrypt native library is unavailable in this environment"); SSLSocketFactory captured = captureConfiguredSslSocketFactory(); assertThat(captured).isNotNull(); try (Socket socket = captured.createSocket()) { @@ -114,55 +129,68 @@ void testDefaultConscryptNamedGroups_containsExpectedGroups() { } @Test - void testShouldUseConscrypt_allowsSunJsseWhenUnset() { - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "SunJSSE")).isTrue(); - } - - @Test - void testShouldUseConscrypt_allowsConscryptWhenUnset() { - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "Conscrypt")).isTrue(); + void testIsDefaultOrConscryptTlsProvider_allowsSunJsseAndConscrypt() { + assertThat(HttpJsonConscryptUtils.isDefaultOrConscryptTlsProvider("SunJSSE")).isTrue(); + assertThat(HttpJsonConscryptUtils.isDefaultOrConscryptTlsProvider("Conscrypt")).isTrue(); } @Test - void testShouldUseConscrypt_skipsNonDefaultTlsProvider() { - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "BCJSSE")).isFalse(); - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, "IBMJSSE2")).isFalse(); + void testIsDefaultOrConscryptTlsProvider_skipsNonDefaultOrMissingProvider() { + assertThat(HttpJsonConscryptUtils.isDefaultOrConscryptTlsProvider("BCJSSE")).isFalse(); + assertThat(HttpJsonConscryptUtils.isDefaultOrConscryptTlsProvider("IBMJSSE2")).isFalse(); + assertThat(HttpJsonConscryptUtils.isDefaultOrConscryptTlsProvider(null)).isFalse(); } @Test - void testShouldUseConscrypt_skipsWhenNoTlsProviderFound() { - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, null, null)).isFalse(); + void testIsDisabledByConfig_disabledBySystemProperty() { + assertThat(HttpJsonConscryptUtils.isDisabledByConfig("true", null)).isTrue(); + assertThat(HttpJsonConscryptUtils.isDisabledByConfig("TRUE", "false")).isTrue(); + assertThat(HttpJsonConscryptUtils.isDisabledByConfig(" true ", null)).isTrue(); + assertThat(HttpJsonConscryptUtils.isDisabledByConfig("true\n", null)).isTrue(); } @Test - void testShouldUseConscrypt_disabledBySystemProperty() { - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("true", null, "SunJSSE")).isFalse(); - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("TRUE", "false", "Conscrypt")).isFalse(); + void testIsDisabledByConfig_disabledByEnvVarWhenPropertyUnsetOrBlank() { + assertThat(HttpJsonConscryptUtils.isDisabledByConfig(null, "true")).isTrue(); + assertThat(HttpJsonConscryptUtils.isDisabledByConfig("", "TRUE")).isTrue(); + assertThat(HttpJsonConscryptUtils.isDisabledByConfig(" ", "true ")).isTrue(); } @Test - void testShouldUseConscrypt_disabledByEnvVarWhenPropertyUnsetOrEmpty() { - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "true", "SunJSSE")).isFalse(); - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("", "TRUE", "Conscrypt")).isFalse(); + void testIsDisabledByConfig_falseSystemPropertyOverridesEnvVar() { + assertThat(HttpJsonConscryptUtils.isDisabledByConfig("false", "true")).isFalse(); + assertThat(HttpJsonConscryptUtils.isDisabledByConfig(" FALSE ", "true")).isFalse(); } @Test - void testShouldUseConscrypt_ignoresNonTrueEnvVarValues() { - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "false", "SunJSSE")).isTrue(); - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "invalid", "SunJSSE")).isTrue(); - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt(null, "", "SunJSSE")).isTrue(); - } + void testIsDisabledByConfig_ignoresUnrecognizedValuesAndLogsWarning() { + CapturingLogHandler handler = attachLogHandler(Level.FINE); + try { + assertThat(HttpJsonConscryptUtils.isDisabledByConfig(null, "false")).isFalse(); + assertThat(HttpJsonConscryptUtils.isDisabledByConfig(null, "")).isFalse(); + assertThat(HttpJsonConscryptUtils.isDisabledByConfig(null, " ")).isFalse(); + assertThat(handler.warnings()).isEmpty(); - @Test - void testShouldUseConscrypt_systemPropertyOverridesEnvVar() { - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("false", "true", "SunJSSE")).isTrue(); - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("invalid", "true", "SunJSSE")).isTrue(); + assertThat(HttpJsonConscryptUtils.isDisabledByConfig(null, "1")).isFalse(); + assertThat(HttpJsonConscryptUtils.isDisabledByConfig(null, "yes")).isFalse(); + assertThat(HttpJsonConscryptUtils.isDisabledByConfig("invalid", null)).isFalse(); + assertThat(handler.warnings()).hasSize(3); + } finally { + detachLogHandler(handler); + } } @Test - void testShouldUseConscrypt_falseSystemPropertyStillRespectsAutoDetect() { - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("false", null, "BCJSSE")).isFalse(); - assertThat(HttpJsonConscryptUtils.shouldUseConscrypt("false", "true", "BCJSSE")).isFalse(); + void testIsDisabledByConfig_unrecognizedSystemPropertyDoesNotOverrideEnvVar() { + CapturingLogHandler handler = attachLogHandler(Level.FINE); + try { + assertThat(HttpJsonConscryptUtils.isDisabledByConfig("invalid", "true")).isTrue(); + assertThat(HttpJsonConscryptUtils.isDisabledByConfig("1", "true")).isTrue(); + assertThat(HttpJsonConscryptUtils.isDisabledByConfig("yes", "true")).isTrue(); + assertThat(handler.warnings()).hasSize(3); + } finally { + detachLogHandler(handler); + } } @Test @@ -180,25 +208,68 @@ void testConfigureConscryptSecurityProvider_disabledBySystemProperty_skipsConscr @Test void testGetConscryptProvider_customTlsProviderPreferred_returnsNull() { - Security.insertProviderAt(createTestTlsProvider(), 1); + System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "false"); + Security.insertProviderAt(new TestTlsProvider(), 1); assertThat(HttpJsonConscryptUtils.getConscryptProvider()).isNull(); } @Test void testConfigureConscryptSecurityProvider_customTlsProviderPreferred_skipsConscrypt() throws Exception { - Security.insertProviderAt(createTestTlsProvider(), 1); + System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "false"); + Security.insertProviderAt(new TestTlsProvider(), 1); assertThat(captureConfiguredSslSocketFactory()).isNull(); } @Test - void testGetConscryptProvider_disabledBySystemProperty_doesNotLoadConscrypt() throws Exception { + void testGetConscryptProvider_deduplicatesSkipLogsUntilReasonChanges() { + CapturingLogHandler handler = attachLogHandler(Level.FINE); + try { + System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "true"); + assertThat(HttpJsonConscryptUtils.getConscryptProvider()).isNull(); + assertThat(HttpJsonConscryptUtils.getConscryptProvider()).isNull(); + assertThat(handler.fineMessages()).hasSize(1); + assertThat(handler.fineMessages().get(0)) + .contains( + "Conscrypt disabled via system property " + + HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY); + + System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "false"); + Security.insertProviderAt(new TestTlsProvider(), 1); + assertThat(HttpJsonConscryptUtils.getConscryptProvider()).isNull(); + assertThat(HttpJsonConscryptUtils.getConscryptProvider()).isNull(); + assertThat(handler.fineMessages()).hasSize(2); + assertThat(handler.fineMessages().get(1)).contains(TEST_TLS_PROVIDER_NAME); + } finally { + detachLogHandler(handler); + } + } + + @Test + void testDisabledBySystemProperty_doesNotLoadConscrypt() throws Exception { System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "true"); + assertConscryptNotLoadedInIsolatedClassLoader(); + } + + @Test + void testCustomTlsProviderPreferred_doesNotLoadConscrypt() throws Exception { + System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "false"); + Security.insertProviderAt(new TestTlsProvider(), 1); + assertConscryptNotLoadedInIsolatedClassLoader(); + } + + private static void assertConscryptNotLoadedInIsolatedClassLoader() throws Exception { ClassLoader loader = new ConscryptBlockingClassLoader(HttpJsonConscryptUtils.class.getClassLoader()); Class utilsClass = loader.loadClass(HttpJsonConscryptUtils.class.getName()); Method getProvider = utilsClass.getMethod("getConscryptProvider"); assertThat(getProvider.invoke(null)).isNull(); + + NetHttpTransport.Builder builder = new NetHttpTransport.Builder(); + Method configure = + utilsClass.getMethod("configureConscryptSecurityProvider", NetHttpTransport.Builder.class); + assertThat(configure.invoke(null, builder)).isSameInstanceAs(builder); + assertThat(builder.build()).isNotNull(); } private static SSLSocketFactory captureConfiguredSslSocketFactory() throws IOException { @@ -225,13 +296,67 @@ private static SSLSocketFactory captureConfiguredSslSocketFactory() throws IOExc return captured.get(); } - @SuppressWarnings("deprecation") - private static Provider createTestTlsProvider() { - return new Provider(TEST_TLS_PROVIDER_NAME, 1.0, "Test TLS provider") { - { - put("SSLContext.TLS", "com.example.UnusedSslContextSpi"); + private static CapturingLogHandler attachLogHandler(Level level) { + Logger logger = Logger.getLogger(HttpJsonConscryptUtils.class.getName()); + CapturingLogHandler handler = new CapturingLogHandler(logger.getLevel()); + handler.setLevel(level); + logger.setLevel(level); + logger.addHandler(handler); + return handler; + } + + private static void detachLogHandler(CapturingLogHandler handler) { + Logger logger = Logger.getLogger(HttpJsonConscryptUtils.class.getName()); + logger.removeHandler(handler); + logger.setLevel(handler.previousLevel); + } + + private static final class CapturingLogHandler extends Handler { + private final Level previousLevel; + private final List records = new ArrayList<>(); + + CapturingLogHandler(Level previousLevel) { + this.previousLevel = previousLevel; + } + + @Override + public void publish(LogRecord record) { + records.add(record); + } + + @Override + public void flush() {} + + @Override + public void close() {} + + List fineMessages() { + List messages = new ArrayList<>(); + for (LogRecord record : records) { + if (Level.FINE.equals(record.getLevel())) { + messages.add(record.getMessage()); + } + } + return messages; + } + + List warnings() { + List messages = new ArrayList<>(); + for (LogRecord record : records) { + if (Level.WARNING.equals(record.getLevel())) { + messages.add(record.getMessage()); + } } - }; + return messages; + } + } + + private static final class TestTlsProvider extends Provider { + @SuppressWarnings("deprecation") + TestTlsProvider() { + super(TEST_TLS_PROVIDER_NAME, 1.0, "Test TLS provider"); + put("SSLContext.TLS", "com.example.UnusedSslContextSpi"); + } } private static final class ConscryptBlockingClassLoader extends ClassLoader { diff --git a/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/InstantiatingHttpJsonChannelProviderTest.java b/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/InstantiatingHttpJsonChannelProviderTest.java index 74a578da24cb..92c77b468631 100644 --- a/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/InstantiatingHttpJsonChannelProviderTest.java +++ b/sdk-platform-java/gax-java/gax-httpjson/src/test/java/com/google/api/gax/httpjson/InstantiatingHttpJsonChannelProviderTest.java @@ -44,20 +44,41 @@ import com.google.auth.mtls.CertificateSourceUnavailableException; import com.google.auth.mtls.MtlsProvider; import java.io.IOException; +import java.lang.reflect.Field; +import java.net.Socket; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.GeneralSecurityException; +import java.security.KeyManagementException; import java.security.KeyStore; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.Provider; +import java.security.SecureRandom; +import java.security.Security; import java.util.Collections; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLContextSpi; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSessionContext; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import org.conscrypt.Conscrypt; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; import org.mockito.Mockito; class InstantiatingHttpJsonChannelProviderTest extends AbstractMtlsTransportChannelTest { @@ -593,6 +614,159 @@ void testConfigureConscryptSecurityProvider_returnsConfiguredBuilder() { assertThat(result).isSameInstanceAs(builder); } + @Test + @ResourceLock(Resources.SYSTEM_PROPERTIES) + void testCreateHttpTransport_withMtls_disabledBySystemProperty_skipsConscrypt() throws Exception { + String previous = System.getProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY); + try { + System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "true"); + Mockito.when(certificateBasedAccess.useMtlsClientCertificate()).thenReturn(true); + MtlsProvider mtlsProvider = + new FakeMtlsProvider(FakeMtlsProvider.createTestMtlsKeyStore(), "", false); + InstantiatingHttpJsonChannelProvider channelProvider = + InstantiatingHttpJsonChannelProvider.newBuilder() + .setEndpoint(DEFAULT_ENDPOINT) + .setMtlsProvider(mtlsProvider) + .setCertificateBasedAccess(certificateBasedAccess) + .setHeaderProvider(Collections::emptyMap) + .setExecutor(Runnable::run) + .build(); + + NetHttpTransport transport = (NetHttpTransport) channelProvider.createHttpTransport(); + assertThat(transport.isMtls()).isTrue(); + SSLSocketFactory socketFactory = getSslSocketFactory(transport); + assertThat(socketFactory).isNotNull(); + try (Socket socket = socketFactory.createSocket()) { + assertThat(socket).isInstanceOf(SSLSocket.class); + assertThat(Conscrypt.isConscrypt((SSLSocket) socket)).isFalse(); + } + } finally { + restoreSystemProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, previous); + } + } + + @Test + @ResourceLock(Resources.SYSTEM_PROPERTIES) + @ResourceLock("java.security.providers") + void testCreateHttpTransport_withMtls_customTlsProviderPreferred_skipsConscrypt() + throws Exception { + String providerName = "TestMtlsCustomJSSE"; + String previous = System.getProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY); + DelegatingTlsProvider customProvider = new DelegatingTlsProvider(providerName); + try { + System.setProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, "false"); + Security.insertProviderAt(customProvider, 1); + Mockito.when(certificateBasedAccess.useMtlsClientCertificate()).thenReturn(true); + MtlsProvider mtlsProvider = + new FakeMtlsProvider(FakeMtlsProvider.createTestMtlsKeyStore(), "", false); + InstantiatingHttpJsonChannelProvider channelProvider = + InstantiatingHttpJsonChannelProvider.newBuilder() + .setEndpoint(DEFAULT_ENDPOINT) + .setMtlsProvider(mtlsProvider) + .setCertificateBasedAccess(certificateBasedAccess) + .setHeaderProvider(Collections::emptyMap) + .setExecutor(Runnable::run) + .build(); + + NetHttpTransport transport = (NetHttpTransport) channelProvider.createHttpTransport(); + assertThat(transport.isMtls()).isTrue(); + assertThat(customProvider.wasSslContextRequested()).isTrue(); + SSLSocketFactory socketFactory = getSslSocketFactory(transport); + assertThat(socketFactory).isNotNull(); + try (Socket socket = socketFactory.createSocket()) { + assertThat(socket).isInstanceOf(SSLSocket.class); + assertThat(Conscrypt.isConscrypt((SSLSocket) socket)).isFalse(); + } + } finally { + Security.removeProvider(providerName); + restoreSystemProperty(HttpJsonConscryptUtils.DISABLE_CONSCRYPT_PROPERTY, previous); + } + } + + private static SSLSocketFactory getSslSocketFactory(NetHttpTransport transport) throws Exception { + Field field = NetHttpTransport.class.getDeclaredField("sslSocketFactory"); + field.setAccessible(true); + return (SSLSocketFactory) field.get(transport); + } + + private static void restoreSystemProperty(String key, String previousValue) { + if (previousValue == null) { + System.clearProperty(key); + } else { + System.setProperty(key, previousValue); + } + } + + private static final class DelegatingTlsProvider extends Provider { + private final AtomicBoolean sslContextRequested = new AtomicBoolean(false); + + @SuppressWarnings("deprecation") + DelegatingTlsProvider(String name) { + super(name, 1.0, "Test delegating TLS provider"); + putService( + new Service( + this, "SSLContext", "TLS", DelegatingSslContextSpi.class.getName(), null, null) { + @Override + public Object newInstance(Object constructorParameter) throws NoSuchAlgorithmException { + sslContextRequested.set(true); + return new DelegatingSslContextSpi(); + } + }); + } + + boolean wasSslContextRequested() { + return sslContextRequested.get(); + } + } + + private static final class DelegatingSslContextSpi extends SSLContextSpi { + private final SSLContext delegate; + + DelegatingSslContextSpi() throws NoSuchAlgorithmException { + try { + this.delegate = SSLContext.getInstance("TLS", "SunJSSE"); + } catch (NoSuchProviderException e) { + throw new NoSuchAlgorithmException(e); + } + } + + @Override + protected void engineInit(KeyManager[] km, TrustManager[] tm, SecureRandom sr) + throws KeyManagementException { + delegate.init(km, tm, sr); + } + + @Override + protected SSLSocketFactory engineGetSocketFactory() { + return delegate.getSocketFactory(); + } + + @Override + protected SSLServerSocketFactory engineGetServerSocketFactory() { + return delegate.getServerSocketFactory(); + } + + @Override + protected SSLEngine engineCreateSSLEngine() { + return delegate.createSSLEngine(); + } + + @Override + protected SSLEngine engineCreateSSLEngine(String host, int port) { + return delegate.createSSLEngine(host, port); + } + + @Override + protected SSLSessionContext engineGetServerSessionContext() { + return delegate.getServerSessionContext(); + } + + @Override + protected SSLSessionContext engineGetClientSessionContext() { + return delegate.getClientSessionContext(); + } + } + @Override protected Object getMtlsObjectFromTransportChannel( MtlsProvider provider, CertificateBasedAccess certificateBasedAccess)