Repository navigation
Expand file tree
/
Copy pathMtlsUtils.java
More file actions
739 lines (688 loc) · 30.9 KB
/
Copy pathMtlsUtils.java
File metadata and controls
739 lines (688 loc) · 30.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
/*
* 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.collect.ImmutableList;
import com.google.common.io.BaseEncoding;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.X509Certificate;
import java.security.spec.X509EncodedKeySpec;
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";
private static final byte[] VERIFICATION_DATA =
"verification-data".getBytes(StandardCharsets.UTF_8);
/**
* Well-known directory where workload SPIFFE credentials and certificate configurations are
* delivered at container startup.
*/
@InternalApi
public static final String WELL_KNOWN_SPIFFE_DIR =
"/var/run/secrets/workload-spiffe-credentials/";
/**
* Alternate well-known directory path where workload SPIFFE credentials and certificate
* configurations may be mounted (for example, when {@code /run/secrets} is mounted directly or
* referenced via resolved {@code /run} paths).
*/
@InternalApi
public static final String WELL_KNOWN_RUN_SPIFFE_DIR =
"/run/secrets/workload-spiffe-credentials/";
private static final ImmutableList<Path> DEFAULT_WELL_KNOWN_SPIFFE_DIRS =
ImmutableList.of(
Paths.get(WELL_KNOWN_SPIFFE_DIR).toAbsolutePath().normalize(),
Paths.get(WELL_KNOWN_RUN_SPIFFE_DIR).toAbsolutePath().normalize());
/**
* 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 =
WELL_KNOWN_SPIFFE_DIR + "x509.credential-bundle.private-key.pem";
// Polling configuration for initial container startup credential file readiness when
// GOOGLE_API_CERTIFICATE_CONFIG and its referenced cert/key files reside in the well-known
// SPIFFE directory (50 * 100ms + 50 * 500ms = 30 seconds total).
private static final int FAST_POLL_CYCLES = 50;
private static final long FAST_POLL_INTERVAL_MS = 100; // 0.1 seconds
private static final long SLOW_POLL_INTERVAL_MS = 500; // 0.5 seconds
private static final long TOTAL_TIMEOUT_MS = 30000; // 30 seconds
/** Total startup polling timeout in seconds (30s). */
@InternalApi public static final long STARTUP_POLL_TIMEOUT_SECONDS = TOTAL_TIMEOUT_MS / 1000;
private static final int TOTAL_POLL_CYCLES =
FAST_POLL_CYCLES
+ (int)
((TOTAL_TIMEOUT_MS - (FAST_POLL_CYCLES * FAST_POLL_INTERVAL_MS))
/ SLOW_POLL_INTERVAL_MS);
// Overridable via setGkeCredentialBundlePathForTesting so unit tests can point to a temp file.
private static volatile String gkeCredentialBundlePath = GKE_CREDENTIAL_BUNDLE_PATH;
// Overridable via setWellKnownSpiffeDirForTesting so unit tests can point to a temp directory.
private static volatile String wellKnownSpiffeDir = WELL_KNOWN_SPIFFE_DIR;
private static volatile TimeService timeService = Thread::sleep;
/**
* Functional interface for sleeping during startup credential polling. Overridable for testing.
*/
@InternalApi
@VisibleForTesting
@FunctionalInterface
public interface TimeService {
void sleep(long millis) throws InterruptedException;
}
private MtlsUtils() {
// Prevent instantiation for Utility class
}
private static long getSleepIntervalMs(int cycle) {
return (cycle < FAST_POLL_CYCLES) ? FAST_POLL_INTERVAL_MS : SLOW_POLL_INTERVAL_MS;
}
/**
* Overrides the well-known SPIFFE directory path for testing; {@code null} restores the default.
*/
@VisibleForTesting
static void setWellKnownSpiffeDirForTesting(@Nullable String dir) {
wellKnownSpiffeDir = dir != null ? dir : WELL_KNOWN_SPIFFE_DIR;
}
/** Overrides the sleep service for testing; {@code null} restores {@code Thread::sleep}. */
@VisibleForTesting
static void setTimeServiceForTesting(@Nullable TimeService service) {
timeService = service != null ? service : Thread::sleep;
}
/**
* Verifies that {@code privateKey} corresponds to the public key in {@code cert} by performing a
* test signature and verification ({@code SHA256withRSA} for RSA keys, {@code SHA256withECDSA}
* for EC/ECDSA keys).
*
* <p>Certificates with key algorithms other than RSA, EC, or ECDSA return without error so
* callers that accept any JCA key algorithm (such as {@link MtlsKeyStoreUtils}) pass through
* unchanged.
*
* @param cert the X.509 certificate whose public key is checked
* @param privateKey the private key to verify against {@code cert}
* @throws GeneralSecurityException if {@code privateKey} does not match {@code cert}'s public
* key, or if signature initialization, signing, or verification fails
*/
@InternalApi
public static void verifyKeyPair(X509Certificate cert, PrivateKey privateKey)
throws GeneralSecurityException {
PublicKey publicKey = cert.getPublicKey();
String keyAlgorithm = publicKey.getAlgorithm();
String sigAlg;
if ("RSA".equals(keyAlgorithm)) {
sigAlg = "SHA256withRSA";
} else if ("EC".equals(keyAlgorithm) || "ECDSA".equals(keyAlgorithm)) {
sigAlg = "SHA256withECDSA";
} else {
return;
}
if ("ECDSA".equals(keyAlgorithm) && publicKey.getEncoded() != null) {
// SunEC rejects keys whose algorithm is "ECDSA" rather than "EC"; normalize the key.
publicKey =
KeyFactory.getInstance("EC")
.generatePublic(new X509EncodedKeySpec(publicKey.getEncoded()));
}
Signature signer = Signature.getInstance(sigAlg);
signer.initSign(privateKey);
signer.update(VERIFICATION_DATA);
byte[] signature = signer.sign();
Signature verifier = Signature.getInstance(sigAlg);
verifier.initVerify(publicKey);
verifier.update(VERIFICATION_DATA);
boolean matches;
try {
matches = verifier.verify(signature);
} catch (SignatureException e) {
throw new GeneralSecurityException("Certificate and private key do not match", e);
}
if (!matches) {
throw new GeneralSecurityException("Certificate and private key do not match");
}
}
/**
* Checks whether {@code pathStr} resides within {@code targetWellKnownDir} (or either of the
* default well-known SPIFFE directories {@link #WELL_KNOWN_SPIFFE_DIR} and {@link
* #WELL_KNOWN_RUN_SPIFFE_DIR} when {@code targetWellKnownDir} is {@link #WELL_KNOWN_SPIFFE_DIR}).
*/
@InternalApi
public static boolean isPathInWellKnownDir(@Nullable String pathStr, String targetWellKnownDir) {
if (Strings.isNullOrEmpty(pathStr) || Strings.isNullOrEmpty(targetWellKnownDir)) {
return false;
}
try {
Path path = Paths.get(pathStr).toAbsolutePath().normalize();
if (WELL_KNOWN_SPIFFE_DIR.equals(targetWellKnownDir)) {
for (Path defaultDir : DEFAULT_WELL_KNOWN_SPIFFE_DIRS) {
if (path.startsWith(defaultDir)) {
return true;
}
}
return false;
}
Path wellKnown = Paths.get(targetWellKnownDir).toAbsolutePath().normalize();
return path.startsWith(wellKnown);
} catch (Exception e) {
return false;
}
}
private static boolean isNonEmptyReadableFile(File file) {
return file.isFile() && file.canRead() && file.length() > 0;
}
private static boolean isExistingNonFileOrUnreadable(File file) {
Path path = file.toPath();
try {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
if (!attrs.isRegularFile()) {
return true;
}
return !Files.isReadable(path) && Files.exists(path);
} catch (AccessDeniedException e) {
return true;
} catch (IOException e) {
return false;
}
}
/**
* Polls up to 30 seconds when {@code configFile} and its referenced {@code cert_path} and {@code
* key_path} reside within {@code targetWellKnownDir} until the configuration and referenced
* certificate/key files are non-empty readable files, or a non-retryable state is encountered.
*
* @return {@code true} if startup polling was active for {@code configFile}, {@code false}
* otherwise
* @throws IOException if the thread is interrupted while sleeping during startup polling
*/
@InternalApi
public static boolean waitForWorkloadConfigStartupIfNeeded(
File configFile,
String targetWellKnownDir,
TimeService sleepService,
@Nullable Runnable onFirstPollSleep)
throws IOException {
boolean shouldPoll = isPathInWellKnownDir(configFile.getPath(), targetWellKnownDir);
try {
waitForExplicitConfigStartupIfNeeded(
configFile, targetWellKnownDir, sleepService, onFirstPollSleep);
} catch (InterruptedIOException e) {
throw new IOException(
"Interrupted while waiting for Agent Identity certificate files for bound"
+ " token request.",
e.getCause() != null ? e.getCause() : e);
} catch (Exception ignored) {
// Non-retryable parse or config errors are handled by the caller's single-pass evaluation.
}
return shouldPoll;
}
/**
* Polls up to 30 seconds when {@code configFile} and its referenced {@code cert_path} and {@code
* key_path} reside within the well-known SPIFFE directory until the configuration and referenced
* certificate/key files are non-empty readable files.
*/
private static @Nullable WorkloadCertificateConfiguration waitForExplicitConfigStartupIfNeeded(
File configFile) throws IOException {
return waitForExplicitConfigStartupIfNeeded(configFile, wellKnownSpiffeDir, timeService, null);
}
private static @Nullable WorkloadCertificateConfiguration waitForExplicitConfigStartupIfNeeded(
File configFile,
String targetWellKnownDir,
TimeService sleepService,
@Nullable Runnable onFirstPollSleep)
throws IOException {
boolean shouldPoll = isPathInWellKnownDir(configFile.getPath(), targetWellKnownDir);
int maxCycles = shouldPoll ? TOTAL_POLL_CYCLES : 1;
boolean warned = false;
for (int cycle = 0; cycle < maxCycles; cycle++) {
if (isExistingNonFileOrUnreadable(configFile)) {
// Directory or permission denied on an existing file will not resolve via startup polling.
break;
}
if (isNonEmptyReadableFile(configFile)) {
try (InputStream certConfigStream = new FileInputStream(configFile)) {
WorkloadCertificateConfiguration config =
WorkloadCertificateConfiguration.fromCertificateConfigurationStream(certConfigStream);
if (!shouldPoll) {
return config;
}
File certFile = new File(config.getCertPath());
File keyFile = new File(config.getPrivateKeyPath());
if (isExistingNonFileOrUnreadable(certFile) || isExistingNonFileOrUnreadable(keyFile)) {
// Referenced certificate or key is a directory or unreadable; fail without polling.
break;
}
if (isNonEmptyReadableFile(certFile) && isNonEmptyReadableFile(keyFile)) {
return config;
}
if (!isPathInWellKnownDir(config.getCertPath(), targetWellKnownDir)
|| !isPathInWellKnownDir(config.getPrivateKeyPath(), targetWellKnownDir)) {
// Startup polling only applies when the config file AND its referenced cert_path and
// key_path all reside within the well-known directory.
break;
}
} catch (CertificateSourceUnavailableException e) {
// Valid JSON without a workload section (e.g. ECP configuration); do not poll.
throw e;
} catch (IllegalArgumentException | ClassCastException e) {
// Valid JSON missing or mistyped cert_configs, cert_path, or key_path; do not poll.
throw e;
} catch (Exception e) {
if (!shouldPoll) {
if (e instanceof IOException) {
throw (IOException) e;
}
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new IOException(e);
}
// When polling in the well-known SPIFFE directory, retry on transient partial JSON
// writes (which may throw IOException or NullPointerException at EOF in JsonParser).
}
}
if (cycle + 1 < maxCycles) {
if (shouldPoll && !warned && onFirstPollSleep != null) {
onFirstPollSleep.run();
warned = true;
}
try {
sleepService.sleep(getSleepIntervalMs(cycle));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
InterruptedIOException interrupted =
new InterruptedIOException(
"Interrupted while waiting for workload certificate configuration at "
+ configFile.getPath());
interrupted.initCause(e);
throw interrupted;
}
}
}
return null;
}
/**
* 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;
}
private static boolean isUseClientCertificateExplicitlyDisabled(
@Nullable String useClientCertificate) {
return !Strings.isNullOrEmpty(useClientCertificate)
&& !"true".equalsIgnoreCase(useClientCertificate);
}
/**
* 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 (set to a non-empty value other than "true").
*/
public static boolean useMtlsClientCertificate(
EnvironmentProvider envProvider, PropertyProvider propProvider) {
String rawVal = envProvider.getEnv("GOOGLE_API_USE_CLIENT_CERTIFICATE");
String useClientCertificate = rawVal != null ? rawVal.trim() : null;
if (isUseClientCertificateExplicitlyDisabled(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} (any non-empty value other than
* {@code "true"}), 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 rawVal = envProvider.getEnv("GOOGLE_API_USE_CLIENT_CERTIFICATE");
String useClientCertificate = rawVal != null ? rawVal.trim() : null;
if (isUseClientCertificateExplicitlyDisabled(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);
WorkloadCertificateConfiguration config = null;
try {
config = waitForExplicitConfigStartupIfNeeded(configFile);
} 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);
}
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
+ "'.");
}
if (config == null) {
try (InputStream certConfigStream = new FileInputStream(configFile)) {
config =
WorkloadCertificateConfiguration.fromCertificateConfigurationStream(certConfigStream);
} 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 (!isNonEmptyReadableFile(certFile) || !isNonEmptyReadableFile(keyFile)) {
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;
boolean isExplicitConfig = false;
if (certConfigPathOverride != null) {
certConfig = new File(certConfigPathOverride);
isExplicitConfig = true;
} else {
String envCredentialsPath = envProvider.getEnv(CERTIFICATE_CONFIGURATION_ENV_VARIABLE);
if (!Strings.isNullOrEmpty(envCredentialsPath)) {
certConfig = new File(envCredentialsPath);
isExplicitConfig = true;
} else {
certConfig = getWellKnownCertificateConfigFile(envProvider, propProvider);
}
}
String rawUseClientCert = envProvider.getEnv("GOOGLE_API_USE_CLIENT_CERTIFICATE");
String useClientCert = rawUseClientCert != null ? rawUseClientCert.trim() : null;
if (isExplicitConfig && !isUseClientCertificateExplicitlyDisabled(useClientCert)) {
WorkloadCertificateConfiguration polledConfig =
waitForExplicitConfigStartupIfNeeded(certConfig);
if (polledConfig != null) {
return polledConfig;
}
}
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);
}
}