-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathchanges.diff
More file actions
3373 lines (3276 loc) · 143 KB
/
changes.diff
File metadata and controls
3373 lines (3276 loc) · 143 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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git a/.gitignore b/.gitignore
index bdf3ed927..888ac8247 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,4 +16,8 @@ target/
.vscode/
# MacOS
-.DS_Store
\ No newline at end of file
+.DS_Store
+
+# Conductor and Gemini
+conductor/
+Gemini/
\ No newline at end of file
diff --git a/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java b/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java
index 5faf29fdb..6739d13f1 100644
--- a/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java
+++ b/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java
@@ -41,6 +41,7 @@
import com.google.api.client.http.HttpStatusCodes;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.GenericData;
+import com.google.api.core.InternalApi;
import com.google.auth.CredentialTypeForMetrics;
import com.google.auth.Credentials;
import com.google.auth.Retryable;
@@ -82,7 +83,7 @@
* <p>These credentials use the IAM API to sign data. See {@link #sign(byte[])} for more details.
*/
public class ComputeEngineCredentials extends GoogleCredentials
- implements ServiceAccountSigner, IdTokenProvider {
+ implements ServiceAccountSigner, IdTokenProvider, RegionalAccessBoundaryProvider {
static final String METADATA_RESPONSE_EMPTY_CONTENT_ERROR_MESSAGE =
"Empty content from metadata token server request.";
@@ -385,7 +386,6 @@ public AccessToken refreshAccessToken() throws IOException {
int expiresInSeconds =
OAuth2Utils.validateInt32(responseData, "expires_in", PARSE_ERROR_PREFIX);
long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000;
-
return new AccessToken(accessToken, new Date(expiresAtMilliseconds));
}
@@ -690,6 +690,11 @@ public static Builder newBuilder() {
*
* @throws RuntimeException if the default service account cannot be read
*/
+ @Override
+ HttpTransportFactory getTransportFactory() {
+ return transportFactory;
+ }
+
@Override
// todo(#314) getAccount should not throw a RuntimeException
public String getAccount() {
@@ -703,6 +708,13 @@ public String getAccount() {
return principal;
}
+ @InternalApi
+ @Override
+ public String getRegionalAccessBoundaryUrl() throws IOException {
+ return String.format(
+ OAuth2Utils.IAM_CREDENTIALS_ALLOWED_LOCATIONS_URL_FORMAT_SERVICE_ACCOUNT, getAccount());
+ }
+
/**
* Signs the provided bytes using the private key associated with the service account.
*
diff --git a/oauth2_http/java/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentials.java b/oauth2_http/java/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentials.java
index e67ddb89d..bc812984d 100644
--- a/oauth2_http/java/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentials.java
+++ b/oauth2_http/java/com/google/auth/oauth2/ExternalAccountAuthorizedUserCredentials.java
@@ -31,7 +31,9 @@
package com.google.auth.oauth2;
+import static com.google.auth.oauth2.OAuth2Utils.IAM_CREDENTIALS_ALLOWED_LOCATIONS_URL_FORMAT_WORKFORCE_POOL;
import static com.google.auth.oauth2.OAuth2Utils.JSON_FACTORY;
+import static com.google.auth.oauth2.OAuth2Utils.WORKFORCE_AUDIENCE_PATTERN;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.api.client.http.GenericUrl;
@@ -44,6 +46,7 @@
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Preconditions;
+import com.google.api.core.InternalApi;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.base.MoreObjects;
import com.google.common.io.BaseEncoding;
@@ -55,6 +58,7 @@
import java.util.Date;
import java.util.Map;
import java.util.Objects;
+import java.util.regex.Matcher;
import javax.annotation.Nullable;
/**
@@ -75,12 +79,12 @@
* }
* </pre>
*/
-public class ExternalAccountAuthorizedUserCredentials extends GoogleCredentials {
+public class ExternalAccountAuthorizedUserCredentials extends GoogleCredentials
+ implements RegionalAccessBoundaryProvider {
private static final String PARSE_ERROR_PREFIX = "Error parsing token refresh response. ";
private static final long serialVersionUID = -2181779590486283287L;
-
private final String transportFactoryClassName;
private final String audience;
private final String tokenUrl;
@@ -216,6 +220,24 @@ public AccessToken refreshAccessToken() throws IOException {
.build();
}
+ @InternalApi
+ @Override
+ public String getRegionalAccessBoundaryUrl() throws IOException {
+ Matcher matcher = WORKFORCE_AUDIENCE_PATTERN.matcher(getAudience());
+ if (!matcher.matches()) {
+ throw new IllegalStateException(
+ "The provided audience is not in the correct format for a workforce pool. "
+ + "Refer: https://docs.cloud.google.com/iam/docs/principal-identifiers");
+ }
+ String poolId = matcher.group("pool");
+ return String.format(IAM_CREDENTIALS_ALLOWED_LOCATIONS_URL_FORMAT_WORKFORCE_POOL, poolId);
+ }
+
+ @Override
+ HttpTransportFactory getTransportFactory() {
+ return transportFactory;
+ }
+
@Nullable
public String getAudience() {
return audience;
diff --git a/oauth2_http/java/com/google/auth/oauth2/ExternalAccountCredentials.java b/oauth2_http/java/com/google/auth/oauth2/ExternalAccountCredentials.java
index c4268d167..12e387357 100644
--- a/oauth2_http/java/com/google/auth/oauth2/ExternalAccountCredentials.java
+++ b/oauth2_http/java/com/google/auth/oauth2/ExternalAccountCredentials.java
@@ -31,12 +31,15 @@
package com.google.auth.oauth2;
+import static com.google.auth.oauth2.OAuth2Utils.WORKFORCE_AUDIENCE_PATTERN;
+import static com.google.auth.oauth2.OAuth2Utils.WORKLOAD_AUDIENCE_PATTERN;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.Data;
+import com.google.api.core.InternalApi;
import com.google.auth.RequestMetadataCallback;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.base.MoreObjects;
@@ -55,6 +58,7 @@
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Executor;
+import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
@@ -64,7 +68,8 @@
* <p>Handles initializing external credentials, calls to the Security Token Service, and service
* account impersonation.
*/
-public abstract class ExternalAccountCredentials extends GoogleCredentials {
+public abstract class ExternalAccountCredentials extends GoogleCredentials
+ implements RegionalAccessBoundaryProvider {
private static final long serialVersionUID = 8049126194174465023L;
@@ -570,6 +575,11 @@ protected AccessToken exchangeExternalCredentialForAccessToken(
*/
public abstract String retrieveSubjectToken() throws IOException;
+ @Override
+ HttpTransportFactory getTransportFactory() {
+ return transportFactory;
+ }
+
public String getAudience() {
return audience;
}
@@ -613,6 +623,37 @@ public String getServiceAccountEmail() {
return ImpersonatedCredentials.extractTargetPrincipal(serviceAccountImpersonationUrl);
}
+ @InternalApi
+ @Override
+ public String getRegionalAccessBoundaryUrl() throws IOException {
+ if (getServiceAccountEmail() != null) {
+ return String.format(
+ OAuth2Utils.IAM_CREDENTIALS_ALLOWED_LOCATIONS_URL_FORMAT_SERVICE_ACCOUNT,
+ getServiceAccountEmail());
+ }
+
+ Matcher workforceMatcher = WORKFORCE_AUDIENCE_PATTERN.matcher(getAudience());
+ if (workforceMatcher.matches()) {
+ String poolId = workforceMatcher.group("pool");
+ return String.format(
+ OAuth2Utils.IAM_CREDENTIALS_ALLOWED_LOCATIONS_URL_FORMAT_WORKFORCE_POOL, poolId);
+ }
+
+ Matcher workloadMatcher = WORKLOAD_AUDIENCE_PATTERN.matcher(getAudience());
+ if (workloadMatcher.matches()) {
+ String projectNumber = workloadMatcher.group("project");
+ String poolId = workloadMatcher.group("pool");
+ return String.format(
+ OAuth2Utils.IAM_CREDENTIALS_ALLOWED_LOCATIONS_URL_FORMAT_WORKLOAD_POOL,
+ projectNumber,
+ poolId);
+ }
+
+ throw new IllegalStateException(
+ "The provided audience is not in a valid format for either a workload identity pool or a workforce pool."
+ + " Refer: https://docs.cloud.google.com/iam/docs/principal-identifiers");
+ }
+
@Nullable
public String getClientId() {
return clientId;
diff --git a/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java b/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java
index fbfd147f2..cbcc5801f 100644
--- a/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java
+++ b/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java
@@ -37,6 +37,8 @@
import com.google.api.client.util.Preconditions;
import com.google.api.core.ObsoleteApi;
import com.google.auth.Credentials;
+import com.google.auth.RequestMetadataCallback;
+import com.google.auth.http.AuthHttpConstants;
import com.google.auth.http.HttpTransportFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
@@ -47,6 +49,8 @@
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collection;
@@ -107,6 +111,9 @@ String getFileType() {
private final String universeDomain;
private final boolean isExplicitUniverseDomain;
+ transient RegionalAccessBoundaryManager regionalAccessBoundaryManager =
+ new RegionalAccessBoundaryManager(clock);
+
protected final String quotaProjectId;
private static final DefaultCredentialsProvider defaultCredentialsProvider =
@@ -331,6 +338,141 @@ public GoogleCredentials createWithQuotaProject(String quotaProject) {
return this.toBuilder().setQuotaProjectId(quotaProject).build();
}
+ /**
+ * Returns the currently cached regional access boundary, or null if none is available or if it
+ * has expired.
+ *
+ * @return The cached regional access boundary, or null.
+ */
+ final RegionalAccessBoundary getRegionalAccessBoundary() {
+ return regionalAccessBoundaryManager.getCachedRAB();
+ }
+
+ /**
+ * Refreshes the Regional Access Boundary if it is expired or not yet fetched.
+ *
+ * @param uri The URI of the outbound request.
+ * @param token The access token to use for the refresh.
+ * @throws IOException If getting the universe domain fails.
+ */
+ void refreshRegionalAccessBoundaryIfExpired(@Nullable URI uri, @Nullable AccessToken token)
+ throws IOException {
+ if (!(this instanceof RegionalAccessBoundaryProvider)
+ || !RegionalAccessBoundary.isEnabled()
+ || !isDefaultUniverseDomain()) {
+ return;
+ }
+
+ // Skip refresh for regional endpoints.
+ if (uri != null && uri.getHost() != null) {
+ String host = uri.getHost();
+ if (host.endsWith(".rep.googleapis.com") || host.endsWith(".rep.sandbox.googleapis.com")) {
+ return;
+ }
+ }
+
+ // We need a valid access token for the refresh.
+ if (token == null
+ || (token.getExpirationTimeMillis() != null
+ && token.getExpirationTimeMillis() < clock.currentTimeMillis())) {
+ return;
+ }
+
+ HttpTransportFactory transportFactory = getTransportFactory();
+ if (transportFactory == null) {
+ return;
+ }
+
+ regionalAccessBoundaryManager.triggerAsyncRefresh(
+ transportFactory, (RegionalAccessBoundaryProvider) this, token);
+ }
+
+ /**
+ * Extracts the self-signed JWT from the request metadata and triggers a Regional Access Boundary
+ * refresh if expired.
+ *
+ * @param uri The URI of the outbound request.
+ * @param requestMetadata The request metadata containing the authorization header.
+ */
+ void refreshRegionalAccessBoundaryWithSelfSignedJwtIfExpired(
+ @Nullable URI uri, Map<String, List<String>> requestMetadata) {
+ List<String> authHeaders = requestMetadata.get(AuthHttpConstants.AUTHORIZATION);
+ if (authHeaders != null && !authHeaders.isEmpty()) {
+ String authHeader = authHeaders.get(0);
+ if (authHeader.startsWith(AuthHttpConstants.BEARER + " ")) {
+ String tokenValue = authHeader.substring((AuthHttpConstants.BEARER + " ").length());
+ // Use a null expiration as JWTs are short-lived anyway.
+ AccessToken wrappedToken = new AccessToken(tokenValue, null);
+ try {
+ refreshRegionalAccessBoundaryIfExpired(uri, wrappedToken);
+ } catch (IOException e) {
+ // Ignore failure in async refresh trigger.
+ }
+ }
+ }
+ }
+
+ /**
+ * Synchronously provides the request metadata.
+ *
+ * <p>This method is blocking and will wait for a token refresh if necessary. It also ensures any
+ * available Regional Access Boundary information is included in the metadata.
+ *
+ * @param uri The URI of the request.
+ * @return The request metadata containing the authorization header and potentially regional
+ * access boundary.
+ * @throws IOException If an error occurs while fetching the token.
+ */
+ @Override
+ public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException {
+ Map<String, List<String>> metadata = super.getRequestMetadata(uri);
+ metadata = addRegionalAccessBoundaryToRequestMetadata(uri, metadata);
+ try {
+ // Sets off an async refresh for request-metadata.
+ refreshRegionalAccessBoundaryIfExpired(uri, getAccessToken());
+ } catch (IOException e) {
+ // Ignore failure in async refresh trigger.
+ }
+ return metadata;
+ }
+
+ /**
+ * Asynchronously provides the request metadata.
+ *
+ * <p>This method is non-blocking. It ensures any available Regional Access Boundary information
+ * is included in the metadata.
+ *
+ * @param uri The URI of the request.
+ * @param executor The executor to use for any required background tasks.
+ * @param callback The callback to receive the metadata or any error.
+ */
+ @Override
+ public void getRequestMetadata(
+ final URI uri,
+ final java.util.concurrent.Executor executor,
+ final RequestMetadataCallback callback) {
+ super.getRequestMetadata(
+ uri,
+ executor,
+ new RequestMetadataCallback() {
+ @Override
+ public void onSuccess(Map<String, List<String>> metadata) {
+ metadata = addRegionalAccessBoundaryToRequestMetadata(uri, metadata);
+ try {
+ refreshRegionalAccessBoundaryIfExpired(uri, getAccessToken());
+ } catch (IOException e) {
+ // Ignore failure in async refresh trigger.
+ }
+ callback.onSuccess(metadata);
+ }
+
+ @Override
+ public void onFailure(Throwable exception) {
+ callback.onFailure(exception);
+ }
+ });
+ }
+
/**
* Gets the universe domain for the credential.
*
@@ -374,22 +516,59 @@ boolean isDefaultUniverseDomain() throws IOException {
static Map<String, List<String>> addQuotaProjectIdToRequestMetadata(
String quotaProjectId, Map<String, List<String>> requestMetadata) {
Preconditions.checkNotNull(requestMetadata);
- Map<String, List<String>> newRequestMetadata = new HashMap<>(requestMetadata);
if (quotaProjectId != null && !requestMetadata.containsKey(QUOTA_PROJECT_ID_HEADER_KEY)) {
- newRequestMetadata.put(
- QUOTA_PROJECT_ID_HEADER_KEY, Collections.singletonList(quotaProjectId));
+ return ImmutableMap.<String, List<String>>builder()
+ .putAll(requestMetadata)
+ .put(QUOTA_PROJECT_ID_HEADER_KEY, Collections.singletonList(quotaProjectId))
+ .build();
+ }
+ return requestMetadata;
+ }
+
+ /**
+ * Adds Regional Access Boundary header to requestMetadata if available. Overwrites if present. If
+ * the current RAB is null, it removes any stale header that might have survived serialization.
+ *
+ * @param uri The URI of the request.
+ * @param requestMetadata The request metadata.
+ * @return a new map with Regional Access Boundary header added, updated, or removed
+ */
+ Map<String, List<String>> addRegionalAccessBoundaryToRequestMetadata(
+ URI uri, Map<String, List<String>> requestMetadata) {
+ Preconditions.checkNotNull(requestMetadata);
+
+ if (uri != null && uri.getHost() != null) {
+ String host = uri.getHost();
+ if (host.endsWith(".rep.googleapis.com") || host.endsWith(".rep.sandbox.googleapis.com")) {
+ return requestMetadata;
+ }
}
- return Collections.unmodifiableMap(newRequestMetadata);
+
+ RegionalAccessBoundary rab = getRegionalAccessBoundary();
+ if (rab != null) {
+ // Overwrite the header to ensure the most recent async update is used,
+ // preventing staleness if the token itself hasn't expired yet.
+ Map<String, List<String>> newMetadata = new HashMap<>(requestMetadata);
+ newMetadata.put(
+ RegionalAccessBoundary.X_ALLOWED_LOCATIONS_HEADER_KEY,
+ Collections.singletonList(rab.getEncodedLocations()));
+ return ImmutableMap.copyOf(newMetadata);
+ } else if (requestMetadata.containsKey(RegionalAccessBoundary.X_ALLOWED_LOCATIONS_HEADER_KEY)) {
+ // If RAB is null but the header exists (e.g., from a serialized cache), we must strip it
+ // to prevent sending stale data to the server.
+ Map<String, List<String>> newMetadata = new HashMap<>(requestMetadata);
+ newMetadata.remove(RegionalAccessBoundary.X_ALLOWED_LOCATIONS_HEADER_KEY);
+ return ImmutableMap.copyOf(newMetadata);
+ }
+ return requestMetadata;
}
@Override
protected Map<String, List<String>> getAdditionalHeaders() {
- Map<String, List<String>> headers = super.getAdditionalHeaders();
+ Map<String, List<String>> headers = new HashMap<>(super.getAdditionalHeaders());
+
String quotaProjectId = this.getQuotaProjectId();
- if (quotaProjectId != null) {
- return addQuotaProjectIdToRequestMetadata(quotaProjectId, headers);
- }
- return headers;
+ return addQuotaProjectIdToRequestMetadata(quotaProjectId, headers);
}
/** Default constructor. */
@@ -500,6 +679,11 @@ public int hashCode() {
return Objects.hash(this.quotaProjectId, this.universeDomain, this.isExplicitUniverseDomain);
}
+ private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
+ input.defaultReadObject();
+ regionalAccessBoundaryManager = new RegionalAccessBoundaryManager(clock);
+ }
+
public static Builder newBuilder() {
return new Builder();
}
@@ -635,6 +819,16 @@ public Map<String, String> getCredentialInfo() {
return ImmutableMap.copyOf(infoMap);
}
+ /**
+ * Returns the transport factory used by the credential.
+ *
+ * @return the transport factory, or null if not available.
+ */
+ @Nullable
+ HttpTransportFactory getTransportFactory() {
+ return null;
+ }
+
public static class Builder extends OAuth2Credentials.Builder {
@Nullable protected String quotaProjectId;
@Nullable protected String universeDomain;
diff --git a/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java b/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java
index 18d7cd0f8..a5311eed1 100644
--- a/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java
+++ b/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java
@@ -43,6 +43,7 @@
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.GenericData;
+import com.google.api.core.InternalApi;
import com.google.auth.CredentialTypeForMetrics;
import com.google.auth.ServiceAccountSigner;
import com.google.auth.http.HttpCredentialsAdapter;
@@ -95,7 +96,7 @@
* </pre>
*/
public class ImpersonatedCredentials extends GoogleCredentials
- implements ServiceAccountSigner, IdTokenProvider {
+ implements ServiceAccountSigner, IdTokenProvider, RegionalAccessBoundaryProvider {
private static final long serialVersionUID = -2133257318957488431L;
private static final String RFC3339 = "yyyy-MM-dd'T'HH:mm:ssX";
@@ -325,10 +326,22 @@ public GoogleCredentials getSourceCredentials() {
return sourceCredentials;
}
+ @InternalApi
+ @Override
+ public String getRegionalAccessBoundaryUrl() throws IOException {
+ return String.format(
+ OAuth2Utils.IAM_CREDENTIALS_ALLOWED_LOCATIONS_URL_FORMAT_SERVICE_ACCOUNT, getAccount());
+ }
+
int getLifetime() {
return this.lifetime;
}
+ @Override
+ HttpTransportFactory getTransportFactory() {
+ return transportFactory;
+ }
+
public void setTransportFactory(HttpTransportFactory httpTransportFactory) {
this.transportFactory = httpTransportFactory;
}
diff --git a/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java b/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java
index dfeb5966a..0835f6dd7 100644
--- a/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java
+++ b/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java
@@ -59,7 +59,6 @@
import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
-import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import javax.annotation.Nullable;
@@ -164,6 +163,16 @@ Duration getExpirationMargin() {
return this.expirationMargin;
}
+ /**
+ * Asynchronously provides the request metadata by ensuring there is a current access token and
+ * providing it as an authorization bearer token.
+ *
+ * <p>This method is non-blocking. The results are provided through the given callback.
+ *
+ * @param uri The URI of the request.
+ * @param executor The executor to use for any required background tasks.
+ * @param callback The callback to receive the metadata or any error.
+ */
@Override
public void getRequestMetadata(
final URI uri, Executor executor, final RequestMetadataCallback callback) {
@@ -175,8 +184,14 @@ public void getRequestMetadata(
}
/**
- * Provide the request metadata by ensuring there is a current access token and providing it as an
- * authorization bearer token.
+ * Synchronously provides the request metadata by ensuring there is a current access token and
+ * providing it as an authorization bearer token.
+ *
+ * <p>This method is blocking and will wait for a token refresh if necessary.
+ *
+ * @param uri The URI of the request.
+ * @return The request metadata containing the authorization header.
+ * @throws IOException If an error occurs while fetching the token.
*/
@Override
public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException {
@@ -264,11 +279,8 @@ private AsyncRefreshResult getOrCreateRefreshTask() {
final ListenableFutureTask<OAuthValue> task =
ListenableFutureTask.create(
- new Callable<OAuthValue>() {
- @Override
- public OAuthValue call() throws Exception {
- return OAuthValue.create(refreshAccessToken(), getAdditionalHeaders());
- }
+ () -> {
+ return OAuthValue.create(refreshAccessToken(), getAdditionalHeaders());
});
refreshTask = new RefreshTask(task, new RefreshTaskListener(task));
@@ -373,7 +385,7 @@ public AccessToken refreshAccessToken() throws IOException {
/**
* Provide additional headers to return as request metadata.
*
- * @return additional headers
+ * @return additional headers.
*/
protected Map<String, List<String>> getAdditionalHeaders() {
return EMPTY_EXTRA_HEADERS;
diff --git a/oauth2_http/java/com/google/auth/oauth2/OAuth2Utils.java b/oauth2_http/java/com/google/auth/oauth2/OAuth2Utils.java
index 21278e8b6..425023adb 100644
--- a/oauth2_http/java/com/google/auth/oauth2/OAuth2Utils.java
+++ b/oauth2_http/java/com/google/auth/oauth2/OAuth2Utils.java
@@ -68,6 +68,7 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.regex.Pattern;
/**
* Internal utilities for the com.google.auth.oauth2 namespace.
@@ -117,6 +118,22 @@ public class OAuth2Utils {
static final double RETRY_MULTIPLIER = 2;
static final int DEFAULT_NUMBER_OF_RETRIES = 3;
+ static final Pattern WORKFORCE_AUDIENCE_PATTERN =
+ Pattern.compile(
+ "^//iam.googleapis.com/locations/(?<location>[^/]+)/workforcePools/(?<pool>[^/]+)/providers/(?<provider>[^/]+)$");
+ static final Pattern WORKLOAD_AUDIENCE_PATTERN =
+ Pattern.compile(
+ "^//iam.googleapis.com/projects/(?<project>[^/]+)/locations/(?<location>[^/]+)/workloadIdentityPools/(?<pool>[^/]+)/providers/(?<provider>[^/]+)$");
+
+ static final String IAM_CREDENTIALS_ALLOWED_LOCATIONS_URL_FORMAT_SERVICE_ACCOUNT =
+ "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/%s/allowedLocations";
+
+ static final String IAM_CREDENTIALS_ALLOWED_LOCATIONS_URL_FORMAT_WORKFORCE_POOL =
+ "https://iamcredentials.googleapis.com/v1/locations/global/workforcePools/%s/allowedLocations";
+
+ static final String IAM_CREDENTIALS_ALLOWED_LOCATIONS_URL_FORMAT_WORKLOAD_POOL =
+ "https://iamcredentials.googleapis.com/v1/projects/%s/locations/global/workloadIdentityPools/%s/allowedLocations";
+
// Includes expected server errors from Google token endpoint
// Other 5xx codes are either not used or retries are unlikely to succeed
public static final Set<Integer> TOKEN_ENDPOINT_RETRYABLE_STATUS_CODES =
diff --git a/oauth2_http/java/com/google/auth/oauth2/RegionalAccessBoundary.java b/oauth2_http/java/com/google/auth/oauth2/RegionalAccessBoundary.java
new file mode 100644
index 000000000..b2a3f4294
--- /dev/null
+++ b/oauth2_http/java/com/google/auth/oauth2/RegionalAccessBoundary.java
@@ -0,0 +1,280 @@
+/*
+ * 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.oauth2;
+
+import com.google.api.client.http.GenericUrl;
+import com.google.api.client.http.HttpBackOffIOExceptionHandler;
+import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
+import com.google.api.client.http.HttpIOExceptionHandler;
+import com.google.api.client.http.HttpRequest;
+import com.google.api.client.http.HttpRequestFactory;
+import com.google.api.client.http.HttpResponse;
+import com.google.api.client.http.HttpUnsuccessfulResponseHandler;
+import com.google.api.client.json.GenericJson;
+import com.google.api.client.json.JsonParser;
+import com.google.api.client.util.Clock;
+import com.google.api.client.util.ExponentialBackOff;
+import com.google.api.client.util.Key;
+import com.google.auth.http.HttpTransportFactory;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.MoreObjects;
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.Serializable;
+import java.util.Collections;
+import java.util.List;
+import javax.annotation.Nullable;
+
+/**
+ * Represents the regional access boundary configuration for a credential. This class holds the
+ * information retrieved from the IAM `allowedLocations` endpoint. This data is then used to
+ * populate the `x-allowed-locations` header in outgoing API requests, which in turn allows Google's
+ * infrastructure to enforce regional security restrictions. This class does not perform any
+ * client-side validation or enforcement.
+ */
+final class RegionalAccessBoundary implements Serializable {
+
+ static final String X_ALLOWED_LOCATIONS_HEADER_KEY = "x-allowed-locations";
+ private static final long serialVersionUID = -2428522338274020302L;
+
+ // Note: this is for internal testing use use only.
+ // TODO: Fix unit test mocks so this can be removed
+ // Refer -> https://github.com/googleapis/google-auth-library-java/issues/1898
+ static final String ENABLE_EXPERIMENT_ENV_VAR = "GOOGLE_AUTH_TRUST_BOUNDARY_ENABLE_EXPERIMENT";
+ static final long TTL_MILLIS = 6 * 60 * 60 * 1000L; // 6 hours
+ static final long REFRESH_THRESHOLD_MILLIS = 1 * 60 * 60 * 1000L; // 1 hour
+
+ private final String encodedLocations;
+ private final List<String> locations;
+ private final long refreshTime;
+ private transient Clock clock;
+
+ private static EnvironmentProvider environmentProvider = SystemEnvironmentProvider.getInstance();
+
+ /**
+ * Creates a new RegionalAccessBoundary instance.
+ *
+ * @param encodedLocations The encoded string representation of the allowed locations.
+ * @param locations A list of human-readable location strings.
+ * @param clock The clock used to set the creation time.
+ */
+ RegionalAccessBoundary(String encodedLocations, List<String> locations, Clock clock) {
+ this(
+ encodedLocations,
+ locations,
+ clock != null ? clock.currentTimeMillis() : Clock.SYSTEM.currentTimeMillis(),
+ clock);
+ }
+
+ /**
+ * Internal constructor for testing and manual creation with refresh time.
+ *
+ * @param encodedLocations The encoded string representation of the allowed locations.
+ * @param locations A list of human-readable location strings.
+ * @param refreshTime The time at which the information was last refreshed.
+ * @param clock The clock to use for expiration checks.
+ */
+ RegionalAccessBoundary(
+ String encodedLocations, List<String> locations, long refreshTime, Clock clock) {
+ this.encodedLocations = encodedLocations;
+ this.locations =
+ locations == null
+ ? Collections.<String>emptyList()
+ : Collections.unmodifiableList(locations);
+ this.refreshTime = refreshTime;
+ this.clock = clock != null ? clock : Clock.SYSTEM;
+ }
+
+ /** Returns the encoded string representation of the allowed locations. */
+ public String getEncodedLocations() {
+ return encodedLocations;
+ }
+
+ /** Returns a list of human-readable location strings. */
+ public List<String> getLocations() {
+ return locations;
+ }
+
+ /**
+ * Checks if the regional access boundary data is expired.
+ *
+ * @return True if the data has expired based on the TTL, false otherwise.
+ */
+ public boolean isExpired() {
+ return clock.currentTimeMillis() > refreshTime + TTL_MILLIS;
+ }
+
+ /**
+ * Checks if the regional access boundary data should be refreshed. This is a "soft-expiry" check
+ * that allows for background refreshes before the data actually expires.
+ *
+ * @return True if the data is within the refresh threshold, false otherwise.
+ */
+ public boolean shouldRefresh() {
+ return clock.currentTimeMillis() > refreshTime + (TTL_MILLIS - REFRESH_THRESHOLD_MILLIS);
+ }
+
+ /** Represents the JSON response from the regional access boundary endpoint. */
+ public static class RegionalAccessBoundaryResponse extends GenericJson {
+ @Key("encodedLocations")
+ private String encodedLocations;
+
+ @Key("locations")
+ private List<String> locations;
+
+ /** Returns the encoded string representation of the allowed locations from the API response. */
+ public String getEncodedLocations() {
+ return encodedLocations;
+ }
+
+ /** Returns a list of human-readable location strings from the API response. */
+ public List<String> getLocations() {
+ return locations;
+ }
+
+ @Override
+ /** Returns a string representation of the RegionalAccessBoundaryResponse. */
+ public String toString() {
+ return MoreObjects.toStringHelper(this)
+ .add("encodedLocations", encodedLocations)
+ .add("locations", locations)
+ .toString();
+ }
+ }
+
+ @VisibleForTesting
+ static void setEnvironmentProviderForTest(@Nullable EnvironmentProvider provider) {
+ environmentProvider = provider == null ? SystemEnvironmentProvider.getInstance() : provider;
+ }
+
+ /**
+ * Checks if the regional access boundary feature is enabled. The feature is enabled if the
+ * environment variable or system property "GOOGLE_AUTH_TRUST_BOUNDARY_ENABLE_EXPERIMENT" is set
+ * to "true" or "1" (case-insensitive).
+ *
+ * @return True if the regional access boundary feature is enabled, false otherwise.
+ */
+ static boolean isEnabled() {
+ String enabled = environmentProvider.getEnv(ENABLE_EXPERIMENT_ENV_VAR);
+ if (enabled == null) {
+ enabled = System.getProperty(ENABLE_EXPERIMENT_ENV_VAR);
+ }
+ if (enabled == null) {
+ return false;
+ }
+ String lowercased = enabled.toLowerCase();
+ return "true".equals(lowercased) || "1".equals(enabled);
+ }
+
+ /**
+ * Refreshes the regional access boundary by making a network call to the lookup endpoint.
+ *
+ * @param transportFactory The HTTP transport factory to use for the network request.
+ * @param url The URL of the regional access boundary endpoint.
+ * @param accessToken The access token to authenticate the request.
+ * @param clock The clock to use for expiration checks.
+ * @param maxRetryElapsedTimeMillis The max duration to wait for retries.
+ * @return A new RegionalAccessBoundary object containing the refreshed information.
+ * @throws IllegalArgumentException If the provided access token is null or expired.
+ * @throws IOException If a network error occurs or the response is malformed.
+ */
+ static RegionalAccessBoundary refresh(
+ HttpTransportFactory transportFactory,
+ String url,
+ AccessToken accessToken,
+ Clock clock,
+ int maxRetryElapsedTimeMillis)
+ throws IOException {
+ Preconditions.checkNotNull(accessToken, "The provided access token is null.");
+ if (accessToken.getExpirationTimeMillis() != null
+ && accessToken.getExpirationTimeMillis() < clock.currentTimeMillis()) {
+ throw new IllegalArgumentException("The provided access token is expired.");
+ }
+
+ HttpRequestFactory requestFactory = transportFactory.create().createRequestFactory();
+ HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(url));
+ request.getHeaders().setAuthorization("Bearer " + accessToken.getTokenValue());
+
+ // Add retry logic
+ ExponentialBackOff backoff =
+ new ExponentialBackOff.Builder()
+ .setInitialIntervalMillis(OAuth2Utils.INITIAL_RETRY_INTERVAL_MILLIS)
+ .setRandomizationFactor(OAuth2Utils.RETRY_RANDOMIZATION_FACTOR)
+ .setMultiplier(OAuth2Utils.RETRY_MULTIPLIER)
+ .setMaxElapsedTimeMillis(maxRetryElapsedTimeMillis)
+ .build();
+
+ HttpUnsuccessfulResponseHandler unsuccessfulResponseHandler =
+ new HttpBackOffUnsuccessfulResponseHandler(backoff)
+ .setBackOffRequired(
+ response -> {
+ int statusCode = response.getStatusCode();
+ return statusCode == 500
+ || statusCode == 502
+ || statusCode == 503
+ || statusCode == 504;
+ });
+ request.setUnsuccessfulResponseHandler(unsuccessfulResponseHandler);
+
+ HttpIOExceptionHandler ioExceptionHandler = new HttpBackOffIOExceptionHandler(backoff);
+ request.setIOExceptionHandler(ioExceptionHandler);
+
+ RegionalAccessBoundaryResponse json;
+ try {
+ HttpResponse response = request.execute();
+ String responseString = response.parseAsString();
+ JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(responseString);
+ json = parser.parseAndClose(RegionalAccessBoundaryResponse.class);
+ } catch (IOException e) {
+ throw new IOException(
+ "RegionalAccessBoundary: Failure while getting regional access boundaries:", e);
+ }
+ String encodedLocations = json.getEncodedLocations();
+ // The encodedLocations is the value attached to the x-allowed-locations header, and
+ // it should always have a value.
+ if (encodedLocations == null) {
+ throw new IOException(
+ "RegionalAccessBoundary: Malformed response from lookup endpoint - `encodedLocations` was null.");
+ }
+ return new RegionalAccessBoundary(encodedLocations, json.getLocations(), clock);
+ }
+
+ /**
+ * Initializes the transient clock to Clock.SYSTEM upon deserialization to prevent
+ * NullPointerException when evaluating expiration on deserialized objects.
+ */
+ private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
+ input.defaultReadObject();
+ clock = Clock.SYSTEM;
+ }
+}
diff --git a/oauth2_http/java/com/google/auth/oauth2/RegionalAccessBoundaryManager.java b/oauth2_http/java/com/google/auth/oauth2/RegionalAccessBoundaryManager.java
new file mode 100644
index 000000000..eeea75bc2
--- /dev/null
+++ b/oauth2_http/java/com/google/auth/oauth2/RegionalAccessBoundaryManager.java
@@ -0,0 +1,244 @@
+/*
+ * 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.oauth2;
+
+import com.google.api.client.util.Clock;
+import com.google.api.core.InternalApi;
+import com.google.auth.http.HttpTransportFactory;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.util.concurrent.SettableFuture;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.logging.Level;
+import javax.annotation.Nullable;
+
+/**
+ * Manages the lifecycle of Regional Access Boundaries (RAB) for a credential.
+ *
+ * <p>This class handles caching, asynchronous refreshing, and cooldown logic to ensure that API
+ * requests are not blocked by lookup failures and that the lookup service is not overwhelmed.
+ */
+@InternalApi
+final class RegionalAccessBoundaryManager {
+
+ private static final LoggerProvider LOGGER_PROVIDER =
+ LoggerProvider.forClazz(RegionalAccessBoundaryManager.class);
+
+ static final long INITIAL_COOLDOWN_MILLIS = 15 * 60 * 1000L; // 15 minutes
+ static final long MAX_COOLDOWN_MILLIS = 6 * 60 * 60 * 1000L; // 6 hours
+
+ /**
+ * The default maximum elapsed time in milliseconds for retrying Regional Access Boundary lookup