Repository navigation
Expand file tree
/
Copy pathMtlsUtils.java
More file actions
392 lines (369 loc) · 16.9 KB
/
Copy pathMtlsUtils.java
File metadata and controls
392 lines (369 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/*
* Copyright 2026 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.auth.mtls;
import com.google.api.core.InternalApi;
import com.google.auth.oauth2.EnvironmentProvider;
import com.google.auth.oauth2.PropertyProvider;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.io.BaseEncoding;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.Locale;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* Utility class for mTLS related operations.
*
* <p>For internal use only.
*/
@NullMarked
@InternalApi
public class MtlsUtils {
static final String CERTIFICATE_CONFIGURATION_ENV_VARIABLE = "GOOGLE_API_CERTIFICATE_CONFIG";
static final String WELL_KNOWN_CERTIFICATE_CONFIG_FILE = "certificate_config.json";
static final String CLOUDSDK_CONFIG_DIRECTORY = "gcloud";
/**
* Well-known path of the combined certificate chain and private key bundle that GKE delivers to
* pods with Agent Identity (Pod Certificates). Used as a fallback client certificate source when
* no certificate configuration file is configured or present.
*/
static final String GKE_CREDENTIAL_BUNDLE_PATH =
"/var/run/secrets/workload-spiffe-credentials/x509.credential-bundle.private-key.pem";
// Overridable via setGkeCredentialBundlePathForTesting so unit tests can point to a temp file.
private static volatile String gkeCredentialBundlePath = GKE_CREDENTIAL_BUNDLE_PATH;
private MtlsUtils() {
// Prevent instantiation for Utility class
}
/**
* Returns {@code true} if a certificate configuration is configured or present: either {@code
* GOOGLE_API_CERTIFICATE_CONFIG} is set, or the well-known gcloud {@code certificate_config.json}
* file exists. When this returns {@code true}, the GKE credential bundle fallback is not used, so
* the certificate used for mTLS and the certificate bound to tokens always come from the same
* source.
*/
public static boolean hasCertificateConfiguration(
EnvironmentProvider envProvider, PropertyProvider propProvider) {
if (!Strings.isNullOrEmpty(envProvider.getEnv(CERTIFICATE_CONFIGURATION_ENV_VARIABLE))) {
return true;
}
try {
return getWellKnownCertificateConfigFile(envProvider, propProvider).exists();
} catch (IOException e) {
// APPDATA missing on Windows, etc. No well-known configuration file.
return false;
}
}
/**
* Returns the GKE credential bundle path if no certificate configuration is configured or present
* (see {@link #hasCertificateConfiguration}) and the bundle exists and is readable; otherwise
* returns {@code null}.
*/
static @Nullable String getGkeCredentialBundlePath(
EnvironmentProvider envProvider, PropertyProvider propProvider) {
if (hasCertificateConfiguration(envProvider, propProvider)) {
return null;
}
return findGkeCredentialBundle();
}
/**
* Returns {@code true} if the GKE credential bundle at {@code path} is a readable, non-empty
* regular file.
*/
public static boolean isGkeCredentialBundleReady(String path) {
File bundle = new File(path);
return bundle.isFile() && bundle.canRead() && bundle.length() > 0;
}
/**
* Returns the GKE credential bundle path if it is a readable, non-empty regular file, otherwise
* null.
*/
private static @Nullable String findGkeCredentialBundle() {
String path = gkeCredentialBundlePath;
return isGkeCredentialBundleReady(path) ? path : null;
}
/** Overrides the GKE credential bundle path for testing; {@code null} restores the default. */
@VisibleForTesting
static void setGkeCredentialBundlePathForTesting(@Nullable String path) {
gkeCredentialBundlePath = path != null ? path : GKE_CREDENTIAL_BUNDLE_PATH;
}
/**
* Returns if mutual TLS client certificate should be used. Returns true if valid workload
* certificates are configured or if GOOGLE_API_USE_CLIENT_CERTIFICATE is explicitly set to true
* (e.g. for Enterprise Certificate Proxy or custom MtlsProviders), unless explicitly disabled via
* GOOGLE_API_USE_CLIENT_CERTIFICATE=false.
*/
public static boolean useMtlsClientCertificate(
EnvironmentProvider envProvider, PropertyProvider propProvider) {
String useClientCertificate = envProvider.getEnv("GOOGLE_API_USE_CLIENT_CERTIFICATE");
if ("false".equalsIgnoreCase(useClientCertificate)) {
return false;
}
if (getWorkloadCertPath(envProvider, propProvider) != null) {
return true;
}
return "true".equalsIgnoreCase(useClientCertificate);
}
/**
* Resolves and returns the path to the mutual TLS client certificate, or null if none should be
* used.
*
* <p>Possible outcomes:
*
* <ol>
* <li><b>Non-null {@link String} (Valid happy path):</b> A valid workload certificate
* configuration was found and both the certificate and private key files exist and are
* readable; or no certificate configuration is set or present and the GKE credential bundle
* ({@code /var/run/secrets/workload-spiffe-credentials/
* x509.credential-bundle.private-key.pem}) exists and is readable, in which case the bundle
* path is returned.
* <li><b>{@link IllegalStateException} (Invalid state - fail closed):</b> An explicit {@code
* GOOGLE_API_CERTIFICATE_CONFIG} path or an existing default well-known certificate
* configuration file is missing, unreadable, malformed, or references missing/unreadable
* certificate or private key files. This is treated as an unrecoverable misconfiguration.
* <li><b>{@code null} (Safe fallback / fail open):</b> Client certificates are explicitly
* disabled via {@code GOOGLE_API_USE_CLIENT_CERTIFICATE=false}, no explicit configuration
* is set and neither the default well-known configuration file nor a readable GKE
* credential bundle exists on disk, or the configuration specifies an non-workload source
* (e.g., ECP/PKCS11 without a {@code workload} section). Callers can proceed without
* workload certificate file polling.
* </ol>
*/
public static @Nullable String getWorkloadCertPath(
EnvironmentProvider envProvider, PropertyProvider propProvider) {
String useClientCertificate = envProvider.getEnv("GOOGLE_API_USE_CLIENT_CERTIFICATE");
if ("false".equalsIgnoreCase(useClientCertificate)) {
return null;
}
String explicitConfigPath = envProvider.getEnv(CERTIFICATE_CONFIGURATION_ENV_VARIABLE);
// 1. Explicit Configuration Path (Fail Closed)
if (!Strings.isNullOrEmpty(explicitConfigPath)) {
File configFile = new File(explicitConfigPath);
if (!configFile.exists()) {
throw new IllegalStateException(
"Certificate configuration file specified via GOOGLE_API_CERTIFICATE_CONFIG at '"
+ explicitConfigPath
+ "' does not exist.");
}
if (!configFile.isFile() || !configFile.canRead()) {
throw new IllegalStateException(
"Failed to read certificate configuration file specified via"
+ " GOOGLE_API_CERTIFICATE_CONFIG at '"
+ explicitConfigPath
+ "'.");
}
WorkloadCertificateConfiguration config;
try {
config = getWorkloadCertificateConfiguration(envProvider, propProvider, explicitConfigPath);
} catch (CertificateSourceUnavailableException e) {
// ECP / PKCS11 configuration without workload section; safe fallback
return null;
} catch (Exception e) {
throw new IllegalStateException(
"Certificate configuration file specified via GOOGLE_API_CERTIFICATE_CONFIG at '"
+ explicitConfigPath
+ "' is malformed: "
+ e.getMessage(),
e);
}
checkCertAndKeyFilesReadable(config, explicitConfigPath, false);
return config.getCertPath();
}
// 2. Implicit / Default gcloud Configuration Path
File defaultConfigFile = null;
try {
defaultConfigFile = getWellKnownCertificateConfigFile(envProvider, propProvider);
} catch (IOException e) {
// APPDATA missing on Windows, etc. Safe fallback.
}
if (defaultConfigFile != null && defaultConfigFile.exists()) {
if (!defaultConfigFile.isFile() || !defaultConfigFile.canRead()) {
throw new IllegalStateException(
"Default certificate configuration file at '"
+ defaultConfigFile.getAbsolutePath()
+ "' exists but could not be read.");
}
WorkloadCertificateConfiguration config = null;
try {
config = getWorkloadCertificateConfiguration(envProvider, propProvider, null);
} catch (CertificateSourceUnavailableException e) {
// ECP-only configuration without workload section; safe fallback
} catch (Exception e) {
throw new IllegalStateException(
"Default certificate configuration file at '"
+ defaultConfigFile.getAbsolutePath()
+ "' is malformed: "
+ e.getMessage(),
e);
}
if (config != null) {
checkCertAndKeyFilesReadable(config, defaultConfigFile.getAbsolutePath(), true);
return config.getCertPath();
}
// A default configuration file exists without a workload section (e.g. ECP); it takes
// precedence over the GKE credential bundle.
return null;
}
// 3. GKE credential bundle (Pod Certificates), used only when no certificate configuration
// file is configured or present. The combined bundle serves as both certificate and key.
return findGkeCredentialBundle();
}
private static void checkCertAndKeyFilesReadable(
WorkloadCertificateConfiguration config, String configPath, boolean isDefaultConfig) {
File certFile = new File(config.getCertPath());
File keyFile = new File(config.getPrivateKeyPath());
if (!certFile.isFile() || !certFile.canRead() || !keyFile.isFile() || !keyFile.canRead()) {
String sourcePrefix =
isDefaultConfig
? "referenced by default configuration '"
: "referenced by configuration '";
throw new IllegalStateException(
"Failed to read certificate/key file at '"
+ config.getCertPath()
+ "' or '"
+ config.getPrivateKeyPath()
+ "' "
+ sourcePrefix
+ configPath
+ "'.");
}
}
/**
* Computes the lower-case SHA-256 hex fingerprint of the certificate file at {@code certPath}.
*
* <p>Unlike {@link #getWorkloadCertPath}, which validates configuration at channel initialization
* and fails closed on errors, this method is called dynamically at runtime during active RPCs to
* detect certificate rotations on disk. External certificate rotators may temporarily delete,
* truncate, or rewrite the certificate file mid-RPC. Returning {@code null} on read/digest
* exceptions (which callers normalize to {@code ""}) allows runtime refresh checks to ignore
* transient mid-write states and keep the active healthy channel without failing in-flight RPCs.
*/
public static @Nullable String getCertificateFingerprint(@Nullable String certPath) {
if (certPath == null) {
return null;
}
try {
byte[] certBytes = Files.readAllBytes(Paths.get(certPath));
byte[] digest = MessageDigest.getInstance("SHA-256").digest(certBytes);
return BaseEncoding.base16().lowerCase().encode(digest);
} catch (Exception e) {
return null;
}
}
/**
* Returns the path to the client certificate file specified by the loaded workload certificate
* configuration.
*
* @return The path to the certificate file.
* @throws IOException if the certificate configuration cannot be found or loaded.
*/
public static String getCertificatePath(
EnvironmentProvider envProvider,
PropertyProvider propProvider,
@Nullable String certConfigPathOverride)
throws IOException {
String certPath =
getWorkloadCertificateConfiguration(envProvider, propProvider, certConfigPathOverride)
.getCertPath();
if (Strings.isNullOrEmpty(certPath)) {
throw new CertificateSourceUnavailableException(
"Certificate configuration loaded successfully, but does not contain a"
+ " 'cert_configs.workload.cert_path' path.");
}
return certPath;
}
/**
* Resolves and loads the workload certificate configuration.
*
* <p>The configuration file is resolved in the following order of precedence: 1. The provided
* certConfigPathOverride (if not null). 2. The path specified by the
* GOOGLE_API_CERTIFICATE_CONFIG environment variable. 3. The well-known certificate configuration
* file in the gcloud config directory.
*
* @param envProvider the environment provider to use for resolving environment variables
* @param propProvider the property provider to use for resolving system properties
* @param certConfigPathOverride optional override path for the configuration file
* @return the loaded WorkloadCertificateConfiguration
* @throws IOException if the configuration file cannot be found, read, or parsed
*/
static WorkloadCertificateConfiguration getWorkloadCertificateConfiguration(
EnvironmentProvider envProvider,
PropertyProvider propProvider,
@Nullable String certConfigPathOverride)
throws IOException {
File certConfig;
if (certConfigPathOverride != null) {
certConfig = new File(certConfigPathOverride);
} else {
String envCredentialsPath = envProvider.getEnv(CERTIFICATE_CONFIGURATION_ENV_VARIABLE);
if (!Strings.isNullOrEmpty(envCredentialsPath)) {
certConfig = new File(envCredentialsPath);
} else {
certConfig = getWellKnownCertificateConfigFile(envProvider, propProvider);
}
}
if (!certConfig.isFile() || !certConfig.canRead()) {
throw new CertificateSourceUnavailableException(
"Certificate configuration file does not exist or is not a file: "
+ certConfig.getAbsolutePath());
}
try (InputStream certConfigStream = new FileInputStream(certConfig)) {
return WorkloadCertificateConfiguration.fromCertificateConfigurationStream(certConfigStream);
}
}
private static File getWellKnownCertificateConfigFile(
EnvironmentProvider envProvider, PropertyProvider propProvider) throws IOException {
File cloudConfigPath;
String envPath = envProvider.getEnv("CLOUDSDK_CONFIG");
if (envPath != null) {
cloudConfigPath = new File(envPath);
} else {
String osName = propProvider.getProperty("os.name", "").toLowerCase(Locale.US);
if (osName.indexOf("windows") >= 0) {
String appData = envProvider.getEnv("APPDATA");
if (Strings.isNullOrEmpty(appData)) {
throw new CertificateSourceUnavailableException(
"APPDATA environment variable is not set on Windows.");
}
File appDataPath = new File(appData);
cloudConfigPath = new File(appDataPath, CLOUDSDK_CONFIG_DIRECTORY);
} else {
File configPath = new File(propProvider.getProperty("user.home", ""), ".config");
cloudConfigPath = new File(configPath, CLOUDSDK_CONFIG_DIRECTORY);
}
}
return new File(cloudConfigPath, WELL_KNOWN_CERTIFICATE_CONFIG_FILE);
}
}