|
| 1 | +/* |
| 2 | + * Copyright 2026 Google LLC |
| 3 | + * |
| 4 | + * Redistribution and use in source and binary forms, with or without |
| 5 | + * modification, are permitted provided that the following conditions are |
| 6 | + * met: |
| 7 | + * |
| 8 | + * * Redistributions of source code must retain the above copyright |
| 9 | + * notice, this list of conditions and the following disclaimer. |
| 10 | + * * Redistributions in binary form must reproduce the above |
| 11 | + * copyright notice, this list of conditions and the following disclaimer |
| 12 | + * in the documentation and/or other materials provided with the |
| 13 | + * distribution. |
| 14 | + * * Neither the name of Google LLC nor the names of its |
| 15 | + * contributors may be used to endorse or promote products derived from |
| 16 | + * this software without specific prior written permission. |
| 17 | + * |
| 18 | + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 19 | + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 20 | + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 21 | + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 22 | + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 24 | + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 25 | + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 26 | + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 27 | + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 28 | + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 | + */ |
| 30 | +package com.google.api.gax.httpjson; |
| 31 | + |
| 32 | +import static com.google.common.truth.Truth.assertThat; |
| 33 | +import static org.junit.jupiter.api.Assumptions.assumeTrue; |
| 34 | + |
| 35 | +import com.google.api.client.http.GenericUrl; |
| 36 | +import com.google.api.client.http.HttpResponse; |
| 37 | +import com.google.api.client.http.HttpTransport; |
| 38 | +import com.google.api.client.util.SecurityUtils; |
| 39 | +import com.google.api.gax.rpc.mtls.CertificateBasedAccess; |
| 40 | +import com.google.api.gax.rpc.testing.FakeMtlsProvider; |
| 41 | +import java.io.BufferedReader; |
| 42 | +import java.io.File; |
| 43 | +import java.io.FileOutputStream; |
| 44 | +import java.io.InputStream; |
| 45 | +import java.io.InputStreamReader; |
| 46 | +import java.io.OutputStream; |
| 47 | +import java.net.InetAddress; |
| 48 | +import java.nio.charset.StandardCharsets; |
| 49 | +import java.security.KeyStore; |
| 50 | +import java.security.cert.CertificateFactory; |
| 51 | +import java.security.cert.X509Certificate; |
| 52 | +import java.util.concurrent.ExecutorService; |
| 53 | +import java.util.concurrent.Executors; |
| 54 | +import java.util.concurrent.Future; |
| 55 | +import java.util.concurrent.TimeUnit; |
| 56 | +import javax.net.ssl.KeyManagerFactory; |
| 57 | +import javax.net.ssl.SSLContext; |
| 58 | +import javax.net.ssl.SSLServerSocket; |
| 59 | +import javax.net.ssl.SSLSocket; |
| 60 | +import javax.net.ssl.TrustManager; |
| 61 | +import javax.net.ssl.X509TrustManager; |
| 62 | +import org.junit.jupiter.api.AfterEach; |
| 63 | +import org.junit.jupiter.api.BeforeEach; |
| 64 | +import org.junit.jupiter.api.Test; |
| 65 | +import org.junit.jupiter.api.io.TempDir; |
| 66 | +import org.mockito.Mockito; |
| 67 | + |
| 68 | +/** |
| 69 | + * Handshake test for the Conscrypt-backed mTLS {@link HttpTransport} built by {@link |
| 70 | + * InstantiatingHttpJsonChannelProvider}. |
| 71 | + * |
| 72 | + * <p>Regression test for "Unknown authType: GENERIC": on TLS 1.3, Conscrypt passes the authType |
| 73 | + * {@code "GENERIC"} to its trust manager. If the trust manager comes from the JDK (SunJSSE) rather |
| 74 | + * than Conscrypt, it rejects server certificates that are issued by a trusted CA and carry a |
| 75 | + * KeyUsage extension (as Google front ends' certificates do), and every mTLS HTTP/JSON handshake |
| 76 | + * fails. A self-signed server certificate that is itself the trust anchor does not reproduce the |
| 77 | + * issue, so the server here presents a CA-issued leaf with KeyUsage. |
| 78 | + * |
| 79 | + * <p>The transport always uses the default trust store, so this test points {@code |
| 80 | + * javax.net.ssl.trustStore} at a temporary store containing only the test CA, and restores the |
| 81 | + * previous value afterwards. |
| 82 | + */ |
| 83 | +class InstantiatingHttpJsonChannelProviderTls13Test { |
| 84 | + |
| 85 | + private static final String RESOURCE_DIR = "com/google/api/gax/httpjson/"; |
| 86 | + private static final String TRUST_STORE_PROPERTY = "javax.net.ssl.trustStore"; |
| 87 | + private static final String TRUST_STORE_PASSWORD_PROPERTY = "javax.net.ssl.trustStorePassword"; |
| 88 | + private static final String TRUST_STORE_PASSWORD = "changeit"; |
| 89 | + |
| 90 | + @TempDir File tempDir; |
| 91 | + |
| 92 | + private String previousTrustStore; |
| 93 | + private String previousTrustStorePassword; |
| 94 | + private ExecutorService serverExecutor; |
| 95 | + |
| 96 | + @BeforeEach |
| 97 | + void setUp() throws Exception { |
| 98 | + assumeTrue( |
| 99 | + HttpJsonConscryptUtils.getConscryptProvider() != null, |
| 100 | + "Conscrypt native library is unavailable on this platform"); |
| 101 | + assumeTrue(isTls13Supported(), "TLS 1.3 is unavailable on this JDK"); |
| 102 | + |
| 103 | + previousTrustStore = System.getProperty(TRUST_STORE_PROPERTY); |
| 104 | + previousTrustStorePassword = System.getProperty(TRUST_STORE_PASSWORD_PROPERTY); |
| 105 | + File trustStoreFile = writeTrustStoreWithTestCa(); |
| 106 | + System.setProperty(TRUST_STORE_PROPERTY, trustStoreFile.getAbsolutePath()); |
| 107 | + System.setProperty(TRUST_STORE_PASSWORD_PROPERTY, TRUST_STORE_PASSWORD); |
| 108 | + |
| 109 | + serverExecutor = Executors.newSingleThreadExecutor(); |
| 110 | + } |
| 111 | + |
| 112 | + @AfterEach |
| 113 | + void tearDown() { |
| 114 | + restoreProperty(TRUST_STORE_PROPERTY, previousTrustStore); |
| 115 | + restoreProperty(TRUST_STORE_PASSWORD_PROPERTY, previousTrustStorePassword); |
| 116 | + if (serverExecutor != null) { |
| 117 | + serverExecutor.shutdownNow(); |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + @Test |
| 122 | + void createHttpTransport_withMtlsAndConscrypt_completesTls13HandshakeWithCaIssuedServerCert() |
| 123 | + throws Exception { |
| 124 | + CertificateBasedAccess certificateBasedAccess = Mockito.mock(CertificateBasedAccess.class); |
| 125 | + Mockito.when(certificateBasedAccess.useMtlsClientCertificate()).thenReturn(true); |
| 126 | + InstantiatingHttpJsonChannelProvider channelProvider = |
| 127 | + InstantiatingHttpJsonChannelProvider.newBuilder() |
| 128 | + .setEndpoint("localhost:443") |
| 129 | + .setMtlsProvider( |
| 130 | + new FakeMtlsProvider(FakeMtlsProvider.createTestMtlsKeyStore(), "", false)) |
| 131 | + .setCertificateBasedAccess(certificateBasedAccess) |
| 132 | + .build(); |
| 133 | + HttpTransport transport = channelProvider.createHttpTransport(); |
| 134 | + assertThat(transport).isNotNull(); |
| 135 | + |
| 136 | + final SSLServerSocket serverSocket = createTls13ServerSocket(); |
| 137 | + try { |
| 138 | + Future<Boolean> clientCertificatePresented = |
| 139 | + serverExecutor.submit(() -> serveSingleRequest(serverSocket)); |
| 140 | + |
| 141 | + HttpResponse response = |
| 142 | + transport |
| 143 | + .createRequestFactory() |
| 144 | + .buildGetRequest( |
| 145 | + new GenericUrl("https://localhost:" + serverSocket.getLocalPort() + "/")) |
| 146 | + .execute(); |
| 147 | + try { |
| 148 | + assertThat(response.getStatusCode()).isEqualTo(200); |
| 149 | + assertThat(response.parseAsString()).isEqualTo("ok"); |
| 150 | + } finally { |
| 151 | + response.disconnect(); |
| 152 | + } |
| 153 | + assertThat(clientCertificatePresented.get(10, TimeUnit.SECONDS)).isTrue(); |
| 154 | + } finally { |
| 155 | + serverSocket.close(); |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + /** Accepts one connection, answers one HTTP request, and reports if a client cert was sent. */ |
| 160 | + private static boolean serveSingleRequest(SSLServerSocket serverSocket) throws Exception { |
| 161 | + SSLSocket socket = (SSLSocket) serverSocket.accept(); |
| 162 | + try { |
| 163 | + socket.startHandshake(); |
| 164 | + boolean clientCertificatePresented = socket.getSession().getPeerCertificates().length > 0; |
| 165 | + BufferedReader reader = |
| 166 | + new BufferedReader( |
| 167 | + new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII)); |
| 168 | + String line; |
| 169 | + while ((line = reader.readLine()) != null && !line.isEmpty()) { |
| 170 | + // Drain request headers. |
| 171 | + } |
| 172 | + OutputStream out = socket.getOutputStream(); |
| 173 | + out.write( |
| 174 | + ("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") |
| 175 | + .getBytes(StandardCharsets.US_ASCII)); |
| 176 | + out.flush(); |
| 177 | + return clientCertificatePresented; |
| 178 | + } finally { |
| 179 | + socket.close(); |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + /** |
| 184 | + * Creates a JDK TLS 1.3 server that presents a CA-issued leaf certificate with KeyUsage and |
| 185 | + * requires (but does not validate) a client certificate. |
| 186 | + */ |
| 187 | + private static SSLServerSocket createTls13ServerSocket() throws Exception { |
| 188 | + KeyStore serverKeyStore; |
| 189 | + InputStream certAndKey = openResource("tls13TestServerCertAndKey.pem"); |
| 190 | + try { |
| 191 | + serverKeyStore = SecurityUtils.createMtlsKeyStore(certAndKey); |
| 192 | + } finally { |
| 193 | + certAndKey.close(); |
| 194 | + } |
| 195 | + KeyManagerFactory keyManagerFactory = |
| 196 | + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); |
| 197 | + keyManagerFactory.init(serverKeyStore, new char[0]); |
| 198 | + |
| 199 | + SSLContext serverContext = SSLContext.getInstance("TLSv1.3"); |
| 200 | + serverContext.init( |
| 201 | + keyManagerFactory.getKeyManagers(), new TrustManager[] {new AcceptAllTrustManager()}, null); |
| 202 | + SSLServerSocket serverSocket = |
| 203 | + (SSLServerSocket) |
| 204 | + serverContext |
| 205 | + .getServerSocketFactory() |
| 206 | + .createServerSocket(0, 1, InetAddress.getLoopbackAddress()); |
| 207 | + serverSocket.setEnabledProtocols(new String[] {"TLSv1.3"}); |
| 208 | + serverSocket.setNeedClientAuth(true); |
| 209 | + return serverSocket; |
| 210 | + } |
| 211 | + |
| 212 | + private File writeTrustStoreWithTestCa() throws Exception { |
| 213 | + X509Certificate caCertificate; |
| 214 | + InputStream caPem = openResource("tls13TestCa.pem"); |
| 215 | + try { |
| 216 | + caCertificate = |
| 217 | + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(caPem); |
| 218 | + } finally { |
| 219 | + caPem.close(); |
| 220 | + } |
| 221 | + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); |
| 222 | + trustStore.load(null, null); |
| 223 | + trustStore.setCertificateEntry("gax-test-ca", caCertificate); |
| 224 | + File trustStoreFile = new File(tempDir, "truststore"); |
| 225 | + OutputStream out = new FileOutputStream(trustStoreFile); |
| 226 | + try { |
| 227 | + trustStore.store(out, TRUST_STORE_PASSWORD.toCharArray()); |
| 228 | + } finally { |
| 229 | + out.close(); |
| 230 | + } |
| 231 | + return trustStoreFile; |
| 232 | + } |
| 233 | + |
| 234 | + private static InputStream openResource(String name) { |
| 235 | + InputStream stream = |
| 236 | + InstantiatingHttpJsonChannelProviderTls13Test.class |
| 237 | + .getClassLoader() |
| 238 | + .getResourceAsStream(RESOURCE_DIR + name); |
| 239 | + if (stream == null) { |
| 240 | + throw new IllegalStateException("Missing test resource: " + RESOURCE_DIR + name); |
| 241 | + } |
| 242 | + return stream; |
| 243 | + } |
| 244 | + |
| 245 | + private static boolean isTls13Supported() { |
| 246 | + try { |
| 247 | + SSLContext.getInstance("TLSv1.3"); |
| 248 | + return true; |
| 249 | + } catch (Exception e) { |
| 250 | + return false; |
| 251 | + } |
| 252 | + } |
| 253 | + |
| 254 | + private static void restoreProperty(String key, String value) { |
| 255 | + if (value == null) { |
| 256 | + System.clearProperty(key); |
| 257 | + } else { |
| 258 | + System.setProperty(key, value); |
| 259 | + } |
| 260 | + } |
| 261 | + |
| 262 | + /** Server-side trust manager: the test only checks that a client certificate is presented. */ |
| 263 | + private static final class AcceptAllTrustManager implements X509TrustManager { |
| 264 | + @Override |
| 265 | + public void checkClientTrusted(X509Certificate[] chain, String authType) {} |
| 266 | + |
| 267 | + @Override |
| 268 | + public void checkServerTrusted(X509Certificate[] chain, String authType) {} |
| 269 | + |
| 270 | + @Override |
| 271 | + public X509Certificate[] getAcceptedIssuers() { |
| 272 | + return new X509Certificate[0]; |
| 273 | + } |
| 274 | + } |
| 275 | +} |
0 commit comments