diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 71ea9353f154..f93364778c7f 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -22,3 +22,9 @@
/librarian.yaml @googleapis/cloud-sdk-java-team @googleapis/cloud-sdk-librarian-team
/java-cloud-bom/ @googleapis/cloud-sdk-java-team
/java-shared-config/ @googleapis/cloud-sdk-java-team
+
+# Bigtable CI configs
+/.kokoro/bigtable-* @googleapis/bigtable-team @googleapis/cloud-sdk-java-team
+/.kokoro/presubmit/bigtable-* @googleapis/bigtable-team @googleapis/cloud-sdk-java-team
+/.kokoro/nightly/bigtable-* @googleapis/bigtable-team @googleapis/cloud-sdk-java-team
+/.github/workflows/java-bigtable-* @googleapis/bigtable-team @googleapis/cloud-sdk-java-team
diff --git a/.github/workflows/java-storage-nio-ci.yaml b/.github/workflows/java-storage-nio-ci.yaml
index 73c25a96b88d..a9eb1678c249 100644
--- a/.github/workflows/java-storage-nio-ci.yaml
+++ b/.github/workflows/java-storage-nio-ci.yaml
@@ -77,7 +77,12 @@ jobs:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
persist-credentials: false
- - uses: actions/setup-java@c1e323688fd81a25caa38c78aa6df2d33d3e20d9 # v4.8.0
+ - name: Cache Temurin JDK 8
+ uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
+ with:
+ path: /opt/hostedtoolcache/Java_Temurin-Hotspot_jdk/8.*
+ key: ${{ runner.os }}-temurin-jdk8
+ - uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
with:
java-version: 8
distribution: temurin
@@ -87,7 +92,7 @@ jobs:
# https://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html#jvm
run: echo "SUREFIRE_JVM_OPT=-Djvm=${JAVA_HOME}/bin/java -P !java17" >> $GITHUB_ENV
shell: bash
- - uses: actions/setup-java@c1e323688fd81a25caa38c78aa6df2d33d3e20d9 # v4.8.0
+ - uses: actions/setup-java@1bcf9fb12cf4aa7d266a90ae39939e61372fe520 # v5.4.0
with:
java-version: 17
distribution: temurin
diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml
deleted file mode 100644
index 20de49ff37ca..000000000000
--- a/.github/workflows/scorecard.yml
+++ /dev/null
@@ -1,72 +0,0 @@
-# This workflow uses actions that are not certified by GitHub. They are provided
-# by a third-party and are governed by separate terms of service, privacy
-# policy, and support documentation.
-
-name: Scorecard supply-chain security
-on:
- # For Branch-Protection check. Only the default branch is supported. See
- # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection
- branch_protection_rule:
- # To guarantee Maintained check is occasionally updated. See
- # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained
- # schedule:
- # - cron: '43 11 * * 5'
- # push:
- # branches: [ "main" ]
-
-# Declare default permissions as read only.
-permissions: read-all
-
-jobs:
- analysis:
- name: Scorecard analysis
- runs-on: ubuntu-latest
- permissions:
- # Needed to upload the results to code-scanning dashboard.
- security-events: write
- # Needed to publish results and get a badge (see publish_results below).
- id-token: write
- # Uncomment the permissions below if installing in a private repository.
- # contents: read
- # actions: read
-
- steps:
- - name: "Checkout code"
- uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # v3.1.0
- with:
- persist-credentials: false
-
- - name: "Run analysis"
- uses: ossf/scorecard-action@e38b1902ae4f44df626f11ba0734b14fb91f8f86 # v2.1.2
- with:
- results_file: results.sarif
- results_format: sarif
- # (Optional) "write" PAT token. Uncomment the `repo_token` line below if:
- # - you want to enable the Branch-Protection check on a *public* repository, or
- # - you are installing Scorecard on a *private* repository
- # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action#authentication-with-pat.
- # repo_token: ${{ secrets.SCORECARD_TOKEN }}
-
- # Public repositories:
- # - Publish results to OpenSSF REST API for easy access by consumers
- # - Allows the repository to include the Scorecard badge.
- # - See https://github.com/ossf/scorecard-action#publishing-results.
- # For private repositories:
- # - `publish_results` will always be set to `false`, regardless
- # of the value entered here.
- publish_results: true
-
- # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
- # format to the repository Actions tab.
- - name: "Upload artifact"
- uses: actions/upload-artifact@3cea5372237819ed00197afe530f5a7ea3e805c8 # v3.1.0
- with:
- name: SARIF file
- path: results.sarif
- retention-days: 5
-
- # Upload the results to GitHub's code scanning dashboard.
- - name: "Upload to code-scanning"
- uses: github/codeql-action/upload-sarif@17573ee1cc1b9d061760f3a006fc4aac4f944fd5 # v2.2.4
- with:
- sarif_file: results.sarif
diff --git a/.kokoro/presubmit/bigtable-integration-cfe.cfg b/.kokoro/presubmit/bigtable-integration-cfe.cfg
index 9e60b33c7da6..91c1d537d732 100644
--- a/.kokoro/presubmit/bigtable-integration-cfe.cfg
+++ b/.kokoro/presubmit/bigtable-integration-cfe.cfg
@@ -8,7 +8,7 @@ env_vars: {
env_vars: {
key: "INTEGRATION_TEST_ARGS"
- value: "-P bigtable-cfe-it,enable-verbose-grpc-logs -Dbigtable.project=gcloud-devel -Dbigtable.instance=google-cloud-bigtable -Dbigtable.table=integration-tests"
+ value: "-P bigtable-cfe-it,bigtable-classic-it,enable-verbose-grpc-logs -Dbigtable.project=gcloud-devel -Dbigtable.instance=google-cloud-bigtable -Dbigtable.table=integration-tests"
}
env_vars: {
diff --git a/.kokoro/presubmit/bigtable-integration-dp.cfg b/.kokoro/presubmit/bigtable-integration-dp.cfg
index a9d32aa6b83b..a6a07f7471f0 100644
--- a/.kokoro/presubmit/bigtable-integration-dp.cfg
+++ b/.kokoro/presubmit/bigtable-integration-dp.cfg
@@ -8,7 +8,7 @@ env_vars: {
env_vars: {
key: "INTEGRATION_TEST_ARGS"
- value: "-P bigtable-directpath-it,enable-verbose-grpc-logs -Dbigtable.project=gcloud-devel -Dbigtable.instance=google-cloud-bigtable -Dbigtable.table=integration-tests"
+ value: "-P bigtable-directpath-it,bigtable-classic-it,enable-verbose-grpc-logs -Dbigtable.project=gcloud-devel -Dbigtable.instance=google-cloud-bigtable -Dbigtable.table=integration-tests"
}
env_vars: {
diff --git a/.kokoro/presubmit/bigtable-integration.cfg b/.kokoro/presubmit/bigtable-integration.cfg
index 5d0f0ff7523b..24114fc19743 100644
--- a/.kokoro/presubmit/bigtable-integration.cfg
+++ b/.kokoro/presubmit/bigtable-integration.cfg
@@ -8,7 +8,7 @@ env_vars: {
env_vars: {
key: "INTEGRATION_TEST_ARGS"
- value: "-P bigtable-prod-it,enable-verbose-grpc-logs -Dbigtable.project=gcloud-devel -Dbigtable.instance=google-cloud-bigtable -Dbigtable.table=integration-tests"
+ value: "-P bigtable-prod-it,enable-verbose-grpc-logs -Dbigtable.project=gcloud-devel -Dbigtable.instance=google-cloud-bigtable -Dbigtable.table=integration-tests -Dbigtable.expected-protocol=CLASSIC"
}
env_vars: {
diff --git a/.mvn/maven.config b/.mvn/maven.config
index e2ac57dd9106..ad46e44a8de7 100644
--- a/.mvn/maven.config
+++ b/.mvn/maven.config
@@ -1,3 +1,7 @@
-Daether.remoteRepositoryFilter.prefixes=false
-Daether.remoteRepositoryFilter.groupId=false
-Daether.syncContext.named.time=900
+-Daether.connector.http.retryHandler.count=5
+-Daether.connector.http.retryHandler.interval=5000
+-Daether.connector.http.retryHandler.intervalMax=60000
+-Daether.connector.http.retryHandler.serviceUnavailable=429,502,503,504
diff --git a/google-auth-library-java/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java b/google-auth-library-java/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java
index 1e4adf96a5c8..741aa982e930 100644
--- a/google-auth-library-java/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java
+++ b/google-auth-library-java/cab-token-generator/javatests/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactoryTest.java
@@ -36,10 +36,12 @@
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.api.client.http.HttpTransport;
+import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.util.Clock;
import com.google.auth.Credentials;
import com.google.auth.TestUtils;
@@ -67,6 +69,7 @@
import java.security.GeneralSecurityException;
import java.time.Duration;
import java.util.Base64;
+import java.util.Date;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -91,17 +94,23 @@ class ClientSideCredentialAccessBoundaryFactoryTest {
static class MockStsTransportFactory implements HttpTransportFactory {
MockStsTransport transport = new MockStsTransport();
- private CountDownLatch refreshEntryLatch = new CountDownLatch(0);
+ private volatile CountDownLatch refreshEntryLatch = new CountDownLatch(0);
+ private volatile CountDownLatch refreshRequestLatch = new CountDownLatch(0);
void setRefreshEntryLatch(CountDownLatch refreshEntryLatch) {
this.refreshEntryLatch = refreshEntryLatch;
}
+ /** Sets a latch counted down once a refresh request has been issued to the mock transport. */
+ void setRefreshRequestLatch(CountDownLatch refreshRequestLatch) {
+ this.refreshRequestLatch = refreshRequestLatch;
+ }
+
@Override
public HttpTransport create() {
// Request 0 is the initial token fetch. On subsequent refresh requests (requestCount >= 1)
- // in multi-threaded tests, pause the in-flight STS request until all concurrent threads have
- // evaluated determineRefreshType() and attached to the existing refreshTask.
+ // in concurrent/async tests, pause the in-flight STS request until the test releases
+ // refreshEntryLatch, then signal refreshRequestLatch once buildRequest() has recorded it.
if (transport.getRequestCount() >= 1) {
try {
if (!refreshEntryLatch.await(5, TimeUnit.SECONDS)) {
@@ -111,6 +120,14 @@ public HttpTransport create() {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
+ return new HttpTransport() {
+ @Override
+ protected LowLevelHttpRequest buildRequest(String method, String url) {
+ LowLevelHttpRequest request = transport.buildRequest(method, url);
+ refreshRequestLatch.countDown();
+ return request;
+ }
+ };
}
return transport;
}
@@ -158,10 +175,7 @@ void fetchIntermediateCredentials() throws Exception {
@Test
void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOException {
String universeDomain = "foobar";
- GoogleCredentials sourceCredentials =
- getServiceAccountSourceCredentials(mockTokenServerTransportFactory).toBuilder()
- .setUniverseDomain(universeDomain)
- .build();
+ GoogleCredentials sourceCredentials = getCustomUniverseSourceCredentials(universeDomain);
ClientSideCredentialAccessBoundaryFactory factory =
ClientSideCredentialAccessBoundaryFactory.newBuilder()
@@ -174,7 +188,7 @@ void fetchIntermediateCredentials_withCustomUniverseDomain() throws IOException
// Verify domain.
String url = mockStsTransportFactory.transport.getRequest().getUrl();
- assertEquals(url, String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain));
+ assertEquals(String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), url);
}
@Test
@@ -282,37 +296,41 @@ void refreshCredentialsIfRequired_blockingSingleThread() throws IOException {
}
@Test
- void refreshCredentialsIfRequired_asyncSingleThread() throws IOException {
+ void refreshCredentialsIfRequired_asyncSingleThread() throws IOException, InterruptedException {
final ClientSideCredentialAccessBoundaryFactory factory =
getClientSideCredentialAccessBoundaryFactory(RefreshType.ASYNC);
+ CountDownLatch allowAsyncRefresh = new CountDownLatch(1);
+ CountDownLatch refreshCompleted = new CountDownLatch(1);
+ mockStsTransportFactory.setRefreshEntryLatch(allowAsyncRefresh);
+ mockStsTransportFactory.setRefreshRequestLatch(refreshCompleted);
// Call refreshCredentialsIfRequired() once to initialize the intermediate credentials. This
// should make one request to the STS endpoint.
factory.refreshCredentialsIfRequired();
assertEquals(1, mockStsTransportFactory.transport.getRequestCount());
- // Subsequent calls to refreshCredentialsIfRequired() in an async mode should NOT
- // immediately call the STS endpoint. They should schedule an asynchronous refresh.
- int numRefresh = 3;
- for (int i = 0; i < numRefresh; i++) {
- factory.refreshCredentialsIfRequired();
- }
-
- // Verify that only the initial call resulted in an immediate STS request. The async refresh
- // is still pending.
- assertEquals(1, mockStsTransportFactory.transport.getRequestCount());
-
- // Introduce a small delay to allow the asynchronous refresh task to complete. This is
- // necessary because the async task runs on a separate thread.
try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- throw new IOException(e);
+ // Subsequent calls to refreshCredentialsIfRequired() in an async mode should NOT
+ // immediately call the STS endpoint. They should schedule an asynchronous refresh.
+ int numRefresh = 3;
+ for (int i = 0; i < numRefresh; i++) {
+ factory.refreshCredentialsIfRequired();
+ }
+
+ // Verify that only the initial call resulted in an immediate STS request. The async refresh
+ // is still paused behind allowAsyncRefresh.
+ assertEquals(1, mockStsTransportFactory.transport.getRequestCount());
+ } finally {
+ allowAsyncRefresh.countDown();
}
- // After the delay, the request count should be 2 (initial fetch + one async refresh).
- // Subsequent calls to refreshCredentialsIfRequired() in ASYNC mode re-use the in-progress
- // refresh task, so they don't trigger additional STS requests.
+ assertTrue(
+ refreshCompleted.await(5, TimeUnit.SECONDS),
+ "Timed out waiting for asynchronous refresh request");
+
+ // After the async refresh executes, the request count should be 2 (initial fetch + one async
+ // refresh). Subsequent calls to refreshCredentialsIfRequired() in ASYNC mode re-use the
+ // in-progress refresh task, so they don't trigger additional STS requests.
assertEquals(2, mockStsTransportFactory.transport.getRequestCount());
}
@@ -354,8 +372,10 @@ void refreshCredentialsIfRequired_asyncMultiThread() throws IOException, Interru
// Wait for all 5 threads to make both clock.currentTimeMillis() calls (outside and inside
// synchronized (refreshLock)) before the background STS refresh completes.
CountDownLatch refreshEntryLatch = new CountDownLatch(numThreads * 2);
+ CountDownLatch refreshCompleted = new CountDownLatch(1);
final ClientSideCredentialAccessBoundaryFactory factory =
getClientSideCredentialAccessBoundaryFactory(RefreshType.ASYNC, refreshEntryLatch);
+ mockStsTransportFactory.setRefreshRequestLatch(refreshCompleted);
// Call refreshCredentialsIfRequired() once to initialize the intermediate credentials. This
// should make one request to the STS endpoint.
@@ -367,15 +387,12 @@ void refreshCredentialsIfRequired_asyncMultiThread() throws IOException, Interru
// trigger additional refreshes while the background refresh is still pending.
triggerConcurrentRefresh(factory, numThreads, refreshEntryLatch);
- // Introduce a small delay to allow the asynchronous refresh task to complete.
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- throw new IOException(e);
- }
+ assertTrue(
+ refreshCompleted.await(5, TimeUnit.SECONDS),
+ "Timed out waiting for asynchronous refresh request");
- // After the delay, the request count should be 2, indicating that the initial fetch and a
- // single async refresh occurred (not one per thread).
+ // After the async refresh executes, the request count should be 2, indicating that the initial
+ // fetch and a single async refresh occurred (not one per thread).
assertEquals(2, mockStsTransportFactory.transport.getRequestCount());
}
@@ -611,6 +628,17 @@ private static GoogleCredentials getServiceAccountSourceCredentials(
return sourceCredentials.createScoped("https://www.googleapis.com/auth/cloud-platform");
}
+ private static GoogleCredentials getCustomUniverseSourceCredentials(String universeDomain) {
+ return new GoogleCredentials(GoogleCredentials.newBuilder().setUniverseDomain(universeDomain)) {
+ @Override
+ public AccessToken refreshAccessToken() {
+ return new AccessToken(
+ "customUniverseAccessToken",
+ new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)));
+ }
+ };
+ }
+
private ClientSideCredentialAccessBoundaryFactory getClientSideCredentialAccessBoundaryFactory(
RefreshType refreshType) throws IOException {
return getClientSideCredentialAccessBoundaryFactory(refreshType, new CountDownLatch(0));
diff --git a/google-auth-library-java/credentials/java/com/google/auth/ApiKeyCredentials.java b/google-auth-library-java/credentials/java/com/google/auth/ApiKeyCredentials.java
index e9aad1c5c830..98c9ce551032 100644
--- a/google-auth-library-java/credentials/java/com/google/auth/ApiKeyCredentials.java
+++ b/google-auth-library-java/credentials/java/com/google/auth/ApiKeyCredentials.java
@@ -47,6 +47,20 @@
* GoogleCredentials/OAuth2Credentials, as it does not provide an access token and is not considered
* an OAuth2 credential.
*
+ *
WARNING: API keys do not carry universe domain metadata and cannot be validated
+ * against a client's configured universe domain or endpoint. When no universe domain is configured
+ * on the client, requests default to {@code googleapis.com}. Callers are solely responsible for
+ * ensuring the API key matches the client's configured universe domain, as the client will not
+ * prevent sending an API key to an unintended universe domain.
+ *
+ *
Quota project: {@code ApiKeyCredentials} does not support overriding the quota project
+ * ID. The Google Cloud project associated with the API key is used as the quota and billing
+ * project. Setting a quota project ID on the client sends {@code x-goog-user-project}, which is
+ * ignored for resource-based APIs and rejected for client-based APIs because standard API keys do
+ * not identify an IAM principal. See Set
+ * the quota project for details.
+ *
*
* Credentials credentials = ApiKeyCredentials.create("your api key");
*
@@ -60,6 +74,19 @@ public class ApiKeyCredentials extends Credentials {
this.apiKey = apiKey;
}
+ /**
+ * Creates an {@link ApiKeyCredentials} instance for the given API key.
+ *
+ *
WARNING: API keys do not carry universe domain metadata and cannot be
+ * validated against a client's configured universe domain or endpoint. Callers are solely
+ * responsible for ensuring the API key matches the client's configured universe domain (which
+ * defaults to {@code googleapis.com}), as the client will not prevent sending an API key to an
+ * unintended universe domain.
+ *
+ * @param apiKey the API key string
+ * @return the credentials instance
+ * @throws IllegalArgumentException if {@code apiKey} is null or empty
+ */
public static ApiKeyCredentials create(String apiKey) {
if (apiKey == null || apiKey.isEmpty()) {
throw new IllegalArgumentException("API key cannot be null or blank");
diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java
index 6c150079271f..c7595556d009 100644
--- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java
+++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ComputeEngineCredentials.java
@@ -881,9 +881,8 @@ public byte[] sign(byte[] toSign) {
try {
String account = getAccount();
return IamUtils.sign(
- account,
+ String.format(IamUtils.IAM_SIGN_BLOB_ENDPOINT_FORMAT, this.getUniverseDomain(), account),
this,
- this.getUniverseDomain(),
transportFactory.create(),
toSign,
Collections.emptyMap());
diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java
index 5e0325266915..9d41e0811afe 100644
--- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java
+++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java
@@ -115,25 +115,34 @@ String getCredentialName() {
/**
* Returns the credentials instance from the given access token.
*
+ *
The returned credentials default to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} ({@code
+ * googleapis.com}). Callers with an access token for a non-default universe domain should use
+ * {@link #create(String, AccessToken)} to specify the universe domain explicitly.
+ *
* @param accessToken the access token
* @return the credentials instance
*/
public static GoogleCredentials create(AccessToken accessToken) {
- return GoogleCredentials.newBuilder().setAccessToken(accessToken).build();
+ return create(null, accessToken);
}
/**
* Returns the credentials instance from the given access token and universe domain.
*
- * @param universeDomain the universe domain
+ *
If {@code universeDomain} is {@code null} or blank, the returned credentials default to
+ * {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} ({@code googleapis.com}).
+ *
+ * @param universeDomain the universe domain, or {@code null} or blank to default to {@link
+ * Credentials#GOOGLE_DEFAULT_UNIVERSE} ({@code googleapis.com})
* @param accessToken the access token
* @return the credentials instance
*/
- public static GoogleCredentials create(String universeDomain, AccessToken accessToken) {
- return GoogleCredentials.newBuilder()
- .setAccessToken(accessToken)
- .setUniverseDomain(universeDomain)
- .build();
+ public static GoogleCredentials create(@Nullable String universeDomain, AccessToken accessToken) {
+ Builder builder = GoogleCredentials.newBuilder().setAccessToken(accessToken);
+ if (universeDomain != null && !universeDomain.trim().isEmpty()) {
+ builder.setUniverseDomain(universeDomain);
+ }
+ return builder.build();
}
/**
@@ -419,11 +428,17 @@ protected GoogleCredentials() {
/**
* Constructor with an explicit access token and quotaProjectId.
*
- *
Deprecated, please use the {@link GoogleCredentials#GoogleCredentials(Builder)} constructor
- * whenever possible.
+ *
Defaults to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} ({@code googleapis.com}). Callers
+ * with an access token for a non-default universe domain should use {@link #create(String,
+ * AccessToken)} (or {@link #newBuilder()} with {@link Builder#setAccessToken(AccessToken)} and
+ * {@link Builder#setUniverseDomain(String)}) to specify the universe domain explicitly.
*
* @param accessToken initial or temporary access token
* @param quotaProjectId a quotaProjectId, a project id to be used for billing purposes
+ * @deprecated Use {@link #GoogleCredentials(Builder)} for subclasses, or {@link #newBuilder()}
+ * with {@link Builder#setAccessToken(AccessToken)} and {@link
+ * Builder#setQuotaProjectId(String)} (and {@link Builder#setUniverseDomain(String)} for a
+ * non-default universe domain).
*/
@Deprecated
protected GoogleCredentials(@Nullable AccessToken accessToken, @Nullable String quotaProjectId) {
@@ -436,7 +451,13 @@ protected GoogleCredentials(@Nullable AccessToken accessToken, @Nullable String
/**
* Constructor with explicit access token.
*
+ *
Defaults to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} ({@code googleapis.com}). Callers
+ * with an access token for a non-default universe domain should use {@link #create(String,
+ * AccessToken)} to specify the universe domain explicitly.
+ *
* @param accessToken initial or temporary access token
+ * @deprecated Use {@link #create(AccessToken)} for {@code googleapis.com}, or {@link
+ * #create(String, AccessToken)} to specify a universe domain explicitly.
*/
@Deprecated
public GoogleCredentials(AccessToken accessToken) {
@@ -467,10 +488,15 @@ protected GoogleCredentials(Builder builder) {
/**
* Constructor with explicit access token and refresh margins.
*
- *
Deprecated, please use the {@link GoogleCredentials#GoogleCredentials(Builder)} constructor
- * whenever possible.
+ *
Defaults to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} ({@code googleapis.com}). Callers
+ * with an access token for a non-default universe domain should use {@link #create(String,
+ * AccessToken)} (or {@link #newBuilder()} with {@link Builder#setAccessToken(AccessToken)} and
+ * {@link Builder#setUniverseDomain(String)}) to specify the universe domain explicitly.
*
* @param accessToken initial or temporary access token
+ * @deprecated Use {@link #GoogleCredentials(Builder)} for subclasses, or {@link #newBuilder()}
+ * with {@link Builder#setAccessToken(AccessToken)} and {@link
+ * Builder#setUniverseDomain(String)} for a non-default universe domain.
*/
@Deprecated
protected GoogleCredentials(
@@ -686,6 +712,15 @@ public Builder setQuotaProjectId(@Nullable String quotaProjectId) {
return this;
}
+ /**
+ * Sets the universe domain for the credential.
+ *
+ *
If unset, {@code null}, or blank, defaults to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}
+ * ({@code googleapis.com}).
+ *
+ * @param universeDomain the universe domain (for example, {@code googleapis.com})
+ * @return this builder
+ */
public Builder setUniverseDomain(String universeDomain) {
this.universeDomain = universeDomain;
return this;
diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java
index 3111bef92402..f47505069a30 100644
--- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java
+++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/IamUtils.java
@@ -85,7 +85,7 @@ class IamUtils {
/**
* Returns a signature for the provided bytes.
*
- * @param serviceAccountEmail the email address for the service account used for signing
+ * @param signBlobUrl the IAM signBlob endpoint for the service account used for signing
* @param credentials credentials required for making the IAM call
* @param transport transport used for building the HTTP request
* @param toSign bytes to sign
@@ -94,9 +94,8 @@ class IamUtils {
* @throws ServiceAccountSigner.SigningException if signing fails
*/
static byte[] sign(
- String serviceAccountEmail,
+ String signBlobUrl,
Credentials credentials,
- String universeDomain,
HttpTransport transport,
byte[] toSign,
Map additionalFields) {
@@ -105,13 +104,7 @@ static byte[] sign(
transport.createRequestFactory(new HttpCredentialsAdapter(credentials));
String signature;
try {
- signature =
- getSignature(
- serviceAccountEmail,
- universeDomain,
- base64.encode(toSign),
- additionalFields,
- factory);
+ signature = getSignature(signBlobUrl, base64.encode(toSign), additionalFields, factory);
} catch (IOException ex) {
throw new ServiceAccountSigner.SigningException("Failed to sign the provided bytes", ex);
}
@@ -119,14 +112,8 @@ static byte[] sign(
}
private static String getSignature(
- String serviceAccountEmail,
- String universeDomain,
- String bytes,
- Map additionalFields,
- HttpRequestFactory factory)
+ String signBlobUrl, String bytes, Map additionalFields, HttpRequestFactory factory)
throws IOException {
- String signBlobUrl =
- String.format(IAM_SIGN_BLOB_ENDPOINT_FORMAT, universeDomain, serviceAccountEmail);
GenericUrl genericUrl = new GenericUrl(signBlobUrl);
GenericData signRequest = new GenericData();
@@ -240,7 +227,8 @@ private static String getStatusMessageOrDefault(HttpResponse response) {
/**
* Returns an IdToken issued to the serviceAccount with a specified targetAudience
*
- * @param serviceAccountEmail the email address for the service account to get an ID Token for
+ * @param idTokenUrl the IAM generateIdToken endpoint for the service account to get an ID Token
+ * for
* @param credentials credentials required for making the IAM call
* @param transport transport used for building the HTTP request
* @param targetAudience the audience the issued ID token should include
@@ -252,18 +240,14 @@ private static String getStatusMessageOrDefault(HttpResponse response) {
* href="https://cloud.google.com/iam/credentials/reference/rest/v1/projects.serviceAccounts/generateIdToken">...
*/
static IdToken getIdToken(
- String serviceAccountEmail,
+ String idTokenUrl,
Credentials credentials,
HttpTransport transport,
String targetAudience,
boolean includeEmail,
Map additionalFields,
- CredentialTypeForMetrics credentialTypeForMetrics,
- String universeDomain)
+ CredentialTypeForMetrics credentialTypeForMetrics)
throws IOException {
-
- String idTokenUrl =
- String.format(IAM_ID_TOKEN_ENDPOINT_FORMAT, universeDomain, serviceAccountEmail);
GenericUrl genericUrl = new GenericUrl(idTokenUrl);
GenericData idTokenRequest = new GenericData();
diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java
index 64a8e202f989..cf3dedffa9d6 100644
--- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java
+++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ImpersonatedCredentials.java
@@ -113,6 +113,9 @@ public class ImpersonatedCredentials extends GoogleCredentials
private static final long serialVersionUID = -2133257318957488431L;
private static final int TWELVE_HOURS_IN_SECONDS = 43200;
private static final int DEFAULT_LIFETIME_IN_SECONDS = 3600;
+ private static final String GENERATE_ACCESS_TOKEN_ACTION = ":generateAccessToken";
+ private static final String SIGN_BLOB_ACTION = ":signBlob";
+ private static final String GENERATE_ID_TOKEN_ACTION = ":generateIdToken";
private volatile GoogleCredentials sourceCredentials;
private transient volatile @Nullable AccessToken cachedStsAccessToken;
private transient volatile @Nullable KeyStore cachedStsKeyStore;
@@ -367,19 +370,34 @@ public void setTransportFactory(HttpTransportFactory httpTransportFactory) {
public byte[] sign(byte[] toSign) {
try {
return IamUtils.sign(
- getAccount(),
+ getIamEndpoint(IamUtils.IAM_SIGN_BLOB_ENDPOINT_FORMAT, SIGN_BLOB_ACTION),
sourceCredentials,
- getUniverseDomain(),
transportFactory.create(),
toSign,
ImmutableMap.of("delegates", this.delegates));
} catch (IOException ex) {
// Throwing an IOException would be a breaking change, so wrap it here.
- // This should not happen for this credential type.
- throw new SigningException("Failed to sign: Error obtaining universe domain", ex);
+ throw new SigningException("Failed to sign: Error obtaining IAM endpoint", ex);
}
}
+ private String getIamEndpoint(String endpointFormat, String action) throws IOException {
+ String endpointOverride = this.iamEndpointOverride;
+ if (endpointOverride == null) {
+ return String.format(endpointFormat, getUniverseDomain(), getAccount());
+ }
+ // Falling back to the universe-domain endpoint could send source credentials to the wrong host.
+ if (!endpointOverride.endsWith(GENERATE_ACCESS_TOKEN_ACTION)) {
+ throw new IOException(
+ String.format(
+ "Invalid IAM endpoint override: %s. Expected a URL ending in %s.",
+ endpointOverride, GENERATE_ACCESS_TOKEN_ACTION));
+ }
+ return endpointOverride.substring(
+ 0, endpointOverride.length() - GENERATE_ACCESS_TOKEN_ACTION.length())
+ + action;
+ }
+
/**
* Returns credentials defined by a ImpersonatedCredential key file in JSON format from the Google
* Developers Console.
@@ -462,6 +480,7 @@ static ImpersonatedCredentials fromJson(
String quotaProjectId;
String targetPrincipal;
String serviceAccountImpersonationUrl;
+ String universeDomain;
// This applies to the scopes applied for the impersonated token and not the
// underlying source credential. Default to empty list to keep the existing
// behavior (when json file did not populate a scopes field).
@@ -474,6 +493,7 @@ static ImpersonatedCredentials fromJson(
sourceCredentialsJson = (Map) json.get("source_credentials");
sourceCredentialsType = (String) sourceCredentialsJson.get("type");
quotaProjectId = (String) json.get("quota_project_id");
+ universeDomain = (String) json.get("universe_domain");
targetPrincipal = extractTargetPrincipal(serviceAccountImpersonationUrl);
if (json.containsKey("scopes")) {
scopes = ImmutableList.copyOf((List) json.get("scopes"));
@@ -496,7 +516,19 @@ static ImpersonatedCredentials fromJson(
"A credential of type %s is not supported as source credential for impersonation.",
sourceCredentialsType));
}
- return ImpersonatedCredentials.newBuilder()
+ ImpersonatedCredentials.Builder builder = ImpersonatedCredentials.newBuilder();
+ if (universeDomain != null && !universeDomain.trim().isEmpty()) {
+ String sourceUniverseDomain = sourceCredentials.getUniverseDomain();
+ if (!universeDomain.equals(sourceUniverseDomain)) {
+ throw new IOException(
+ String.format(
+ "Universe domain %s in source credentials does not match %s universe domain"
+ + " set for impersonated credentials.",
+ sourceUniverseDomain, universeDomain));
+ }
+ builder.setUniverseDomain(universeDomain);
+ }
+ return builder
.setSourceCredentials(sourceCredentials)
.setTargetPrincipal(targetPrincipal)
.setDelegates(delegates)
@@ -900,14 +932,13 @@ public IdToken idTokenWithAudience(
boolean includeEmail =
options != null && options.contains(IdTokenProvider.Option.INCLUDE_EMAIL);
return IamUtils.getIdToken(
- getAccount(),
+ getIamEndpoint(IamUtils.IAM_ID_TOKEN_ENDPOINT_FORMAT, GENERATE_ID_TOKEN_ACTION),
sourceCredentials,
transportFactory.create(),
targetAudience,
includeEmail,
ImmutableMap.of("delegates", this.delegates),
- getMetricsCredentialType(),
- getUniverseDomain());
+ getMetricsCredentialType());
}
@Override
diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/JwtCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/JwtCredentials.java
index 6966ee3fc82f..7997d5fa6b32 100644
--- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/JwtCredentials.java
+++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/JwtCredentials.java
@@ -40,6 +40,7 @@
import com.google.common.base.Preconditions;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
+import java.io.ObjectInputStream;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
@@ -71,6 +72,9 @@
*/
@NullMarked
public class JwtCredentials extends Credentials implements JwtProvider {
+ // Matches the default computed serialVersionUID from released versions before universeDomain was
+ // added, so previously serialized JwtCredentials instances still deserialize.
+ private static final long serialVersionUID = 287345113251030847L;
private static final String JWT_ACCESS_PREFIX = OAuth2Utils.BEARER_PREFIX;
private static final String JWT_INCOMPLETE_ERROR_MESSAGE =
"JWT claims must contain audience, " + "issuer, and subject.";
@@ -82,7 +86,7 @@ public class JwtCredentials extends Credentials implements JwtProvider {
private final String privateKeyId;
private final JwtClaims jwtClaims;
private final Long lifeSpanSeconds;
- private final String universeDomain;
+ @VisibleForTesting String universeDomain;
@VisibleForTesting transient Clock clock;
private transient String jwt;
@@ -230,6 +234,17 @@ Clock getClock() {
return clock;
}
+ private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
+ input.defaultReadObject();
+ clock = Clock.SYSTEM;
+ // Java deserialization bypasses the constructor and leaves fields absent from older serialized
+ // streams as null. Normalize universeDomain here so getUniverseDomain(), equals(), and
+ // hashCode() stay consistent with newly constructed default instances.
+ if (this.universeDomain == null || this.universeDomain.trim().isEmpty()) {
+ this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE;
+ }
+ }
+
public static class Builder {
private PrivateKey privateKey;
private String privateKeyId;
diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java
index 9816a4c87bf2..180c76db206b 100644
--- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java
+++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2Credentials.java
@@ -93,6 +93,10 @@ public class OAuth2Credentials extends Credentials {
/**
* Returns the credentials instance from the given access token.
*
+ *
The returned credentials default to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. To create
+ * access-token credentials for a custom universe domain, use {@link
+ * GoogleCredentials#create(String, AccessToken)}.
+ *
* @param accessToken the access token
* @return the credentials instance
*/
@@ -559,6 +563,13 @@ public static T getFromServiceLoader(Class extends T> clazz, T defaultInst
return Iterables.getFirst(ServiceLoader.load(clazz), defaultInstance);
}
+ /**
+ * Returns a new builder for {@link OAuth2Credentials}.
+ *
+ *
Built credentials default to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. To create
+ * access-token credentials for a custom universe domain, use {@link
+ * GoogleCredentials#create(String, AccessToken)} or {@link GoogleCredentials#newBuilder()}.
+ */
public static Builder newBuilder() {
return new Builder();
}
diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java
index 91b374da5e96..d8ab23c92aec 100644
--- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java
+++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/OAuth2CredentialsWithRefresh.java
@@ -33,46 +33,58 @@
import static com.google.common.base.Preconditions.checkNotNull;
+import com.google.auth.Credentials;
+import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.util.Objects;
import org.jspecify.annotations.NullMarked;
+import org.jspecify.annotations.Nullable;
/**
* A refreshable alternative to {@link OAuth2Credentials}.
*
*
To enable automatic token refreshes, you must provide an {@link OAuth2RefreshHandler}.
+ *
+ *
Because {@link OAuth2RefreshHandler} returns {@link AccessToken} values without universe
+ * domain metadata, credentials default to {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. Callers
+ * refreshing tokens for a custom universe domain should configure it explicitly via {@link
+ * Builder#setUniverseDomain(String)}. If lazy or delegated universe domain resolution is needed,
+ * subclass this class and override {@link #getUniverseDomain()}.
*/
@NullMarked
public class OAuth2CredentialsWithRefresh extends OAuth2Credentials {
+ // Matches the computed serialVersionUID prior to adding universeDomain.
+ private static final long serialVersionUID = -5362111100740719676L;
+
/** Interface for the refresh handler. */
public interface OAuth2RefreshHandler {
AccessToken refreshAccessToken() throws IOException;
}
private final OAuth2RefreshHandler refreshHandler;
+ @VisibleForTesting String universeDomain;
protected OAuth2CredentialsWithRefresh(Builder builder) {
super(builder.getAccessToken(), builder.getRefreshMargin(), builder.getExpirationMargin());
- // An expiration time must be provided.
+ // If no expirationTime is provided, the token will never be refreshed.
if (builder.getAccessToken() != null && builder.getAccessToken().getExpirationTime() == null) {
throw new IllegalArgumentException(
"The provided access token must contain the expiration time.");
}
this.refreshHandler = checkNotNull(builder.refreshHandler);
+ if (builder.universeDomain == null || builder.universeDomain.trim().isEmpty()) {
+ this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE;
+ } else {
+ this.universeDomain = builder.universeDomain;
+ }
}
protected OAuth2CredentialsWithRefresh(
AccessToken accessToken, OAuth2RefreshHandler refreshHandler) {
- super(accessToken);
-
- // If no expirationTime is provided, the token will never be refreshed.
- if (accessToken != null && accessToken.getExpirationTime() == null) {
- throw new IllegalArgumentException(
- "The provided access token must contain the expiration time.");
- }
-
- this.refreshHandler = checkNotNull(refreshHandler);
+ this(newBuilder().setAccessToken(accessToken).setRefreshHandler(refreshHandler));
}
/** Refreshes the access token using the provided {@link OAuth2RefreshHandler}. */
@@ -87,6 +99,46 @@ public OAuth2RefreshHandler getRefreshHandler() {
return refreshHandler;
}
+ /**
+ * Returns the universe domain for this credential.
+ *
+ *
Returns the fixed universe domain configured via {@link Builder#setUniverseDomain(String)},
+ * or {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} if none was configured. Subclasses may override
+ * this method if lazy or delegated resolution is required.
+ *
+ * @return the configured universe domain, or {@link Credentials#GOOGLE_DEFAULT_UNIVERSE} if none
+ * was explicitly configured
+ * @throws IOException if a subclass fails while resolving the universe domain
+ */
+ @Override
+ public String getUniverseDomain() throws IOException {
+ return this.universeDomain;
+ }
+
+ @Override
+ public boolean equals(@Nullable Object obj) {
+ if (!(obj instanceof OAuth2CredentialsWithRefresh)) {
+ return false;
+ }
+ OAuth2CredentialsWithRefresh other = (OAuth2CredentialsWithRefresh) obj;
+ return super.equals(other)
+ && Objects.equals(this.refreshHandler, other.refreshHandler)
+ && Objects.equals(this.universeDomain, other.universeDomain);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(super.hashCode(), this.refreshHandler, this.universeDomain);
+ }
+
+ private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
+ input.defaultReadObject();
+ // Default absent or blank universeDomain from older serialized streams.
+ if (this.universeDomain == null || this.universeDomain.trim().isEmpty()) {
+ this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE;
+ }
+ }
+
public static Builder newBuilder() {
return new Builder();
}
@@ -94,6 +146,7 @@ public static Builder newBuilder() {
public static class Builder extends OAuth2Credentials.Builder {
private OAuth2RefreshHandler refreshHandler;
+ private @Nullable String universeDomain;
private Builder() {}
@@ -115,6 +168,28 @@ public Builder setRefreshHandler(OAuth2RefreshHandler handler) {
return this;
}
+ /**
+ * Sets the fixed universe domain for this credential. If null or blank, defaults to {@link
+ * Credentials#GOOGLE_DEFAULT_UNIVERSE}.
+ *
+ *
Because {@link OAuth2RefreshHandler} returns {@link AccessToken} values without universe
+ * domain metadata, callers refreshing tokens for a custom universe domain must set this
+ * explicitly.
+ *
+ * @param universeDomain the universe domain (for example, {@code googleapis.com})
+ * @return this builder
+ */
+ @CanIgnoreReturnValue
+ public Builder setUniverseDomain(@Nullable String universeDomain) {
+ this.universeDomain = universeDomain;
+ return this;
+ }
+
+ /** Returns the configured universe domain, or {@code null} if not explicitly set. */
+ public @Nullable String getUniverseDomain() {
+ return universeDomain;
+ }
+
@Override
public OAuth2CredentialsWithRefresh build() {
return new OAuth2CredentialsWithRefresh(this);
diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java
index 3c09e1c20dfa..76a66d05b46d 100644
--- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java
+++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountCredentials.java
@@ -119,6 +119,9 @@ public class ServiceAccountCredentials extends GoogleCredentials
private transient HttpTransportFactory transportFactory;
+ // Lazily cached self-signed JWT credentials for scope-based requests, where the claims are
+ // identical across requests. Reused across calls so the RSA key only signs once per expiry
+ // window (JwtCredentials handles re-signing near expiration).
private transient @Nullable JwtCredentials selfSignedJwtCredentialsWithScope = null;
/**
@@ -522,10 +525,30 @@ private GenericData parseResponseAs(HttpResponse response) throws IOException {
}
/**
- * Refreshes the OAuth2 access token by getting a new access token using a JSON Web Token (JWT).
+ * Refreshes the OAuth2 access token by exchanging a signed JWT assertion at {@code
+ * tokenServerUri}.
+ *
+ *
This method is only used for the OAuth2 access token flow (not self-signed JWT
+ * authentication, which is handled directly by {@link #getRequestMetadata(URI)} without calling
+ * this method).
+ *
+ *
OAuth2 token exchange is only supported in {@link Credentials#GOOGLE_DEFAULT_UNIVERSE}. In
+ * non-default universe domains, this method throws {@link IOException}. Use {@link
+ * #getRequestMetadata(URI)} for self-signed JWT authentication, or wrap this credential in {@link
+ * ImpersonatedCredentials} if an OAuth2 access token is required.
*/
@Override
public AccessToken refreshAccessToken() throws IOException {
+ String universeDomain = getUniverseDomain();
+ if (!Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain)) {
+ throw new IOException(
+ String.format(
+ "OAuth2 access token refresh is not supported for ServiceAccountCredentials in"
+ + " universe domain %s. Use self-signed JWT authentication via"
+ + " getRequestMetadata() or wrap this credential in ImpersonatedCredentials to"
+ + " obtain short-lived OAuth2 access tokens.",
+ universeDomain));
+ }
JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY;
long currentTime = clock.currentTimeMillis();
String assertion = createAssertion(jsonFactory, currentTime);
@@ -862,6 +885,8 @@ public byte[] sign(byte[] toSign) {
/**
* Returns a new JwtCredentials instance with modified claims.
*
+ *
The returned credentials use the same universe domain as these credentials.
+ *
* @param newClaims new claims. Any unspecified claim fields will default to the current values.
* @return new credentials
*/
@@ -874,6 +899,7 @@ public JwtCredentials jwtWithClaims(JwtClaims newClaims) {
.setPrivateKeyId(privateKeyId)
.setJwtClaims(claimsBuilder.build().merge(newClaims))
.setClock(clock)
+ .setUniverseDomain(getUniverseDomainOrThrow())
.build();
}
@@ -1035,9 +1061,21 @@ JwtCredentials createSelfSignedJwtCredentials(
.setPrivateKeyId(privateKeyId)
.setJwtClaims(claimsBuilder.build())
.setClock(clock)
+ .setUniverseDomain(getUniverseDomainOrThrow())
.build();
}
+ // Helper only to catch the checked IOException from getUniverseDomain().
+ // ServiceAccountCredentials reads universeDomain from the key file or builder, so it should not
+ // throw IOException.
+ private String getUniverseDomainOrThrow() {
+ try {
+ return getUniverseDomain();
+ } catch (IOException e) {
+ throw new IllegalStateException("Failed to retrieve universe domain.", e);
+ }
+ }
+
@Override
public void getRequestMetadata(
final URI uri, Executor executor, final RequestMetadataCallback callback) {
diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountJwtAccessCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountJwtAccessCredentials.java
index f4f2145c4cc2..f4958c9ef107 100644
--- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountJwtAccessCredentials.java
+++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/ServiceAccountJwtAccessCredentials.java
@@ -91,9 +91,11 @@ public class ServiceAccountJwtAccessCredentials extends Credentials
private final String privateKeyId;
private final URI defaultAudience;
private final String quotaProjectId;
- private final String universeDomain;
+ @VisibleForTesting String universeDomain;
- private transient LoadingCache credentialsCache;
+ // Caches one JwtCredentials per audience (JwtClaims) so each target URI signs a JWT once per
+ // token lifetime instead of re-signing with the RSA private key on every request.
+ @VisibleForTesting transient LoadingCache credentialsCache;
// Until we expose this to the users it can remain transient and non-serializable
@VisibleForTesting transient Clock clock = Clock.SYSTEM;
@@ -142,13 +144,13 @@ private ServiceAccountJwtAccessCredentials(
this.privateKey = Preconditions.checkNotNull(privateKey);
this.privateKeyId = privateKeyId;
this.defaultAudience = defaultAudience;
- this.credentialsCache = createCache();
this.quotaProjectId = quotaProjectId;
if (universeDomain == null || universeDomain.trim().isEmpty()) {
this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE;
} else {
this.universeDomain = universeDomain;
}
+ this.credentialsCache = createCache();
}
/**
@@ -311,6 +313,10 @@ public static ServiceAccountJwtAccessCredentials fromStream(
}
private LoadingCache createCache() {
+ // Bound entries to 100 audiences and expire them after LIFE_SPAN_SECS - CLOCK_SKEW (55 minutes)
+ // so idle audiences are evicted around the same time JwtCredentials would re-sign. The custom
+ // ticker reads clock (and the loader reads fields from the enclosing instance lazily on each
+ // cache miss) so tests can advance time with a fake clock.
return CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(LIFE_SPAN_SECS - CLOCK_SKEW, TimeUnit.SECONDS)
@@ -331,6 +337,7 @@ public JwtCredentials load(JwtClaims claims) throws Exception {
.setJwtClaims(claims)
.setLifeSpanSeconds(LIFE_SPAN_SECS)
.setClock(clock)
+ .setUniverseDomain(universeDomain)
.build();
}
});
@@ -339,6 +346,8 @@ public JwtCredentials load(JwtClaims claims) throws Exception {
/**
* Returns a new JwtCredentials instance with modified claims.
*
+ *
The returned credentials use the same universe domain as these credentials.
+ *
* @param newClaims new claims. Any unspecified claim fields will default to the current values.
* @return new credentials
*/
@@ -355,6 +364,7 @@ public JwtCredentials jwtWithClaims(JwtClaims newClaims) {
.setJwtClaims(claimsBuilder.build().merge(newClaims))
.setLifeSpanSeconds(LIFE_SPAN_SECS)
.setClock(clock)
+ .setUniverseDomain(universeDomain)
.build();
}
@@ -465,7 +475,13 @@ public byte[] sign(byte[] toSign) {
@Override
public int hashCode() {
return Objects.hash(
- clientId, clientEmail, privateKey, privateKeyId, defaultAudience, quotaProjectId);
+ clientId,
+ clientEmail,
+ privateKey,
+ privateKeyId,
+ defaultAudience,
+ quotaProjectId,
+ universeDomain);
}
@Override
@@ -476,6 +492,7 @@ public String toString() {
.add("privateKeyId", privateKeyId)
.add("defaultAudience", defaultAudience)
.add("quotaProjectId", quotaProjectId)
+ .add("universeDomain", universeDomain)
.toString();
}
@@ -490,12 +507,20 @@ public boolean equals(@Nullable Object obj) {
&& Objects.equals(this.privateKey, other.privateKey)
&& Objects.equals(this.privateKeyId, other.privateKeyId)
&& Objects.equals(this.defaultAudience, other.defaultAudience)
- && Objects.equals(this.quotaProjectId, other.quotaProjectId);
+ && Objects.equals(this.quotaProjectId, other.quotaProjectId)
+ && Objects.equals(this.universeDomain, other.universeDomain);
}
private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
input.defaultReadObject();
clock = Clock.SYSTEM;
+ // Java deserialization bypasses the constructor and leaves fields absent from older serialized
+ // streams as null. Normalize universeDomain here so getUniverseDomain(), equals(), and
+ // hashCode() stay consistent with newly constructed default instances.
+ if (this.universeDomain == null || this.universeDomain.trim().isEmpty()) {
+ this.universeDomain = Credentials.GOOGLE_DEFAULT_UNIVERSE;
+ }
+ // LoadingCache is transient (not serializable), so recreate an empty cache.
credentialsCache = createCache();
}
diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/Slf4jLoggingHelpers.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/Slf4jLoggingHelpers.java
index 510e54ba174b..94bcb619397e 100644
--- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/Slf4jLoggingHelpers.java
+++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/Slf4jLoggingHelpers.java
@@ -72,6 +72,7 @@ class Slf4jLoggingHelpers {
"authorization",
"subject_token",
"actor_token",
+ "access_boundary_session_key",
"id_token"));
}
diff --git a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java
index c2eb38aa490c..35d37f3d727c 100644
--- a/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java
+++ b/google-auth-library-java/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java
@@ -44,6 +44,7 @@
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.util.GenericData;
import com.google.auth.CredentialTypeForMetrics;
+import com.google.auth.Credentials;
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.oauth2.MetricsUtils.RequestType;
import com.google.common.base.MoreObjects;
@@ -137,20 +138,34 @@ static UserCredentials fromJson(Map json, HttpTransportFactory t
// currently "token_uri" is not a default field and needs to be added to json file manually
String tokenUrl = (String) json.get("token_uri");
URI tokenUri = (tokenUrl == null || tokenUrl.isEmpty()) ? null : URI.create(tokenUrl);
+ String universeDomain = (String) json.get("universe_domain");
+ if (universeDomain != null
+ && !universeDomain.trim().isEmpty()
+ && !Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain)) {
+ throw new IOException(
+ String.format(
+ "UserCredentials are not supported in universes other than %s (configured"
+ + " universe_domain: %s).",
+ Credentials.GOOGLE_DEFAULT_UNIVERSE, universeDomain));
+ }
String account = null;
if (json.containsKey("account")) {
account = (String) json.get("account");
}
- return UserCredentials.newBuilder()
- .setClientId(clientId)
- .setClientSecret(clientSecret)
- .setRefreshToken(refreshToken)
- .setAccessToken(null)
- .setHttpTransportFactory(transportFactory)
- .setTokenServerUri(tokenUri)
- .setQuotaProjectId(quotaProjectId)
- .setAccount(account)
- .build();
+ UserCredentials.Builder builder =
+ UserCredentials.newBuilder()
+ .setClientId(clientId)
+ .setClientSecret(clientSecret)
+ .setRefreshToken(refreshToken)
+ .setAccessToken(null)
+ .setHttpTransportFactory(transportFactory)
+ .setTokenServerUri(tokenUri)
+ .setQuotaProjectId(quotaProjectId)
+ .setAccount(account);
+ if (universeDomain != null && !universeDomain.trim().isEmpty()) {
+ builder.setUniverseDomain(universeDomain);
+ }
+ return builder.build();
}
/**
@@ -271,6 +286,13 @@ private GenericData doRefreshAccessToken() throws IOException {
throw new IllegalStateException(
"UserCredentials instance cannot refresh because there is no refresh token.");
}
+ String universeDomain = getUniverseDomain();
+ if (!Credentials.GOOGLE_DEFAULT_UNIVERSE.equals(universeDomain)) {
+ throw new IOException(
+ String.format(
+ "UserCredentials refresh is only supported in %s (configured universe domain: %s).",
+ Credentials.GOOGLE_DEFAULT_UNIVERSE, universeDomain));
+ }
GenericData tokenRequest = new GenericData();
tokenRequest.set("client_id", clientId);
tokenRequest.set("client_secret", clientSecret);
diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java
index e2759a292439..258e362ea0c5 100644
--- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java
+++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/DownscopedCredentialsTest.java
@@ -165,10 +165,7 @@ void refreshAccessToken() throws IOException {
void refreshAccessToken_withCustomUniverseDomain() throws IOException {
MockStsTransportFactory transportFactory = new MockStsTransportFactory();
String universeDomain = "foobar";
- GoogleCredentials sourceCredentials =
- getServiceAccountSourceCredentials(/* canRefresh= */ true).toBuilder()
- .setUniverseDomain(universeDomain)
- .build();
+ GoogleCredentials sourceCredentials = getCustomUniverseSourceCredentials(universeDomain);
DownscopedCredentials downscopedCredentials =
DownscopedCredentials.newBuilder()
@@ -192,7 +189,7 @@ void refreshAccessToken_withCustomUniverseDomain() throws IOException {
// Verify domain.
String url = transportFactory.transport.getRequest().getUrl();
- assertEquals(url, String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain));
+ assertEquals(String.format(TOKEN_EXCHANGE_URL_FORMAT, universeDomain), url);
}
@Test
@@ -350,6 +347,17 @@ private static GoogleCredentials getServiceAccountSourceCredentials(boolean canR
return sourceCredentials.createScoped(OAuth2Utils.CLOUD_PLATFORM_SCOPE);
}
+ private static GoogleCredentials getCustomUniverseSourceCredentials(String universeDomain) {
+ return new GoogleCredentials(GoogleCredentials.newBuilder().setUniverseDomain(universeDomain)) {
+ @Override
+ public AccessToken refreshAccessToken() {
+ return new AccessToken(
+ "customUniverseAccessToken",
+ new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1)));
+ }
+ };
+ }
+
private static GoogleCredentials getUserSourceCredentials() {
MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory();
transportFactory.transport.addClient("clientId", "clientSecret");
diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java
index 343eca7fbcd2..53544ded1a74 100644
--- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java
+++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/GoogleCredentialsTest.java
@@ -98,7 +98,7 @@ class GoogleCredentialsTest extends BaseSerializationTest {
private static final Collection DEFAULT_SCOPES =
Collections.unmodifiableCollection(Arrays.asList("scope3"));
private static final String GOOGLE_DEFAULT_UNIVERSE = "googleapis.com";
- private static final String TPC_UNIVERSE = "foo.bar";
+ private static final String CUSTOM_UNIVERSE = "foo.bar";
@Test
void getApplicationDefault_nullTransport_throws() {
@@ -190,13 +190,17 @@ void fromStream_serviceAccount_Universe_noToken() throws IOException {
transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN);
InputStream serviceAccountStream =
ServiceAccountCredentialsTest.writeServiceAccountStream(
- SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, TPC_UNIVERSE);
+ SA_CLIENT_ID,
+ SA_CLIENT_EMAIL,
+ SA_PRIVATE_KEY_PKCS8,
+ SA_PRIVATE_KEY_ID,
+ CUSTOM_UNIVERSE);
GoogleCredentials credentials =
GoogleCredentials.fromStream(serviceAccountStream, transportFactory);
assertNotNull(credentials);
- assertEquals(TPC_UNIVERSE, credentials.getUniverseDomain());
+ assertEquals(CUSTOM_UNIVERSE, credentials.getUniverseDomain());
assertTrue(credentials.isExplicitUniverseDomain());
credentials = credentials.createScoped(SCOPES);
credentials.getRequestMetadata(CALL_URI);
diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java
index b136f264f998..303d4f6720dc 100644
--- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java
+++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/IamUtilsTest.java
@@ -51,6 +51,14 @@ class IamUtilsTest {
private static final String CLIENT_EMAIL =
"36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com";
+ private static final String SIGN_BLOB_URL =
+ String.format(
+ IamUtils.IAM_SIGN_BLOB_ENDPOINT_FORMAT,
+ Credentials.GOOGLE_DEFAULT_UNIVERSE,
+ CLIENT_EMAIL);
+ private static final String ID_TOKEN_URL =
+ String.format(
+ IamUtils.IAM_ID_TOKEN_ENDPOINT_FORMAT, Credentials.GOOGLE_DEFAULT_UNIVERSE, CLIENT_EMAIL);
private ServiceAccountCredentials credentials;
@@ -77,9 +85,8 @@ void sign_success_noRetry() {
byte[] signature =
IamUtils.sign(
- CLIENT_EMAIL,
+ SIGN_BLOB_URL,
credentials,
- Credentials.GOOGLE_DEFAULT_UNIVERSE,
transportFactory.getTransport(),
expectedSignature,
ImmutableMap.of());
@@ -109,9 +116,8 @@ void sign_retryTwoTimes_success() {
byte[] signature =
IamUtils.sign(
- CLIENT_EMAIL,
+ SIGN_BLOB_URL,
credentials,
- Credentials.GOOGLE_DEFAULT_UNIVERSE,
transportFactory.getTransport(),
expectedSignature,
ImmutableMap.of());
@@ -146,9 +152,8 @@ void sign_retryThreeTimes_success() {
byte[] signature =
IamUtils.sign(
- CLIENT_EMAIL,
+ SIGN_BLOB_URL,
credentials,
- Credentials.GOOGLE_DEFAULT_UNIVERSE,
transportFactory.getTransport(),
expectedSignature,
ImmutableMap.of());
@@ -189,9 +194,8 @@ void sign_retryThreeTimes_exception() {
ServiceAccountSigner.SigningException.class,
() ->
IamUtils.sign(
- CLIENT_EMAIL,
+ SIGN_BLOB_URL,
credentials,
- Credentials.GOOGLE_DEFAULT_UNIVERSE,
transportFactory.getTransport(),
expectedSignature,
ImmutableMap.of()));
@@ -225,9 +229,8 @@ void sign_4xxError_noRetry_exception() {
ServiceAccountSigner.SigningException.class,
() ->
IamUtils.sign(
- CLIENT_EMAIL,
+ SIGN_BLOB_URL,
credentials,
- Credentials.GOOGLE_DEFAULT_UNIVERSE,
transportFactory.getTransport(),
expectedSignature,
ImmutableMap.of()));
@@ -262,9 +265,8 @@ void sign_4xxErrorWithEmptyBody_throwsSigningExceptionWithStatusCode() {
ServiceAccountSigner.SigningException.class,
() ->
IamUtils.sign(
- CLIENT_EMAIL,
+ SIGN_BLOB_URL,
credentials,
- Credentials.GOOGLE_DEFAULT_UNIVERSE,
transport,
new byte[] {0xD, 0xE, 0xA, 0xD},
ImmutableMap.of()));
@@ -292,14 +294,13 @@ void getIdToken_4xxErrorWithEmptyBody_throwsIOExceptionWithStatusCode() throws I
IOException.class,
() ->
IamUtils.getIdToken(
- CLIENT_EMAIL,
+ ID_TOKEN_URL,
credentials,
transport,
"https://example.com",
false,
ImmutableMap.of(),
- CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT,
- Credentials.GOOGLE_DEFAULT_UNIVERSE));
+ CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT));
assertEquals("Error code 401 trying to getIDToken: Unauthorized", exception.getMessage());
Mockito.verify(credentials, Mockito.never()).refresh();
}
@@ -320,14 +321,13 @@ void getIdToken_4xxErrorWithJsonBody_includesServerMessage() {
IOException.class,
() ->
IamUtils.getIdToken(
- CLIENT_EMAIL,
+ ID_TOKEN_URL,
credentials,
transport,
"https://example.com",
false,
ImmutableMap.of(),
- CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT,
- Credentials.GOOGLE_DEFAULT_UNIVERSE));
+ CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT));
assertEquals("Error code 403 trying to getIDToken: Permission denied", exception.getMessage());
}
@@ -347,9 +347,8 @@ void sign_4xxErrorWithEmptyStringBody_usesStatusMessage() {
ServiceAccountSigner.SigningException.class,
() ->
IamUtils.sign(
- CLIENT_EMAIL,
+ SIGN_BLOB_URL,
credentials,
- Credentials.GOOGLE_DEFAULT_UNIVERSE,
transport,
new byte[] {0xD, 0xE, 0xA, 0xD},
ImmutableMap.of()));
@@ -372,9 +371,8 @@ void sign_4xxErrorWithEmptyBodyAndNoReasonPhrase_usesFallbackMessage() {
ServiceAccountSigner.SigningException.class,
() ->
IamUtils.sign(
- CLIENT_EMAIL,
+ SIGN_BLOB_URL,
credentials,
- Credentials.GOOGLE_DEFAULT_UNIVERSE,
transport,
new byte[] {0xD, 0xE, 0xA, 0xD},
ImmutableMap.of()));
@@ -398,14 +396,13 @@ void getIdToken_4xxErrorWithEmptyBodyAndEmptyReasonPhrase_usesFallbackMessage()
IOException.class,
() ->
IamUtils.getIdToken(
- CLIENT_EMAIL,
+ ID_TOKEN_URL,
credentials,
transport,
"https://example.com",
false,
ImmutableMap.of(),
- CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT,
- Credentials.GOOGLE_DEFAULT_UNIVERSE));
+ CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT));
assertEquals(
"Error code 403 trying to getIDToken: (no error details in the response)",
exception.getMessage());
@@ -427,9 +424,8 @@ void sign_4xxErrorWithJsonBody_includesServerMessage() {
ServiceAccountSigner.SigningException.class,
() ->
IamUtils.sign(
- CLIENT_EMAIL,
+ SIGN_BLOB_URL,
credentials,
- Credentials.GOOGLE_DEFAULT_UNIVERSE,
transport,
new byte[] {0xD, 0xE, 0xA, 0xD},
ImmutableMap.of()));
@@ -457,9 +453,8 @@ void sign_4xxErrorWithJsonNullBody_usesStatusMessage() {
ServiceAccountSigner.SigningException.class,
() ->
IamUtils.sign(
- CLIENT_EMAIL,
+ SIGN_BLOB_URL,
credentials,
- Credentials.GOOGLE_DEFAULT_UNIVERSE,
transport,
new byte[] {0xD, 0xE, 0xA, 0xD},
ImmutableMap.of()));
@@ -486,9 +481,8 @@ void sign_4xxErrorWithHtmlBody_usesStatusMessage() {
ServiceAccountSigner.SigningException.class,
() ->
IamUtils.sign(
- CLIENT_EMAIL,
+ SIGN_BLOB_URL,
credentials,
- Credentials.GOOGLE_DEFAULT_UNIVERSE,
transport,
new byte[] {0xD, 0xE, 0xA, 0xD},
ImmutableMap.of()));
@@ -515,9 +509,8 @@ void sign_4xxErrorWithEmptyJsonObject_usesStatusMessage() {
ServiceAccountSigner.SigningException.class,
() ->
IamUtils.sign(
- CLIENT_EMAIL,
+ SIGN_BLOB_URL,
credentials,
- Credentials.GOOGLE_DEFAULT_UNIVERSE,
transport,
new byte[] {0xD, 0xE, 0xA, 0xD},
ImmutableMap.of()));
@@ -544,14 +537,13 @@ void getIdToken_4xxErrorWithHtmlBody_usesStatusMessage() {
IOException.class,
() ->
IamUtils.getIdToken(
- CLIENT_EMAIL,
+ ID_TOKEN_URL,
credentials,
transport,
"https://example.com",
false,
ImmutableMap.of(),
- CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT,
- Credentials.GOOGLE_DEFAULT_UNIVERSE));
+ CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT));
assertEquals("Error code 403 trying to getIDToken: Forbidden", exception.getMessage());
}
@@ -572,14 +564,13 @@ void getIdToken_4xxErrorWithJsonMissingMessage_usesStatusMessage() {
IOException.class,
() ->
IamUtils.getIdToken(
- CLIENT_EMAIL,
+ ID_TOKEN_URL,
credentials,
transport,
"https://example.com",
false,
ImmutableMap.of(),
- CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT,
- Credentials.GOOGLE_DEFAULT_UNIVERSE));
+ CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT));
assertEquals("Error code 403 trying to getIDToken: Forbidden", exception.getMessage());
}
@@ -600,14 +591,13 @@ void getIdToken_4xxErrorWithJsonEmptyMessage_usesStatusMessage() {
IOException.class,
() ->
IamUtils.getIdToken(
- CLIENT_EMAIL,
+ ID_TOKEN_URL,
credentials,
transport,
"https://example.com",
false,
ImmutableMap.of(),
- CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT,
- Credentials.GOOGLE_DEFAULT_UNIVERSE));
+ CredentialTypeForMetrics.SERVICE_ACCOUNT_CREDENTIALS_AT));
assertEquals("Error code 403 trying to getIDToken: Forbidden", exception.getMessage());
}
}
diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java
index cd33872d146c..3bdf64190dbb 100644
--- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java
+++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ImpersonatedCredentialsTest.java
@@ -46,13 +46,17 @@
import com.google.api.client.http.HttpStatusCodes;
import com.google.api.client.http.HttpTransport;
+import com.google.api.client.http.LowLevelHttpRequest;
+import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonGenerator;
import com.google.api.client.json.JsonParser;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.json.webtoken.JsonWebToken.Payload;
+import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
+import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.api.client.util.Clock;
import com.google.auth.Credentials;
import com.google.auth.ServiceAccountSigner.SigningException;
@@ -874,7 +878,7 @@ void sign_universeDomainException() throws IOException {
SigningException exception =
assertThrows(SigningException.class, () -> targetCredentials.sign(expectedSignature));
- assertEquals("Failed to sign: Error obtaining universe domain", exception.getMessage());
+ assertEquals("Failed to sign: Error obtaining IAM endpoint", exception.getMessage());
}
@Test
@@ -1596,4 +1600,153 @@ public AccessToken refreshAccessToken() {
.getRequest()
.getFirstHeaderValue("Authorization"));
}
+
+ @Test
+ void fromStream_matchingTopLevelUniverseDomain_loads() throws IOException {
+ GenericJson json = serviceAccountImpersonationJson(NONGDU_IMPERSONATION_URL);
+ setSourceUniverseDomain(json, TEST_UNIVERSE_DOMAIN);
+ json.put("universe_domain", TEST_UNIVERSE_DOMAIN);
+
+ ImpersonatedCredentials credentials =
+ ImpersonatedCredentials.fromStream(TestUtils.jsonToInputStream(json));
+
+ assertEquals(TEST_UNIVERSE_DOMAIN, credentials.getUniverseDomain());
+ assertTrue(credentials.isExplicitUniverseDomain());
+ }
+
+ @Test
+ void fromStream_topLevelUniverseDomainMismatchesUserSource_throwsIOException()
+ throws IOException {
+ // authorized_user sources always report the default universe.
+ GenericJson json =
+ buildImpersonationCredentialsJson(
+ NONGDU_IMPERSONATION_URL,
+ null,
+ null,
+ USER_ACCOUNT_CLIENT_ID,
+ USER_ACCOUNT_CLIENT_SECRET,
+ REFRESH_TOKEN,
+ IMMUTABLE_SCOPES_LIST);
+ json.put("universe_domain", TEST_UNIVERSE_DOMAIN);
+ InputStream stream = TestUtils.jsonToInputStream(json);
+
+ assertThrows(IOException.class, () -> ImpersonatedCredentials.fromStream(stream));
+ }
+
+ @Test
+ void sign_withImpersonationUrlFromStream_usesOverrideSignBlobEndpoint() throws IOException {
+ List requestedUrls = new ArrayList<>();
+ GenericJson json = serviceAccountImpersonationJson(NONGDU_IMPERSONATION_URL);
+ ImpersonatedCredentials credentials =
+ ImpersonatedCredentials.fromStream(
+ TestUtils.jsonToInputStream(json), recordingSignBlobTransportFactory(requestedUrls));
+
+ credentials.sign(new byte[] {0x1});
+
+ assertEquals(
+ Collections.singletonList(
+ String.format(
+ IamUtils.IAM_SIGN_BLOB_ENDPOINT_FORMAT,
+ TEST_UNIVERSE_DOMAIN,
+ IMPERSONATED_CLIENT_EMAIL)),
+ requestedUrls);
+ }
+
+ @Test
+ void sign_withPscImpersonationUrl_usesPscSignBlobEndpoint() throws IOException {
+ String pscUrl =
+ "https://iamcredentials-myendpoint.p.googleapis.com/v1/projects/-/serviceAccounts/"
+ + IMPERSONATED_CLIENT_EMAIL;
+ List requestedUrls = new ArrayList<>();
+ GenericJson json = serviceAccountImpersonationJson(pscUrl + ":generateAccessToken");
+ ImpersonatedCredentials credentials =
+ ImpersonatedCredentials.fromStream(
+ TestUtils.jsonToInputStream(json), recordingSignBlobTransportFactory(requestedUrls));
+
+ credentials.sign(new byte[] {0x1});
+
+ assertEquals(Collections.singletonList(pscUrl + ":signBlob"), requestedUrls);
+ }
+
+ @Test
+ void idTokenWithAudience_withImpersonationUrlFromStream_usesOverrideGenerateIdTokenEndpoint()
+ throws IOException {
+ List requestedUrls = new ArrayList<>();
+ GenericJson json = serviceAccountImpersonationJson(NONGDU_IMPERSONATION_URL);
+ ImpersonatedCredentials credentials =
+ ImpersonatedCredentials.fromStream(
+ TestUtils.jsonToInputStream(json), recordingIdTokenTransportFactory(requestedUrls));
+
+ credentials.idTokenWithAudience("https://foo.bar", null);
+
+ assertEquals(
+ Collections.singletonList(
+ String.format(
+ IamUtils.IAM_ID_TOKEN_ENDPOINT_FORMAT,
+ TEST_UNIVERSE_DOMAIN,
+ IMPERSONATED_CLIENT_EMAIL)),
+ requestedUrls);
+ }
+
+ @Test
+ void idTokenWithAudience_withBaseHostOverride_throwsIOExceptionWithoutNetworkCall()
+ throws IOException {
+ List requestedUrls = new ArrayList<>();
+ ImpersonatedCredentials credentials =
+ credentialsWithOverride(
+ "https://iamcredentials." + TEST_UNIVERSE_DOMAIN,
+ recordingIdTokenTransportFactory(requestedUrls));
+
+ assertThrows(IOException.class, () -> credentials.idTokenWithAudience("https://foo.bar", null));
+ assertEquals(Collections.emptyList(), requestedUrls);
+ }
+
+ private static GenericJson serviceAccountImpersonationJson(String impersonationUrl) {
+ return buildImpersonationCredentialsJson(impersonationUrl, null, null, Collections.emptyList());
+ }
+
+ @SuppressWarnings("unchecked")
+ private static void setSourceUniverseDomain(GenericJson json, String universeDomain) {
+ ((Map) json.get("source_credentials")).put("universe_domain", universeDomain);
+ }
+
+ private static ImpersonatedCredentials credentialsWithOverride(
+ String iamEndpointOverride, HttpTransportFactory transportFactory) throws IOException {
+ return ImpersonatedCredentials.newBuilder()
+ .setSourceCredentials(getSourceCredentials())
+ .setTargetPrincipal(IMPERSONATED_CLIENT_EMAIL)
+ .setScopes(Collections.emptyList())
+ .setIamEndpointOverride(iamEndpointOverride)
+ .setHttpTransportFactory(transportFactory)
+ .build();
+ }
+
+ private static HttpTransportFactory recordingSignBlobTransportFactory(
+ List requestedUrls) {
+ return recordingIamTransportFactory(requestedUrls, "{\"signedBlob\":\"3q2+\"}");
+ }
+
+ private static HttpTransportFactory recordingIdTokenTransportFactory(List requestedUrls) {
+ return recordingIamTransportFactory(requestedUrls, "{\"token\":\"" + STANDARD_ID_TOKEN + "\"}");
+ }
+
+ private static HttpTransportFactory recordingIamTransportFactory(
+ List requestedUrls, String responseJson) {
+ return () ->
+ new MockHttpTransport() {
+ @Override
+ public LowLevelHttpRequest buildRequest(String method, String url) {
+ requestedUrls.add(url);
+ return new MockLowLevelHttpRequest(url) {
+ @Override
+ public LowLevelHttpResponse execute() {
+ return new MockLowLevelHttpResponse()
+ .setStatusCode(HttpStatusCodes.STATUS_CODE_OK)
+ .setContentType("application/json")
+ .setContent(responseJson);
+ }
+ };
+ }
+ };
+ }
}
diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java
index 96afc0dce6e8..8a00bd8b0adf 100644
--- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java
+++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/JwtCredentialsTest.java
@@ -93,10 +93,34 @@ void serialize() throws IOException, ClassNotFoundException {
assertEquals(credentials.hashCode(), deserializedCredentials.hashCode());
assertEquals(credentials.toString(), deserializedCredentials.toString());
assertEquals(credentials.getUniverseDomain(), deserializedCredentials.getUniverseDomain());
+ verifyJwtAccess(
+ deserializedCredentials.getRequestMetadata(),
+ "some-audience",
+ "some-issuer",
+ "some-subject",
+ PRIVATE_KEY_ID);
assertSame(Clock.SYSTEM, deserializedCredentials.getClock());
}
}
+ @Test
+ void deserialize_missingOrBlankUniverseDomain_defaultsToGoogleDefaultUniverse()
+ throws IOException, ClassNotFoundException {
+ JwtCredentials expected = createTestBuilder().build();
+
+ for (String serializedUniverseDomain : Arrays.asList(null, "", " ")) {
+ JwtCredentials credentials = createTestBuilder().build();
+ credentials.universeDomain = serializedUniverseDomain;
+
+ JwtCredentials deserialized = serializeAndDeserialize(credentials);
+ assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, deserialized.getUniverseDomain());
+ assertEquals(expected, deserialized);
+ assertEquals(deserialized, expected);
+ assertEquals(expected.hashCode(), deserialized.hashCode());
+ assertEquals(expected.toString(), deserialized.toString());
+ }
+ }
+
@Test
void builder_requiresPrivateKey() {
JwtClaims claims =
diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java
index 34e66daace9c..abe21cf3ada0 100644
--- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java
+++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/LoggingTest.java
@@ -604,6 +604,7 @@ void serviceAccountCredentials_exchangeToken_masksSensitiveTokens() throws IOExc
void stsRequestHandler_exchangeToken_masksSensitiveTokens() throws IOException {
TestAppender testAppender = setupTestLogger(StsRequestHandler.class);
MockStsTransport transport = new MockStsTransport();
+ transport.setReturnAccessBoundarySessionKey(true);
StsTokenExchangeRequest tokenRequest =
StsTokenExchangeRequest.newBuilder(
@@ -643,6 +644,7 @@ void stsRequestHandler_exchangeToken_masksSensitiveTokens() throws IOException {
assertEquals("Response payload for token exchange", payloadLog.getMessage());
boolean foundAccessToken = false;
+ boolean foundSessionKey = false;
for (KeyValuePair kvp : payloadLog.getKeyValuePairs()) {
if ("access_token".equals(kvp.key)) {
foundAccessToken = true;
@@ -657,9 +659,21 @@ void stsRequestHandler_exchangeToken_masksSensitiveTokens() throws IOException {
64,
((String) kvp.value).length(),
"access_token should be masked as a SHA-256 hash (64 hex chars)");
+ } else if ("access_boundary_session_key".equals(kvp.key)) {
+ foundSessionKey = true;
+ assertNotNull(kvp.value);
+ assertNotEquals(
+ transport.getAccessBoundarySessionKey(),
+ kvp.value,
+ "access_boundary_session_key value should be masked, not logged as raw key");
+ assertEquals(
+ 64,
+ ((String) kvp.value).length(),
+ "access_boundary_session_key should be masked as a SHA-256 hash (64 hex chars)");
}
}
assertTrue(foundAccessToken);
+ assertTrue(foundSessionKey);
testAppender.stop();
}
diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java
index a6b437eabc3b..3f716dcb007a 100644
--- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java
+++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/OAuth2CredentialsWithRefreshTest.java
@@ -35,20 +35,25 @@
import static com.google.auth.oauth2.OAuth2Credentials.DEFAULT_REFRESH_MARGIN;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import com.google.auth.Credentials;
import com.google.auth.TestUtils;
import java.io.IOException;
+import java.io.Serializable;
import java.net.URI;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import org.junit.jupiter.api.Test;
/** Tests for {@link OAuth2CredentialsWithRefresh}. */
-class OAuth2CredentialsWithRefreshTest {
+class OAuth2CredentialsWithRefreshTest extends BaseSerializationTest {
private static final AccessToken ACCESS_TOKEN = new AccessToken("accessToken", new Date());
@Test
@@ -199,4 +204,205 @@ void getRequestMetadata() throws IOException {
TestUtils.assertContainsBearerToken(metadata, refreshedToken.getTokenValue());
}
+
+ private static final AccessToken REFRESHED_TOKEN =
+ new AccessToken("refreshedAccessToken", new Date());
+
+ private static final class SerializableRefreshHandler
+ implements OAuth2CredentialsWithRefresh.OAuth2RefreshHandler, Serializable {
+ private static final long serialVersionUID = 1L;
+ private final AccessToken refreshedToken;
+
+ private SerializableRefreshHandler(AccessToken refreshedToken) {
+ this.refreshedToken = refreshedToken;
+ }
+
+ @Override
+ public AccessToken refreshAccessToken() {
+ return refreshedToken;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (!(obj instanceof SerializableRefreshHandler)) {
+ return false;
+ }
+ SerializableRefreshHandler other = (SerializableRefreshHandler) obj;
+ return Objects.equals(this.refreshedToken, other.refreshedToken);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(refreshedToken);
+ }
+ }
+
+ private static OAuth2CredentialsWithRefresh.Builder createTestBuilder(
+ OAuth2CredentialsWithRefresh.OAuth2RefreshHandler handler) {
+ return OAuth2CredentialsWithRefresh.newBuilder()
+ .setAccessToken(ACCESS_TOKEN)
+ .setRefreshHandler(handler);
+ }
+
+ @Test
+ void protectedConstructor() throws IOException {
+ OAuth2CredentialsWithRefresh.OAuth2RefreshHandler handler = () -> ACCESS_TOKEN;
+ OAuth2CredentialsWithRefresh credentials =
+ new OAuth2CredentialsWithRefresh(ACCESS_TOKEN, handler);
+
+ assertEquals(ACCESS_TOKEN, credentials.getAccessToken());
+ assertEquals(handler, credentials.getRefreshHandler());
+ assertEquals(DEFAULT_REFRESH_MARGIN, credentials.getRefreshMargin());
+ assertEquals(DEFAULT_EXPIRATION_MARGIN, credentials.getExpirationMargin());
+ assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, credentials.getUniverseDomain());
+
+ assertThrows(
+ NullPointerException.class, () -> new OAuth2CredentialsWithRefresh(ACCESS_TOKEN, null));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> new OAuth2CredentialsWithRefresh(new AccessToken("accessToken", null), handler));
+ }
+
+ @Test
+ void builder_universeDomain() throws IOException {
+ OAuth2CredentialsWithRefresh.Builder builder = createTestBuilder(() -> ACCESS_TOKEN);
+ assertNull(builder.getUniverseDomain());
+
+ builder.setUniverseDomain("example.com");
+ assertEquals("example.com", builder.getUniverseDomain());
+ assertEquals("example.com", builder.build().getUniverseDomain());
+ }
+
+ @Test
+ void getUniverseDomain_defaultsToGoogleDefaultUniverse() throws IOException {
+ assertEquals(
+ Credentials.GOOGLE_DEFAULT_UNIVERSE,
+ createTestBuilder(() -> ACCESS_TOKEN).build().getUniverseDomain());
+ assertEquals(
+ Credentials.GOOGLE_DEFAULT_UNIVERSE,
+ createTestBuilder(() -> ACCESS_TOKEN).setUniverseDomain(null).build().getUniverseDomain());
+ assertEquals(
+ Credentials.GOOGLE_DEFAULT_UNIVERSE,
+ createTestBuilder(() -> ACCESS_TOKEN).setUniverseDomain("").build().getUniverseDomain());
+ assertEquals(
+ Credentials.GOOGLE_DEFAULT_UNIVERSE,
+ createTestBuilder(() -> ACCESS_TOKEN).setUniverseDomain(" ").build().getUniverseDomain());
+ }
+
+ @Test
+ void serialize() throws IOException, ClassNotFoundException {
+ SerializableRefreshHandler handler = new SerializableRefreshHandler(REFRESHED_TOKEN);
+ OAuth2CredentialsWithRefresh credentials = createTestBuilder(handler).build();
+
+ OAuth2CredentialsWithRefresh deserialized = serializeAndDeserialize(credentials);
+ assertEquals(credentials, deserialized);
+ assertEquals(credentials.hashCode(), deserialized.hashCode());
+ assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, deserialized.getUniverseDomain());
+ assertEquals(REFRESHED_TOKEN, deserialized.refreshAccessToken());
+ TestUtils.assertContainsBearerToken(
+ deserialized.getRequestMetadata(URI.create("http://googleapis.com/testapi/v1/foo")),
+ REFRESHED_TOKEN.getTokenValue());
+ }
+
+ @Test
+ void serialize_preservesCustomUniverseDomain() throws IOException, ClassNotFoundException {
+ SerializableRefreshHandler handler = new SerializableRefreshHandler(REFRESHED_TOKEN);
+ OAuth2CredentialsWithRefresh credentials =
+ createTestBuilder(handler).setUniverseDomain("example.com").build();
+
+ OAuth2CredentialsWithRefresh deserialized = serializeAndDeserialize(credentials);
+ assertEquals("example.com", deserialized.getUniverseDomain());
+ }
+
+ @Test
+ void deserialize_missingOrBlankUniverseDomain_defaultsToGoogleDefaultUniverse()
+ throws IOException, ClassNotFoundException {
+ SerializableRefreshHandler handler = new SerializableRefreshHandler(REFRESHED_TOKEN);
+ OAuth2CredentialsWithRefresh expected = createTestBuilder(handler).build();
+
+ // Simulate deserializing streams written before universeDomain existed or with blank values.
+ for (String rawUniverseDomain : new String[] {null, "", " "}) {
+ OAuth2CredentialsWithRefresh credentials = createTestBuilder(handler).build();
+ credentials.universeDomain = rawUniverseDomain;
+
+ OAuth2CredentialsWithRefresh deserialized = serializeAndDeserialize(credentials);
+ assertEquals(Credentials.GOOGLE_DEFAULT_UNIVERSE, deserialized.getUniverseDomain());
+ assertEquals(expected, deserialized);
+ }
+ }
+
+ @Test
+ void equals_true() {
+ OAuth2CredentialsWithRefresh.OAuth2RefreshHandler handler = () -> ACCESS_TOKEN;
+ OAuth2CredentialsWithRefresh custom =
+ createTestBuilder(handler).setUniverseDomain("example.com").build();
+ OAuth2CredentialsWithRefresh sameCustom =
+ createTestBuilder(handler).setUniverseDomain("example.com").build();
+
+ assertEquals(custom, custom);
+ assertEquals(custom, sameCustom);
+ assertEquals(sameCustom, custom);
+ assertEquals(custom.hashCode(), sameCustom.hashCode());
+
+ OAuth2CredentialsWithRefresh noToken =
+ OAuth2CredentialsWithRefresh.newBuilder()
+ .setRefreshHandler(handler)
+ .setUniverseDomain("example.com")
+ .build();
+ OAuth2CredentialsWithRefresh sameNoToken =
+ OAuth2CredentialsWithRefresh.newBuilder()
+ .setRefreshHandler(handler)
+ .setUniverseDomain("example.com")
+ .build();
+ assertEquals(noToken, sameNoToken);
+ assertEquals(noToken.hashCode(), sameNoToken.hashCode());
+
+ // Explicit default universe domain equals unset, null, empty, and blank values.
+ OAuth2CredentialsWithRefresh explicitDefault =
+ createTestBuilder(handler).setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE).build();
+ assertEquals(explicitDefault, createTestBuilder(handler).build());
+ assertEquals(explicitDefault, createTestBuilder(handler).setUniverseDomain(null).build());
+ assertEquals(explicitDefault, createTestBuilder(handler).setUniverseDomain("").build());
+ assertEquals(explicitDefault, createTestBuilder(handler).setUniverseDomain(" ").build());
+ }
+
+ @Test
+ void equals_false() {
+ OAuth2CredentialsWithRefresh.OAuth2RefreshHandler handler = () -> ACCESS_TOKEN;
+ OAuth2CredentialsWithRefresh.OAuth2RefreshHandler otherHandler = () -> ACCESS_TOKEN;
+ AccessToken otherToken =
+ new AccessToken("otherAccessToken", new Date(ACCESS_TOKEN.getExpirationTime().getTime()));
+
+ OAuth2CredentialsWithRefresh baseline =
+ createTestBuilder(handler).setUniverseDomain("example.com").build();
+ OAuth2CredentialsWithRefresh differentToken =
+ OAuth2CredentialsWithRefresh.newBuilder()
+ .setAccessToken(otherToken)
+ .setRefreshHandler(handler)
+ .setUniverseDomain("example.com")
+ .build();
+ OAuth2CredentialsWithRefresh differentHandler =
+ createTestBuilder(otherHandler).setUniverseDomain("example.com").build();
+ OAuth2CredentialsWithRefresh differentUniverse =
+ createTestBuilder(handler).setUniverseDomain("other.example.com").build();
+
+ assertNotEquals(baseline, null);
+ assertNotEquals(baseline, "not-a-credential");
+ assertNotEquals(baseline, differentToken);
+ assertNotEquals(baseline, differentHandler);
+ assertNotEquals(baseline, differentUniverse);
+
+ // Without an initial access token, distinct refresh handlers must still compare unequal.
+ OAuth2CredentialsWithRefresh noToken =
+ OAuth2CredentialsWithRefresh.newBuilder()
+ .setRefreshHandler(handler)
+ .setUniverseDomain("example.com")
+ .build();
+ OAuth2CredentialsWithRefresh noTokenOtherHandler =
+ OAuth2CredentialsWithRefresh.newBuilder()
+ .setRefreshHandler(otherHandler)
+ .setUniverseDomain("example.com")
+ .build();
+ assertNotEquals(noToken, noTokenOtherHandler);
+ }
}
diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java
index 34592a6ce5ea..07f2287dcf81 100644
--- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java
+++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java
@@ -43,14 +43,21 @@
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
+import com.google.api.client.http.GenericUrl;
+import com.google.api.client.http.HttpRequest;
+import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpStatusCodes;
+import com.google.api.client.http.LowLevelHttpRequest;
+import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.json.webtoken.JsonWebSignature;
import com.google.api.client.json.webtoken.JsonWebToken;
import com.google.api.client.testing.http.FixedClock;
+import com.google.api.client.testing.http.MockHttpTransport;
+import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.api.client.util.Clock;
import com.google.api.client.util.Joiner;
@@ -59,6 +66,7 @@
import com.google.auth.RequestMetadataCallback;
import com.google.auth.TestUtils;
import com.google.auth.http.AuthHttpConstants;
+import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.oauth2.GoogleCredentials.GoogleCredentialsInfo;
import com.google.common.collect.ImmutableSet;
@@ -81,6 +89,8 @@
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Test;
/** Test case for {@link ServiceAccountCredentials}. */
@@ -644,6 +654,108 @@ void refreshAccessToken_tokenExpiry() throws IOException {
assertEquals(3600 * 1000 * 1000L, accessToken.getExpirationTimeMillis().longValue());
}
+ @Test
+ void refreshAccessToken_nonDefaultUniverse_throwsIOExceptionWithoutNetworkCall()
+ throws IOException {
+ URI customTokenUri = URI.create("https://oauth2.example.com/token");
+ MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory();
+ transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN);
+
+ GoogleCredentials[] cases = {
+ createDefaultBuilder()
+ .setScopes(SCOPES)
+ .setHttpTransportFactory(transportFactory)
+ .setUniverseDomain("example.com")
+ .build(),
+ createDefaultBuilder()
+ .setScopes(SCOPES)
+ .setHttpTransportFactory(transportFactory)
+ .setTokenServerUri(customTokenUri)
+ .setUniverseDomain("example.com")
+ .build(),
+ createDefaultBuilder()
+ .setScopes(SCOPES)
+ .setHttpTransportFactory(transportFactory)
+ .setUniverseDomain("example.com")
+ .build()
+ .createDelegated("user@example.com")
+ };
+
+ for (GoogleCredentials credentials : cases) {
+ IOException error = assertThrows(IOException.class, credentials::refreshAccessToken);
+ assertTrue(error.getMessage().contains("example.com"));
+ }
+ assertThrows(IOException.class, cases[0]::refresh);
+ assertThrows(IOException.class, cases[0]::refreshIfExpired);
+ assertEquals(0, transportFactory.transport.buildRequestCount);
+ assertNull(transportFactory.transport.getRequest());
+ }
+
+ @Test
+ void refreshAccessToken_nonDefaultUniverseFromJson_throwsIOException() throws IOException {
+ MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory();
+ transportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN);
+ GenericJson json = writeServiceAccountJson(PROJECT_ID, null, "example.com");
+ json.put("token_uri", OAuth2Utils.TOKEN_SERVER_URI.toString());
+
+ GoogleCredentials credentials =
+ ServiceAccountCredentials.fromJson(json, transportFactory).createScoped(SCOPES);
+
+ IOException error = assertThrows(IOException.class, credentials::refreshAccessToken);
+ assertTrue(error.getMessage().contains("example.com"));
+ assertEquals(0, transportFactory.transport.buildRequestCount);
+ assertNull(transportFactory.transport.getRequest());
+ }
+
+ @Test
+ void httpCredentialsAdapter_401WithNonDefaultUniverseServiceAccount_doesNotCallTokenServer()
+ throws IOException {
+ MockTokenServerTransportFactory tokenTransportFactory = new MockTokenServerTransportFactory();
+ tokenTransportFactory.transport.addServiceAccount(CLIENT_EMAIL, ACCESS_TOKEN);
+ ServiceAccountCredentials credentials =
+ createDefaultBuilder()
+ .setScopes(SCOPES)
+ .setHttpTransportFactory(tokenTransportFactory)
+ .setUniverseDomain("example.com")
+ .build();
+
+ AtomicInteger apiRequestCount = new AtomicInteger();
+ AtomicReference authorizationHeader = new AtomicReference<>();
+ MockHttpTransport apiTransport =
+ new MockHttpTransport() {
+ @Override
+ public LowLevelHttpRequest buildRequest(String method, String url) {
+ return new MockLowLevelHttpRequest() {
+ @Override
+ public LowLevelHttpResponse execute() {
+ apiRequestCount.incrementAndGet();
+ authorizationHeader.set(getFirstHeaderValue(AuthHttpConstants.AUTHORIZATION));
+ MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
+ response.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
+ response.addHeader("WWW-Authenticate", "Bearer error=\"invalid_token\"");
+ return response;
+ }
+ };
+ }
+ };
+
+ HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials);
+ HttpRequest request =
+ apiTransport
+ .createRequestFactory(adapter)
+ .buildGetRequest(new GenericUrl("https://storage.example.com/test"));
+ request.setThrowExceptionOnExecuteError(false);
+
+ HttpResponse response = request.execute();
+
+ assertEquals(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED, response.getStatusCode());
+ assertEquals(1, apiRequestCount.get());
+ assertNotNull(authorizationHeader.get());
+ assertTrue(authorizationHeader.get().startsWith("Bearer "));
+ assertEquals(0, tokenTransportFactory.transport.buildRequestCount);
+ assertNull(tokenTransportFactory.transport.getRequest());
+ }
+
@Test
void refreshAccessToken_IOException_Retry() throws IOException {
final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2";
@@ -1773,6 +1885,74 @@ void getRequestMetadata_withMultipleScopes_selfSignedJWT() throws IOException {
verifyJwtAccess(credentials.getRequestMetadata(CALL_URI), "scope1 scope2");
}
+ @Test
+ void jwtWithClaims_propagatesUniverseDomain() throws IOException {
+ JwtClaims newClaims =
+ JwtClaims.newBuilder().setAudience("https://service.example.com/").build();
+
+ ServiceAccountCredentials defaultCredentials = createDefaultBuilder().build();
+ assertEquals(
+ Credentials.GOOGLE_DEFAULT_UNIVERSE,
+ defaultCredentials.jwtWithClaims(newClaims).getUniverseDomain());
+
+ ServiceAccountCredentials customCredentials =
+ createDefaultBuilder().setUniverseDomain("example.com").build();
+ assertEquals("example.com", customCredentials.jwtWithClaims(newClaims).getUniverseDomain());
+
+ InputStream stream =
+ writeServiceAccountStream(
+ CLIENT_ID, CLIENT_EMAIL, PRIVATE_KEY_PKCS8, PRIVATE_KEY_ID, "example.com");
+ ServiceAccountCredentials jsonCredentials = ServiceAccountCredentials.fromStream(stream);
+ assertEquals("example.com", jsonCredentials.jwtWithClaims(newClaims).getUniverseDomain());
+ }
+
+ @Test
+ void jwtWithClaims_getUniverseDomainIOException_throwsIllegalStateException() throws IOException {
+ IOException expectedCause = new IOException("universe lookup failed");
+ ServiceAccountCredentials credentials =
+ new ServiceAccountCredentials(createDefaultBuilder()) {
+ @Override
+ public String getUniverseDomain() throws IOException {
+ throw expectedCause;
+ }
+ };
+ JwtClaims newClaims =
+ JwtClaims.newBuilder().setAudience("https://service.example.com/").build();
+
+ IllegalStateException exception =
+ assertThrows(IllegalStateException.class, () -> credentials.jwtWithClaims(newClaims));
+ assertSame(expectedCause, exception.getCause());
+ }
+
+ @Test
+ void createSelfSignedJwtCredentials_propagatesUniverseDomain() throws IOException {
+ URI audienceUri = URI.create("https://service.example.com/v1/resource");
+
+ ServiceAccountCredentials defaultCredentials = createDefaultBuilder().build();
+ assertEquals(
+ Credentials.GOOGLE_DEFAULT_UNIVERSE,
+ defaultCredentials.createSelfSignedJwtCredentials(audienceUri).getUniverseDomain());
+
+ ServiceAccountCredentials customCredentials =
+ createDefaultBuilder().setUniverseDomain("example.com").build();
+ assertEquals(
+ "example.com",
+ customCredentials.createSelfSignedJwtCredentials(audienceUri).getUniverseDomain());
+ }
+
+ @Test
+ void getRequestMetadata_withScopesAndCustomUniverseDomain_propagatesUniverseDomainToCachedJwt()
+ throws IOException {
+ ServiceAccountCredentials credentials =
+ createDefaultBuilder().setScopes(SCOPES).setUniverseDomain("example.com").build();
+
+ credentials.getRequestMetadata(null);
+
+ JwtCredentials cachedJwt = credentials.getSelfSignedJwtCredentialsWithScope();
+ assertNotNull(cachedJwt);
+ assertEquals("example.com", cachedJwt.getUniverseDomain());
+ }
+
private void verifyJwtAccess(Map> metadata, String expectedScopeClaim)
throws IOException {
assertNotNull(metadata);
diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java
index 4a12b7483a33..43b720a02908 100644
--- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java
+++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountJwtAccessCredentialsTest.java
@@ -62,6 +62,7 @@
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
+import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -561,6 +562,30 @@ void equals_false_callUri() throws IOException {
assertNotEquals(otherCredentials, credentials);
}
+ @Test
+ void equals_false_universeDomain() throws IOException {
+ PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8);
+ ServiceAccountJwtAccessCredentials credentials =
+ ServiceAccountJwtAccessCredentials.newBuilder()
+ .setClientId(SA_CLIENT_ID)
+ .setClientEmail(SA_CLIENT_EMAIL)
+ .setPrivateKey(privateKey)
+ .setPrivateKeyId(SA_PRIVATE_KEY_ID)
+ .setDefaultAudience(CALL_URI)
+ .build();
+ ServiceAccountJwtAccessCredentials otherCredentials =
+ ServiceAccountJwtAccessCredentials.newBuilder()
+ .setClientId(SA_CLIENT_ID)
+ .setClientEmail(SA_CLIENT_EMAIL)
+ .setPrivateKey(privateKey)
+ .setPrivateKeyId(SA_PRIVATE_KEY_ID)
+ .setDefaultAudience(CALL_URI)
+ .setUniverseDomain("example.com")
+ .build();
+ assertNotEquals(credentials, otherCredentials);
+ assertNotEquals(otherCredentials, credentials);
+ }
+
@Test
void toString_containsFields() throws IOException {
PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8);
@@ -576,8 +601,13 @@ void toString_containsFields() throws IOException {
String expectedToString =
String.format(
"ServiceAccountJwtAccessCredentials{clientId=%s, clientEmail=%s, privateKeyId=%s, "
- + "defaultAudience=%s, quotaProjectId=%s}",
- SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_ID, CALL_URI, QUOTA_PROJECT);
+ + "defaultAudience=%s, quotaProjectId=%s, universeDomain=%s}",
+ SA_CLIENT_ID,
+ SA_CLIENT_EMAIL,
+ SA_PRIVATE_KEY_ID,
+ CALL_URI,
+ QUOTA_PROJECT,
+ GOOGLE_DEFAULT_UNIVERSE);
assertEquals(expectedToString, credentials.toString());
}
@@ -591,6 +621,7 @@ void hashCode_equals() throws IOException {
.setPrivateKey(privateKey)
.setPrivateKeyId(SA_PRIVATE_KEY_ID)
.setDefaultAudience(CALL_URI)
+ .setUniverseDomain("example.com")
.build();
ServiceAccountJwtAccessCredentials otherCredentials =
ServiceAccountJwtAccessCredentials.newBuilder()
@@ -599,14 +630,51 @@ void hashCode_equals() throws IOException {
.setPrivateKey(privateKey)
.setPrivateKeyId(SA_PRIVATE_KEY_ID)
.setDefaultAudience(CALL_URI)
+ .setUniverseDomain("example.com")
.build();
+ assertEquals(credentials, otherCredentials);
assertEquals(credentials.hashCode(), otherCredentials.hashCode());
}
@Test
void serialize() throws IOException, ClassNotFoundException {
PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8);
- ServiceAccountJwtAccessCredentials credentials =
+ JwtClaims expectedClaims =
+ JwtClaims.newBuilder()
+ .setAudience(CALL_URI.toString())
+ .setIssuer(SA_CLIENT_EMAIL)
+ .setSubject(SA_CLIENT_EMAIL)
+ .build();
+
+ for (String universeDomain : Arrays.asList(GOOGLE_DEFAULT_UNIVERSE, "example.com")) {
+ ServiceAccountJwtAccessCredentials credentials =
+ ServiceAccountJwtAccessCredentials.newBuilder()
+ .setClientId(SA_CLIENT_ID)
+ .setClientEmail(SA_CLIENT_EMAIL)
+ .setPrivateKey(privateKey)
+ .setPrivateKeyId(SA_PRIVATE_KEY_ID)
+ .setDefaultAudience(CALL_URI)
+ .setUniverseDomain(universeDomain)
+ .build();
+ ServiceAccountJwtAccessCredentials deserializedCredentials =
+ serializeAndDeserialize(credentials);
+ verifyJwtAccess(deserializedCredentials.getRequestMetadata(), CALL_URI);
+ assertEquals(credentials, deserializedCredentials);
+ assertEquals(credentials.hashCode(), deserializedCredentials.hashCode());
+ assertEquals(credentials.toString(), deserializedCredentials.toString());
+ assertEquals(universeDomain, deserializedCredentials.getUniverseDomain());
+ assertSame(Clock.SYSTEM, deserializedCredentials.clock);
+ JwtCredentials cached = deserializedCredentials.credentialsCache.getIfPresent(expectedClaims);
+ assertNotNull(cached);
+ assertEquals(universeDomain, cached.getUniverseDomain());
+ }
+ }
+
+ @Test
+ void deserialize_missingOrBlankUniverseDomain_defaultsToGoogleDefaultUniverse()
+ throws IOException, ClassNotFoundException {
+ PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8);
+ ServiceAccountJwtAccessCredentials expected =
ServiceAccountJwtAccessCredentials.newBuilder()
.setClientId(SA_CLIENT_ID)
.setClientEmail(SA_CLIENT_EMAIL)
@@ -614,13 +682,35 @@ void serialize() throws IOException, ClassNotFoundException {
.setPrivateKeyId(SA_PRIVATE_KEY_ID)
.setDefaultAudience(CALL_URI)
.build();
- ServiceAccountJwtAccessCredentials deserializedCredentials =
- serializeAndDeserialize(credentials);
- verifyJwtAccess(deserializedCredentials.getRequestMetadata(), CALL_URI);
- assertEquals(credentials, deserializedCredentials);
- assertEquals(credentials.hashCode(), deserializedCredentials.hashCode());
- assertEquals(credentials.toString(), deserializedCredentials.toString());
- assertSame(Clock.SYSTEM, deserializedCredentials.clock);
+ JwtClaims expectedClaims =
+ JwtClaims.newBuilder()
+ .setAudience(CALL_URI.toString())
+ .setIssuer(SA_CLIENT_EMAIL)
+ .setSubject(SA_CLIENT_EMAIL)
+ .build();
+
+ for (String serializedUniverseDomain : Arrays.asList(null, "", " ")) {
+ ServiceAccountJwtAccessCredentials credentials =
+ ServiceAccountJwtAccessCredentials.newBuilder()
+ .setClientId(SA_CLIENT_ID)
+ .setClientEmail(SA_CLIENT_EMAIL)
+ .setPrivateKey(privateKey)
+ .setPrivateKeyId(SA_PRIVATE_KEY_ID)
+ .setDefaultAudience(CALL_URI)
+ .build();
+ credentials.universeDomain = serializedUniverseDomain;
+
+ ServiceAccountJwtAccessCredentials deserialized = serializeAndDeserialize(credentials);
+ assertEquals(GOOGLE_DEFAULT_UNIVERSE, deserialized.getUniverseDomain());
+ assertEquals(expected, deserialized);
+ assertEquals(deserialized, expected);
+ assertEquals(expected.hashCode(), deserialized.hashCode());
+ assertEquals(expected.toString(), deserialized.toString());
+ verifyJwtAccess(deserialized.getRequestMetadata(), CALL_URI);
+ JwtCredentials cached = deserialized.credentialsCache.getIfPresent(expectedClaims);
+ assertNotNull(cached);
+ assertEquals(GOOGLE_DEFAULT_UNIVERSE, cached.getUniverseDomain());
+ }
}
@Test
@@ -900,6 +990,75 @@ void builder_customUniverseDomain() throws IOException {
assertEquals("example.com", credentials.getUniverseDomain());
}
+ @Test
+ void jwtWithClaims_propagatesUniverseDomain() throws IOException {
+ PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8);
+ JwtClaims newClaims = JwtClaims.newBuilder().setAudience("new-audience").build();
+
+ ServiceAccountJwtAccessCredentials defaultCredentials =
+ ServiceAccountJwtAccessCredentials.newBuilder()
+ .setClientId(SA_CLIENT_ID)
+ .setClientEmail(SA_CLIENT_EMAIL)
+ .setPrivateKey(privateKey)
+ .setPrivateKeyId(SA_PRIVATE_KEY_ID)
+ .setDefaultAudience(URI.create("default-audience"))
+ .build();
+ assertEquals(
+ GOOGLE_DEFAULT_UNIVERSE, defaultCredentials.jwtWithClaims(newClaims).getUniverseDomain());
+
+ ServiceAccountJwtAccessCredentials customCredentials =
+ ServiceAccountJwtAccessCredentials.newBuilder()
+ .setClientId(SA_CLIENT_ID)
+ .setClientEmail(SA_CLIENT_EMAIL)
+ .setPrivateKey(privateKey)
+ .setPrivateKeyId(SA_PRIVATE_KEY_ID)
+ .setDefaultAudience(URI.create("default-audience"))
+ .setUniverseDomain("example.com")
+ .build();
+ assertEquals("example.com", customCredentials.jwtWithClaims(newClaims).getUniverseDomain());
+
+ ServiceAccountJwtAccessCredentials jsonCredentials =
+ ServiceAccountJwtAccessCredentials.fromJson(
+ writeServiceAccountJson("example.com"), CALL_URI);
+ assertEquals("example.com", jsonCredentials.jwtWithClaims(newClaims).getUniverseDomain());
+ }
+
+ @Test
+ void getRequestMetadata_propagatesUniverseDomainToCachedJwtCredentials() throws IOException {
+ PrivateKey privateKey = OAuth2Utils.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8);
+ JwtClaims expectedClaims =
+ JwtClaims.newBuilder()
+ .setAudience(CALL_URI.toString())
+ .setIssuer(SA_CLIENT_EMAIL)
+ .setSubject(SA_CLIENT_EMAIL)
+ .build();
+
+ ServiceAccountJwtAccessCredentials defaultCredentials =
+ ServiceAccountJwtAccessCredentials.newBuilder()
+ .setClientId(SA_CLIENT_ID)
+ .setClientEmail(SA_CLIENT_EMAIL)
+ .setPrivateKey(privateKey)
+ .setPrivateKeyId(SA_PRIVATE_KEY_ID)
+ .build();
+ defaultCredentials.getRequestMetadata(CALL_URI);
+ JwtCredentials defaultCached = defaultCredentials.credentialsCache.getIfPresent(expectedClaims);
+ assertNotNull(defaultCached);
+ assertEquals(GOOGLE_DEFAULT_UNIVERSE, defaultCached.getUniverseDomain());
+
+ ServiceAccountJwtAccessCredentials customCredentials =
+ ServiceAccountJwtAccessCredentials.newBuilder()
+ .setClientId(SA_CLIENT_ID)
+ .setClientEmail(SA_CLIENT_EMAIL)
+ .setPrivateKey(privateKey)
+ .setPrivateKeyId(SA_PRIVATE_KEY_ID)
+ .setUniverseDomain("example.com")
+ .build();
+ customCredentials.getRequestMetadata(CALL_URI);
+ JwtCredentials customCached = customCredentials.credentialsCache.getIfPresent(expectedClaims);
+ assertNotNull(customCached);
+ assertEquals("example.com", customCached.getUniverseDomain());
+ }
+
private void verifyJwtAccess(Map> metadata, URI expectedAudience)
throws IOException {
assertNotNull(metadata);
diff --git a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java
index b4b06743ee24..0fd2e9a2273f 100644
--- a/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java
+++ b/google-auth-library-java/oauth2_http/javatests/com/google/auth/oauth2/UserCredentialsTest.java
@@ -71,8 +71,8 @@
class UserCredentialsTest extends BaseSerializationTest {
static final String CLIENT_SECRET = "jakuaL9YyieakhECKL2SwZcu";
- static final String CLIENT_ID = "ya29.1.AADtN_UtlxN3PuGAxrN2XQnZTVRvDyVWnYq4I6dws";
- static final String REFRESH_TOKEN = "1/Tl6awhpFjkMkSJoj1xsli0H2eL5YsMgU_NKPY2TyGWY";
+ static final String CLIENT_ID = "test-client-id";
+ static final String REFRESH_TOKEN = "test-refresh-token";
private static final String ACCESS_TOKEN = "1/MkSJoj1xsli0AccessToken_NKPY2";
private static final String QUOTA_PROJECT = "sample-quota-project-id";
private static final Collection SCOPES = Collections.singletonList("dummy.scope");
@@ -883,6 +883,134 @@ void userCredentials_toBuilder_copyEveryAttribute() {
assertEquals(credentials, otherCredentials);
}
+ @Test
+ void refreshAccessToken_nonDefaultUniverse_throwsIOException() {
+ MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(null);
+ URI[] tokenUris = {
+ null,
+ URI.create("https://oauth2.example.com/token"),
+ URI.create("https://accounts.google.com/o/oauth2/token"),
+ URI.create("/token"),
+ URI.create("mailto:user@example.com")
+ };
+
+ for (URI tokenUri : tokenUris) {
+ UserCredentials credentials =
+ createUniverseUserCredentials(transportFactory, tokenUri, "example.com");
+ IOException error = assertThrows(IOException.class, credentials::refreshAccessToken);
+ assertTrue(error.getMessage().contains("example.com"));
+ }
+
+ UserCredentials defaultUriCredentials =
+ createUniverseUserCredentials(transportFactory, null, "example.com");
+ assertThrows(IOException.class, defaultUriCredentials::refresh);
+ assertThrows(IOException.class, defaultUriCredentials::refreshIfExpired);
+
+ GoogleCredentials fromToBuilder =
+ createUniverseUserCredentials(transportFactory, null, null).toBuilder()
+ .setUniverseDomain("example.com")
+ .build();
+ assertThrows(IOException.class, fromToBuilder::refreshAccessToken);
+
+ assertEquals(0, transportFactory.transport.buildRequestCount);
+ assertNull(transportFactory.transport.getRequest());
+ }
+
+ @Test
+ void idTokenWithAudience_nonDefaultUniverse_throwsIOException() {
+ MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(null);
+ UserCredentials credentials =
+ createUniverseUserCredentials(transportFactory, null, "example.com");
+
+ assertThrows(
+ IOException.class,
+ () -> credentials.idTokenWithAudience("https://target.example.com", null));
+ assertEquals(0, transportFactory.transport.buildRequestCount);
+ assertNull(transportFactory.transport.getRequest());
+ }
+
+ @Test
+ void refreshAccessToken_defaultUniverseWithDefaultOrCustomTokenUri_succeeds() throws IOException {
+ URI[] tokenUris = {null, URI.create("https://oauth2.example.com/token")};
+
+ for (URI tokenUri : tokenUris) {
+ MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(tokenUri);
+ UserCredentials credentials = createUniverseUserCredentials(transportFactory, tokenUri, null);
+
+ AccessToken token = credentials.refreshAccessToken();
+
+ URI expectedUri = tokenUri != null ? tokenUri : OAuth2Utils.TOKEN_SERVER_URI;
+ assertEquals(ACCESS_TOKEN, token.getTokenValue());
+ assertEquals(expectedUri.toString(), transportFactory.transport.getRequest().getUrl());
+ }
+ }
+
+ @Test
+ void fromJson_nonDefaultUniverse_throwsIOException() {
+ String[] tokenUrls = {
+ null, OAuth2Utils.TOKEN_SERVER_URI.toString(), "https://oauth2.example.com/token"
+ };
+
+ for (String tokenUrl : tokenUrls) {
+ MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(null);
+ GenericJson json = writeUserJson(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, tokenUrl);
+ json.put("universe_domain", "example.com");
+
+ IOException error =
+ assertThrows(IOException.class, () -> UserCredentials.fromJson(json, transportFactory));
+ assertTrue(error.getMessage().contains("example.com"));
+ assertEquals(0, transportFactory.transport.buildRequestCount);
+ assertNull(transportFactory.transport.getRequest());
+ }
+ }
+
+ @Test
+ void fromJson_defaultOrBlankUniverse_succeeds() throws IOException {
+ String[] universeDomains = {null, "", " ", "googleapis.com"};
+
+ for (String universeDomain : universeDomains) {
+ MockTokenServerTransportFactory transportFactory = createMockTokenTransportFactory(null);
+ GenericJson json = writeUserJson(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, null);
+ if (universeDomain != null) {
+ json.put("universe_domain", universeDomain);
+ }
+
+ UserCredentials credentials = UserCredentials.fromJson(json, transportFactory);
+ assertEquals("googleapis.com", credentials.getUniverseDomain());
+ assertEquals(ACCESS_TOKEN, credentials.refreshAccessToken().getTokenValue());
+ assertEquals(
+ OAuth2Utils.TOKEN_SERVER_URI.toString(),
+ transportFactory.transport.getRequest().getUrl());
+ }
+ }
+
+ private static MockTokenServerTransportFactory createMockTokenTransportFactory(URI tokenUri) {
+ MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory();
+ if (tokenUri != null) {
+ transportFactory.transport.setTokenServerUri(tokenUri);
+ }
+ transportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET);
+ transportFactory.transport.addRefreshToken(REFRESH_TOKEN, ACCESS_TOKEN);
+ return transportFactory;
+ }
+
+ private static UserCredentials createUniverseUserCredentials(
+ MockTokenServerTransportFactory transportFactory, URI tokenUri, String universeDomain) {
+ UserCredentials.Builder builder =
+ UserCredentials.newBuilder()
+ .setClientId(CLIENT_ID)
+ .setClientSecret(CLIENT_SECRET)
+ .setRefreshToken(REFRESH_TOKEN)
+ .setHttpTransportFactory(transportFactory);
+ if (tokenUri != null) {
+ builder.setTokenServerUri(tokenUri);
+ }
+ if (universeDomain != null) {
+ builder.setUniverseDomain(universeDomain);
+ }
+ return builder.build();
+ }
+
static GenericJson writeUserJson(
String clientId,
String clientSecret,
diff --git a/java-bigquery-jdbc/.agents/skills/bigquery-jdbc-testing/SKILL.md b/java-bigquery-jdbc/.agents/skills/bigquery-jdbc-testing/SKILL.md
index fb89b3c46cf7..61c738de7c7b 100644
--- a/java-bigquery-jdbc/.agents/skills/bigquery-jdbc-testing/SKILL.md
+++ b/java-bigquery-jdbc/.agents/skills/bigquery-jdbc-testing/SKILL.md
@@ -1,6 +1,6 @@
---
name: bigquery-jdbc-testing
-description: Conventions for writing and refactoring unit and integration tests in the BigQuery JDBC driver (java-bigquery-jdbc). Use this skill when adding, reviewing, or cleaning up tests under java-bigquery-jdbc/src/test, including tests for connection/credential setup, Storage Read/Write API clients, TPC/universe-domain behavior, and ITBase-derived integration tests.
+description: Conventions for writing and refactoring unit and integration tests in the BigQuery JDBC driver (java-bigquery-jdbc). Use this skill when adding, reviewing, or cleaning up tests under java-bigquery-jdbc/src/test, including tests for connection/credential setup, Storage Read/Write API clients, universe-domain behavior, and ITBase-derived integration tests.
---
# BigQuery JDBC Driver: Writing Tests
@@ -39,7 +39,7 @@ Example:
String url =
getUriOAuthServiceAccount()
.append("ProjectId", "project")
- .append("universeDomain", "apis-tpczero.goog")
+ .append("universeDomain", "example.com")
.toString();
```
@@ -54,20 +54,20 @@ the assertions into one `private static` helper that takes the varying parts
(credentials, endpoint URI, expected scopes, expected universe) as parameters.
Each test then makes one call per object.
-This is how `BigQueryConnectionTest` does it. `TPC_UNIVERSE`, `storageUri` and
-`assertStorageCredentialsScoped` are private members of that class, not shared
-fixtures:
+This is how `BigQueryConnectionTest` does it. `CUSTOM_UNIVERSE`, `storageUri`
+and `assertStorageCredentialsScoped` are private members of that class, not
+shared fixtures:
```java
assertStorageCredentialsScoped(
readClient.getSettings().getCredentialsProvider().getCredentials(),
- TPC_UNIVERSE,
- storageUri(TPC_UNIVERSE, "BigQueryRead"),
+ CUSTOM_UNIVERSE,
+ storageUri(CUSTOM_UNIVERSE, "BigQueryRead"),
BigQueryReadSettings.getDefaultServiceScopes());
assertStorageCredentialsScoped(
writeClient.getSettings().getCredentialsProvider().getCredentials(),
- TPC_UNIVERSE,
- storageUri(TPC_UNIVERSE, "BigQueryWrite"),
+ CUSTOM_UNIVERSE,
+ storageUri(CUSTOM_UNIVERSE, "BigQueryWrite"),
BigQueryWriteSettings.getDefaultServiceScopes());
```
@@ -83,8 +83,8 @@ takes each side. In particular:
`GoogleCredentials`, also test a credential that is *not* a service account,
such as `getUriOAuthToken()` / `GoogleCredentials.create(AccessToken)`. Check
that it passes through unchanged (`assertSame` where possible).
-- **Universe domain.** If the code behaves differently for TPC
- (`universeDomain=apis-tpczero.goog`), also test the **default** universe (no
+- **Universe domain.** If the code behaves differently for a custom universe
+ domain (`universeDomain=example.com`), also test the **default** universe (no
`universeDomain` property, so `googleapis.com`).
- **Already configured input.** For example, credentials that already have
explicit scopes must keep them.
@@ -111,9 +111,10 @@ cases or weaken assertions (for example, changing `assertEquals` to
misleads the reader.
- Use try-with-resources for `Connection`, `Statement`, and `ResultSet`, or close
them explicitly. IT suites share quotas.
-- `@Tag("disable_tpc")` excludes a test from TPC runs. Remove it only when the
- feature is known to work against TPC, and in that case add an assertion that
- proves the intended path was used (for example `assertArrowResultSet`).
+- `@Tag("disable_universe_domain")` excludes a test from custom universe domain
+ runs. Remove it only when the feature is known to work against a custom
+ universe domain, and in that case add an assertion that proves the intended
+ path was used (for example `assertArrowResultSet`).
## 5. Style and verification
diff --git a/java-bigquery-jdbc/README.MD b/java-bigquery-jdbc/README.MD
index 34bbb7b38c54..fbbeb7681295 100644
--- a/java-bigquery-jdbc/README.MD
+++ b/java-bigquery-jdbc/README.MD
@@ -40,6 +40,8 @@ libraryDependencies += "com.google.cloud" % "google-cloud-bigquery-jdbc" % "LATE
See the [Authentication][authentication] section in the base directory's README.
+For custom universe domain deployments, configure the target universe domain via the `universeDomain=` JDBC connection URL property, `DataSource.setUniverseDomain("")`, or the `GOOGLE_CLOUD_UNIVERSE_DOMAIN` environment variable (`GOOGLE_CLOUD_UNIVERSE_DOMAIN` configures client endpoints only and does not override credentials). Self-describing JSON credentials (Service Account JSON keys, External Account JSON files, and Application Default Credentials) always retain their own embedded `universe_domain`. When inline External Account / Workload Identity Federation (`OAuthType=4` with `BYOID_*` properties) is used without an explicit `BYOID_TokenUri`, the driver derives `https://sts./v1/token` when `universeDomain` is explicitly set (otherwise defaulting to `https://sts.googleapis.com/v1/token`).
+
## Authorization
The client application making API calls must be granted [authorization scopes][auth-scopes] required for the desired BigQuery JDBC APIs, and the authenticated principal must have the [IAM role(s)][predefined-iam-roles] required to access GCP resources using the BigQuery JDBC API calls.
diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md
index 1549d1b5fb4a..cb2f7cc28e92 100644
--- a/java-bigquery-jdbc/docs/USER_GUIDE.md
+++ b/java-bigquery-jdbc/docs/USER_GUIDE.md
@@ -109,7 +109,7 @@ The driver supports multiple OAuth 2.0 and identity workflows specified via the
| **`0`** | **Service Account Key File (P12)** | `OAuthPvtKeyPath`, `OAuthServiceAcctEmail` | `OAuthP12Password` | Path to `.p12` key file. Requires explicit `OAuthServiceAcctEmail` as `.p12` files do not contain email metadata. `OAuthP12Password` defaults to `notasecret`. |
| **`0`** | **Service Account Key String (JSON)** | `OAuthPvtKey` | `OAuthServiceAcctEmail` | Raw JSON key file string content in URL. Service account email and private key are automatically extracted from the JSON string. |
| **`0`** | **Service Account Key String (PKCS#8 / P12 Bytes)** | `OAuthPvtKey`, `OAuthServiceAcctEmail` | `OAuthP12Password` | Raw PKCS#8 or P12 bytes key string content in URL. Requires explicit `OAuthServiceAcctEmail`. |
-| **`1`** | **User Account (Interactive 3-Legged OAuth)** | None (for built-in client app) | `OAuthClientId`, `OAuthClientSecret` | Launches local browser tab for interactive user login on desktop. Built-in client ID/secret used if omitted. |
+| **`1`** | **User Account (Interactive 3-Legged OAuth)** | None (for built-in client app) | `OAuthClientId`, `OAuthClientSecret` | Launches local browser tab for interactive user login on desktop. Built-in client ID/secret used if omitted. Custom `OAuthClientId` values must be configured as a **Desktop app** OAuth 2.0 client. |
| **`2`** | **Pre-generated Access Token** | `OAuthAccessToken` | `OAuthAccessTokenReadonly` | Uses short-lived bearer token directly. `OAuthAccessTokenReadonly` defaults to `false`. |
| **`2`** | **Pre-generated Refresh Token** | `OAuthRefreshToken`, `OAuthClientId`, `OAuthClientSecret` | None | Uses refresh token with client credentials to automatically mint access tokens. |
| **`3`** | **Application Default Credentials (ADC)** | None | None | Uses GCP standard credential resolution (`GOOGLE_APPLICATION_CREDENTIALS` env var or `gcloud` CLI context). |
@@ -160,7 +160,7 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443"
| `OAuthAccessToken` | `null` | Pre-generated OAuth 2.0 access token string. |
| `OAuthAccessTokenReadonly` | `false` | Indicates whether the pre-generated access token has read-only scope. |
| `OAuthRefreshToken` | `null` | Pre-generated refresh token to automatically mint access tokens. |
-| `OAuthClientId` | *Google Client ID* | OAuth 2.0 Client ID for user authentication or refresh token flows. |
+| `OAuthClientId` | *Google Client ID* | OAuth 2.0 Client ID for user authentication or refresh token flows. For `OAuthType=1`, custom client IDs must be configured as a **Desktop app** OAuth 2.0 client so dynamic loopback redirect URIs (`http://127.0.0.1:` or `http://[::1]:`) are accepted. |
| `OAuthClientSecret` | *Google Secret* | OAuth 2.0 Client Secret for user authentication or refresh token flows. |
| `ServiceAccountImpersonationEmail` | `null` | Target Service Account email to impersonate for query job execution. |
| `ServiceAccountImpersonationChain` | `null` | Comma-separated list of service account emails representing the impersonation chain. |
@@ -177,7 +177,7 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443"
| `BYOID_PoolUserProject` | `null` | Google Cloud project number associated with the workforce pool. |
| `BYOID_SA_Impersonation_Uri` | `null` | Service Account impersonation URL for Workload Identity Federation. |
| `BYOID_SubjectTokenType` | `urn:ietf:params:oauth:tokentype:id_token` | Type of subject token provided (e.g., `urn:ietf:params:oauth:tokentype:jwt`). |
-| `BYOID_TokenUri` | `https://sts.googleapis.com/v1/token` | Security Token Service (STS) token exchange endpoint URI. |
+| `BYOID_TokenUri` | `https://sts./v1/token` (`https://sts.googleapis.com/v1/token`) | Security Token Service (STS) token exchange endpoint URI. Derived from explicit `universeDomain` when omitted (defaults to `https://sts.googleapis.com/v1/token`). |
### Core Query & Catalog Properties
@@ -253,7 +253,7 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443"
| `ProxyPwd` | `null` | Password for proxy server authentication. |
| `EndpointOverrides` | `null` | Semicolon or comma-separated list of custom service endpoint overrides. Supported keys: `BIGQUERY`, `READ_API`, `OAUTH2`, `STS`, `ACCOUNTS`. |
| `PrivateServiceConnectUris` | `null` | Alias for `EndpointOverrides`. Accepts the same custom service endpoint override format and supported keys. |
-| `universeDomain` | `googleapis.com` | Domain name for Google Cloud Dedicated (GCD) or custom Google universe instances. |
+| `universeDomain` | `null` (falls back to `GOOGLE_CLOUD_UNIVERSE_DOMAIN`, then `googleapis.com`) | Domain name for Google Cloud Dedicated (GCD) or custom universe domain instances. Configures BigQuery, Storage Read/Write, and Cloud Logging client endpoints. Explicit `universeDomain` also applies to non-JSON credentials (PKCS#8/P12 keys, pre-generated tokens, and inline `BYOID_*` properties), while `GOOGLE_CLOUD_UNIVERSE_DOMAIN` applies to client endpoints only and JSON credentials always preserve their own `universe_domain`. |
| `SSLTrustStore` | `null` | Path to custom Java TrustStore file containing trusted server certificates for SSL. |
| `SSLTrustStorePwd` | `null` | Password for accessing the custom Java TrustStore file. |
| `SSLTrustStoreType` | *System Default* (`JKS`/`PKCS12`) | Type of the custom Java TrustStore file. |
@@ -272,8 +272,8 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443"
| `RetryInitialDelay` | `0` | Initial delay (in seconds) before executing the first retry attempt. |
| `RetryMaxDelay` | `0` | Maximum delay limit (in seconds) between retry attempts. |
| `MetaDataFetchThreadCount` | `32` | Thread pool size used to parallelize `DatabaseMetaData` catalog RPC calls. |
-| `ConnectionPoolSize` | `10` | Maximum size of the internal connection pool when connection pooling is enabled. |
-| `ListenerPoolSize` | `10` | Maximum size of the listener thread pool when connection pooling is enabled. |
+| `ConnectionPoolSize` | `10` | Maximum number of idle physical connections retained in `PooledConnectionDataSource`'s built-in pool (`0` = unbounded). Latched from the first physical connection checkout; changing it on the same `PooledConnectionDataSource` afterward has no effect. |
+| `ListenerPoolSize` | `10` | Maximum number of `ConnectionEventListener` instances that can be registered on a single `PooledConnection` (`0` = unbounded). |
| `RequestReason` | `null` | Reason string passed in the `x-goog-request-reason` HTTP header for auditing. |
### OpenTelemetry & Cloud Observability Exporters
@@ -625,9 +625,9 @@ jdbc:bigquery://https://bigquery.googleapis.com:443
;PrivateServiceConnectUris=BIGQUERY=https://bigquery-privateendpoint.p.googleapis.com
```
-#### 3. Custom Universe Domains (`universeDomain`)
+#### 3. Custom Universe Domains (`universeDomain` / `GOOGLE_CLOUD_UNIVERSE_DOMAIN`)
-To target Google Cloud Dedicated (GCD) or non-default Universe Domain instances, specify `universeDomain`:
+To target Google Cloud Dedicated (GCD) or custom universe domain instances, specify `universeDomain` in the connection URL (or set the `GOOGLE_CLOUD_UNIVERSE_DOMAIN` environment variable):
```
jdbc:bigquery://https://www.my-universe.cloud:443
@@ -699,7 +699,12 @@ Logging can also be configured globally across all driver connections using envi
#### Log File Naming & Format
-Log files are generated inside the specified `LogPath` directory with per-connection log isolation.
+Log files are generated inside the specified `LogPath` directory with per-connection log isolation:
+- **Global log file**: `BQ-JDBC-GLOBAL.log` (or `BQ-JDBC-GLOBAL--.log` on lock/ownership contention), used for pre-connection driver events (such as URL parsing warnings and connection-setup failures before a connection ID exists) and fallback records when a per-connection file cannot be opened; all connection-scoped logs go to the per-connection file.
+- **Per-connection log file**: `BQ-JDBC--.log` (with a numeric collision suffix if needed).
+- **File permissions**: Created directories and log files enforce owner-only permissions (`0700` on directories, `0600` on files) on POSIX filesystems and reject symbolic links.
+- **Size cap & rotation**: Each active log file is capped at `1 GiB` by default (configurable via `-Dcom.google.cloud.bigquery.jdbc.maxLogFileBytes=`) and rotates onto a single `.1.log` backup file (falling back to in-place truncation if rotation is blocked).
+- **URL `LogPath` restriction**: Set `-Dcom.google.cloud.bigquery.jdbc.allowUrlLogPath=false` to ignore `LogPath` values supplied via JDBC URLs or connection `Properties` and restrict file logging to `BIGQUERY_JDBC_LOG_PATH`.
**Standard Log Record Format**:
```text
diff --git a/java-bigquery-jdbc/pom.xml b/java-bigquery-jdbc/pom.xml
index ff5f6a1e8739..2eb1d6ecafda 100644
--- a/java-bigquery-jdbc/pom.xml
+++ b/java-bigquery-jdbc/pom.xml
@@ -33,6 +33,9 @@
githubgoogle-cloud-bigquery-jdbcfalse
+
+
@@ -65,6 +68,15 @@
org.apache.maven.pluginsmaven-failsafe-plugin
+ 1
+
+ @{argLine} -Xmx1536m -XX:MaxDirectMemorySize=1gtrue
@@ -513,14 +525,15 @@
so BigQueryJdbcCustomLoggerTest can read the JDK-internal child-logger list and
assert that driver objects do not leak logger registrations.
-->
- --add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED --add-opens=java.logging/java.util.logging=ALL-UNNAMED
+ @{argLine} --add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED --add-opens=java.logging/java.util.logging=ALL-UNNAMEDorg.apache.maven.pluginsmaven-failsafe-plugin
- --add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED
+
+ @{argLine} -Xmx1536m -XX:MaxDirectMemorySize=1g --add-opens=java.base/java.nio=org.apache.arrow.memory.core,ALL-UNNAMED
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryBaseResultSet.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryBaseResultSet.java
index 97e04b6d9564..ce54b3dbeec4 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryBaseResultSet.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryBaseResultSet.java
@@ -71,6 +71,9 @@ public abstract class BigQueryBaseResultSet extends BigQueryNoOpsResultSet
protected final boolean isNested;
protected boolean isClosed = false;
protected boolean wasNull = false;
+ // getMetaData() is commonly called inside row loops; cache the immutable wrapper and record
+ // the adoption signal once per result set. ResultSet is single-threaded by JDBC contract.
+ private ResultSetMetaData cachedMetaData;
private int fetchSize = -1;
private Job job;
private SQLWarning warnings;
@@ -258,21 +261,26 @@ public boolean wasNull() throws SQLException {
@Override
public ResultSetMetaData getMetaData() throws SQLException {
checkClosed();
- String connectionId = this.statement != null ? this.statement.connectionId : null;
- ResultSetMetaData metaData;
- try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) {
- if (this.isNested) {
- metaData = BigQueryResultSetMetadata.of(this.schemaFieldList, this.statement);
- } else {
- metaData = BigQueryResultSetMetadata.of(this.schema.getFields(), this.statement);
+ if (this.cachedMetaData == null) {
+ String connectionId = this.statement != null ? this.statement.connectionId : null;
+ ResultSetMetaData metaData;
+ try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) {
+ if (this.isNested) {
+ metaData = BigQueryResultSetMetadata.of(this.schemaFieldList, this.statement);
+ } else {
+ metaData = BigQueryResultSetMetadata.of(this.schema.getFields(), this.statement);
+ }
}
+ this.cachedMetaData =
+ BigQueryJdbcContextProxy.wrap(metaData, ResultSetMetaData.class, connectionId);
+ // Always a user call: no driver code invokes ResultSet.getMetaData(), so this is recorded
+ // regardless of whether the owning statement is internal (e.g. the result set that
+ // DatabaseMetaData.getExportedKeys hands back to the user).
+ TelemetryManager.recordFeatureUsage(
+ DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL,
+ "DRIVER_FEATURE_RESULTSET_METADATA_RETRIEVAL");
}
-
- TelemetryManager.recordFeatureUsage(
- DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL,
- "DRIVER_FEATURE_RESULTSET_METADATA_RETRIEVAL");
-
- return BigQueryJdbcContextProxy.wrap(metaData, ResultSetMetaData.class, connectionId);
+ return this.cachedMetaData;
}
@Override
@@ -290,7 +298,11 @@ public int getConcurrency() throws SQLException {
@Override
public Statement getStatement() throws SQLException {
checkClosed();
- return this.statement;
+ if (this.statement == null || this.statement.isInternal()) {
+ return null;
+ }
+ Statement proxy = this.statement.getLogicalStatementProxy();
+ return proxy != null ? proxy : this.statement;
}
@Override
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java
index a10d03c1fcaa..8699c261a60a 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java
@@ -28,6 +28,7 @@
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
+import com.google.cloud.RetryOption;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
@@ -36,6 +37,7 @@
import com.google.cloud.bigquery.DatasetId;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.JobInfo;
+import com.google.cloud.bigquery.JobStatus;
import com.google.cloud.bigquery.Project;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.QueryJobConfiguration.JobCreationMode;
@@ -74,15 +76,18 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
@@ -155,7 +160,6 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
BigQueryJdbcUrlUtility.HTTP_CONNECT_TIMEOUT_PROPERTY_NAME,
BigQueryJdbcUrlUtility.HTTP_READ_TIMEOUT_PROPERTY_NAME,
BigQueryJdbcUrlUtility.BYOID_AUDIENCE_URI_PROPERTY_NAME,
- BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME,
BigQueryJdbcUrlUtility.BYOID_POOL_USER_PROJECT_PROPERTY_NAME,
BigQueryJdbcUrlUtility.BYOID_SA_IMPERSONATION_URI_PROPERTY_NAME,
BigQueryJdbcUrlUtility.BYOID_SUBJECT_TOKEN_TYPE_PROPERTY_NAME,
@@ -176,13 +180,13 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
BigQuery bigQuery;
String connectionUrl;
Set openStatements;
- boolean autoCommit;
+ volatile boolean autoCommit;
int transactionIsolation;
- List sqlWarnings;
+ final List sqlWarnings;
String catalog;
String gcpTelemetryCredentials;
String gcpTelemetryProjectId;
- int holdability;
+ int holdability = ResultSet.CLOSE_CURSORS_AT_COMMIT;
long retryTimeoutInSeconds;
Duration retryTimeoutDuration;
long retryInitialDelayInSeconds;
@@ -191,8 +195,11 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
Duration retryMaxDelayDuration;
// transactionStarted is false by default.
// when autocommit is false transaction starts and session is initialized.
- boolean transactionStarted;
- boolean isClosed;
+ volatile boolean transactionStarted;
+ volatile boolean isClosed;
+ private volatile boolean closeInitiated = false;
+ private final Object closeStateLock = new Object();
+ private final Object lifecycleLock = new Object();
DatasetId defaultDataset;
String location;
boolean enableHighThroughputAPI;
@@ -249,12 +256,19 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
private Context otelContext;
Tracer tracer =
OpenTelemetry.noop().getTracer(BigQueryJdbcOpenTelemetry.INSTRUMENTATION_SCOPE_NAME);
- DatabaseMetaData databaseMetaData;
+
+ private volatile DatabaseMetaData databaseMetaData;
+ private final Object metaDataLock = new Object();
+
+ // A Connection may be used from several threads; compareAndSet keeps the adoption signal at
+ // exactly one record per connection without a lock.
+ private final AtomicBoolean metadataRetrievalRecorded = new AtomicBoolean();
Boolean reqGoogleDriveScope;
private final Properties clientInfo = new Properties();
private boolean isReadOnlyTokenUsed = false;
private final ExecutorService metadataExecutor;
private final ExecutorService queryExecutor;
+ private final SessionState initialSessionState;
/**
* All session-scoped state, published as a single immutable snapshot.
@@ -264,6 +278,35 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
private final AtomicReference sessionState =
new AtomicReference<>(new SessionState(null, Collections.emptyList(), false));
+ static String sanitizeForLog(String value) {
+ if (value == null) {
+ return null;
+ }
+ StringBuilder sb = null;
+ for (int i = 0; i < value.length(); i++) {
+ char c = value.charAt(i);
+ if (c < 0x20 || c == 0x7F) {
+ if (sb == null) {
+ sb = new StringBuilder(value.length()).append(value, 0, i);
+ }
+ sb.append('?');
+ } else if (sb != null) {
+ sb.append(c);
+ }
+ }
+ return sb == null ? value : sb.toString();
+ }
+
+ static String maskPropertyValue(String key, Object value) {
+ if (value == null) {
+ return null;
+ }
+ if (key == null || !SAFE_TO_LOG_PROPERTIES.contains(key)) {
+ return "*****";
+ }
+ return sanitizeForLog(String.valueOf(value));
+ }
+
BigQueryConnection(String url) throws SQLException {
this(url, DataSource.fromUrl(url));
}
@@ -275,23 +318,41 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
.put(BigQueryJdbcOpenTelemetry.CONNECTION_ID_BAGGAGE_KEY, this.connectionId)
.build();
this.otelContext = Context.current().with(baggage);
+ String rawLogLevel = ds.getLogLevel();
+ if (rawLogLevel == null) {
+ rawLogLevel = System.getenv(BigQueryJdbcUrlUtility.LOG_LEVEL_ENV_VAR);
+ }
+ String connLogPath =
+ BigQueryJdbcUrlUtility.resolveEffectiveLogPath(
+ ds.getLogPath(),
+ System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR),
+ rawLogLevel != null && !ds.getEnableGcpLogExporter());
+ BigQueryJdbcRootLogger.registerConnection(this.connectionId, rawLogLevel, connLogPath);
+ boolean initialized = false;
+ ExecutorService createdQueryExecutor = null;
+ ExecutorService createdMetadataExecutor = null;
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(this.connectionId)) {
this.connectionUrl = url;
if (LOG.isLoggable(Level.CONFIG)) {
Properties connectionProps = ds.createProperties();
Properties maskedProps = new Properties();
for (String name : connectionProps.stringPropertyNames()) {
- String value = connectionProps.getProperty(name);
- if (!SAFE_TO_LOG_PROPERTIES.contains(name)) {
- value = "*****";
- }
- maskedProps.setProperty(name, value);
+ maskedProps.setProperty(
+ sanitizeForLog(name), maskPropertyValue(name, connectionProps.getProperty(name)));
}
LOG.config("Connection properties: %s", maskedProps.toString());
}
this.openStatements = ConcurrentHashMap.newKeySet();
this.autoCommit = true;
- this.sqlWarnings = new ArrayList<>();
+ this.sqlWarnings = new CopyOnWriteArrayList<>();
+ if (ds.getLogPath() != null && !BigQueryJdbcUrlUtility.isUrlLogPathAllowed()) {
+ this.sqlWarnings.add(
+ new SQLWarning(
+ String.format(
+ "Ignoring URL/Properties %s because system property %s is false.",
+ BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME,
+ BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY)));
+ }
this.transactionStarted = false;
this.isClosed = false;
@@ -310,12 +371,15 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
BigQueryJdbcOAuthUtility.parseOAuthProperties(ds, this.connectionClassName);
this.isReadOnlyTokenUsed = checkIsReadOnlyTokenUsed(this.authProperties);
this.catalog = ds.getProjectId();
- this.universeDomain = ds.getUniverseDomain();
+ this.universeDomain = ds.resolveUniverseDomain();
this.overrideProperties = ds.getOverrideProperties();
- if (this.universeDomain != null) {
+ // Only record an explicit URL/DataSource universeDomain in overrideProperties for non-JSON
+ // credentials; JSON credentials always keep their own parsed universe_domain.
+ String explicitUniverseDomain = ds.getUniverseDomain();
+ if (explicitUniverseDomain != null) {
this.overrideProperties.put(
- BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME, this.universeDomain);
+ BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME, explicitUniverseDomain);
}
this.reqGoogleDriveScope =
@@ -383,11 +447,12 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
this.unsupportedHTAPIFallback = ds.getUnsupportedHTAPIFallback();
this.maxResults = ds.getMaxResults();
Map queryPropertiesMap = ds.getQueryProperties();
- this.sessionState.set(
+ this.initialSessionState =
new SessionState(
getSessionPropertyFromQueryProperties(queryPropertiesMap),
convertMapToConnectionPropertiesList(queryPropertiesMap),
- false));
+ false);
+ this.sessionState.set(this.initialSessionState);
this.enableWriteAPI = ds.getEnableWriteAPI();
this.writeAPIActivationRowCount = ds.getSwaActivationRowCount();
this.writeAPIAppendRowCount = ds.getSwaAppendRowCount();
@@ -413,11 +478,28 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
this.bigQuery = getBigQueryConnection();
// Cached pool executes queries immediately without queueing and reclaims all idle threads
// when inactive, minimizing resources.
- this.queryExecutor =
+ createdQueryExecutor =
BigQueryJdbcMdc.newCachedThreadPool(String.format("BQ-Query-%s", connectionId));
- this.metadataExecutor =
+ this.queryExecutor = createdQueryExecutor;
+ createdMetadataExecutor =
BigQueryJdbcMdc.newFixedThreadPool(
String.format("BQ-Metadata-%s", connectionId), this.metadataFetchThreadCount);
+ this.metadataExecutor = createdMetadataExecutor;
+ BigQueryJdbcRootLogger.trackConnectionLifecycle(this, this.connectionId);
+ initialized = true;
+ } finally {
+ if (!initialized) {
+ if (createdQueryExecutor != null) {
+ createdQueryExecutor.shutdownNow();
+ }
+ if (createdMetadataExecutor != null) {
+ createdMetadataExecutor.shutdownNow();
+ }
+ BigQueryJdbcRootLogger.closeConnectionHandler(this.connectionId);
+ BigQueryJdbcOpenTelemetry.unregisterConnection(this.connectionId);
+ BigQueryJdbcOpenTelemetry.releaseSdk(this.openTelemetry);
+ this.openTelemetry = null;
+ }
}
}
@@ -511,6 +593,38 @@ public Statement createStatement() throws SQLException {
return currentStatement;
}
+ /**
+ * Creates a {@code Statement} for the driver's own use (for example the {@code isValid}
+ * health-check query). Identical to {@link #createStatement()} except that neither the statement
+ * nor anything it executes is reported as user activity in usage telemetry.
+ */
+ BigQueryStatement createStatementInternal() throws SQLException {
+ checkClosed();
+ BigQueryStatement statement = new BigQueryStatement(this, false);
+ LOG.fine("Internal Statement %s created.", statement);
+ addOpenStatements(statement);
+ return statement;
+ }
+
+ /**
+ * Creates a {@code PreparedStatement} for the driver's own metadata queries. Identical to {@link
+ * #prepareStatement(String)} except that neither the statement, its parameter bindings, nor
+ * anything it executes is reported as user activity in usage telemetry.
+ */
+ BigQueryPreparedStatement prepareStatementInternal(String sql) throws SQLException {
+ return prepareStatementInternal(sql, false);
+ }
+
+ BigQueryPreparedStatement prepareStatementInternal(String sql, boolean skipDryRun)
+ throws SQLException {
+ checkClosed();
+ BigQueryPreparedStatement statement =
+ new BigQueryPreparedStatement(this, sql, skipDryRun, false);
+ LOG.fine("Internal Prepared Statement %s created.", statement);
+ addOpenStatements(statement);
+ return statement;
+ }
+
/**
* Creates and returns a new {@code Statement} object for executing BigQuery SQL queries. This
* method is similar to {@link BigQueryConnection#createStatement()}, but it overrides the type
@@ -887,7 +1001,8 @@ public boolean isValid(int timeout) throws SQLException {
throw new BigQueryJdbcException("timeout must be >= 0");
}
if (!isClosed()) {
- try (Statement statement = createStatement();
+ // Internal statement: a pool health-check must not count as user statements or SELECTs.
+ try (Statement statement = createStatementInternal();
ResultSet rs = statement.executeQuery("SELECT 1")) {
LOG.finer("Running validation query");
if (rs.next()) {
@@ -904,7 +1019,40 @@ public boolean isValid(int timeout) throws SQLException {
@Override
public void abort(Executor executor) throws SQLException {
- close();
+ if (executor == null) {
+ throw new BigQueryJdbcException("Executor cannot be null.");
+ }
+ synchronized (this.closeStateLock) {
+ if (this.isClosed || this.closeInitiated) {
+ return;
+ }
+ this.closeInitiated = true;
+ try {
+ executor.execute(
+ () -> {
+ this.isClosed = true;
+ String previousConnectionId = BigQueryJdbcMdc.getConnectionId();
+ try {
+ BigQueryJdbcMdc.registerInstance(this.connectionId);
+ LOG.fine("Aborting Connection %s", this);
+ closeImpl();
+ } catch (SQLException ex) {
+ LOG.warning(ex, "Failed to release resources during connection abort");
+ } finally {
+ if (previousConnectionId != null
+ && !previousConnectionId.equals(this.connectionId)) {
+ BigQueryJdbcMdc.registerInstance(previousConnectionId);
+ }
+ }
+ });
+ this.isClosed = true;
+ } catch (RuntimeException | Error ex) {
+ if (!this.isClosed) {
+ this.closeInitiated = false;
+ }
+ throw ex;
+ }
+ }
}
@Override
@@ -947,7 +1095,8 @@ public void setClientInfo(Properties properties) {
@Override
public SQLWarning getWarnings() {
- return this.sqlWarnings.isEmpty() ? null : this.sqlWarnings.get(0);
+ Iterator iterator = this.sqlWarnings.iterator();
+ return iterator.hasNext() ? iterator.next() : null;
}
@Override
@@ -1009,10 +1158,10 @@ public void rollback() throws SQLException {
"Cannot rollback without an active transaction. Please set setAutoCommit to false to"
+ " start a transaction.");
}
- rollbackImpl();
+ rollbackImpl(!getAutoCommit());
}
- private void rollbackImpl() throws SQLException {
+ private void rollbackImpl(boolean startNextTransaction) throws SQLException {
try {
QueryJobConfiguration transactionRollbackJobConfig =
QueryJobConfiguration.newBuilder("ROLLBACK TRANSACTION;")
@@ -1020,9 +1169,9 @@ private void rollbackImpl() throws SQLException {
Collections.singletonList(this.sessionState.get().sessionInfo))
.build();
Job rollbackJob = this.bigQuery.create(JobInfo.of(transactionRollbackJobConfig));
- rollbackJob.waitFor();
+ waitForTransactionJob(rollbackJob, "rollback");
this.transactionStarted = false;
- if (!getAutoCommit()) {
+ if (startNextTransaction) {
beginTransaction();
}
} catch (BigQueryException ex) {
@@ -1033,15 +1182,135 @@ private void rollbackImpl() throws SQLException {
}
}
+ private void waitForTransactionJob(Job job, String operationName)
+ throws BigQueryJdbcException, InterruptedException {
+ Job completedJob =
+ this.retryTimeoutInSeconds > 0L
+ ? job.waitFor(RetryOption.totalTimeoutDuration(this.retryTimeoutDuration))
+ : job.waitFor();
+ if (completedJob == null) {
+ throw new BigQueryJdbcException(
+ "Transaction " + operationName + " job no longer exists before completion.");
+ }
+ JobStatus status = completedJob.getStatus();
+ if (status != null) {
+ if (status.getState() != null && status.getState() != JobStatus.State.DONE) {
+ throw new BigQueryJdbcException(
+ "Timed out waiting for transaction " + operationName + " job to complete.");
+ }
+ if (status.getError() != null) {
+ throw new BigQueryJdbcException(
+ "Transaction " + operationName + " job failed: " + status.getError().getMessage());
+ }
+ }
+ }
+
+ /**
+ * Resets mutable JDBC connection state, closes remaining open statements, rolls back any active
+ * transaction without starting a follow-up transaction, and aborts any driver-created BigQuery
+ * session before returning this physical connection for pooled reuse.
+ */
+ void resetForReuse() throws SQLException {
+ try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(this.connectionId)) {
+ LOG.finer("++enter++");
+ synchronized (this.lifecycleLock) {
+ checkClosed();
+ boolean callerInterrupted = Thread.interrupted();
+ try {
+ SQLException exceptionToThrow = closeOpenStatements();
+
+ this.autoCommit = true;
+ boolean rollbackFailed = false;
+ if (this.transactionStarted) {
+ try {
+ rollbackImpl(false);
+ } catch (SQLException e) {
+ rollbackFailed = true;
+ exceptionToThrow = accumulateException(exceptionToThrow, e);
+ }
+ }
+
+ boolean sessionAbortFailed = false;
+ SessionState snapshot = this.sessionState.get();
+ if (snapshot.sessionInfo != null && snapshot.createdByDriver) {
+ try {
+ abortSession(snapshot, true);
+ } catch (SQLException e) {
+ sessionAbortFailed = true;
+ exceptionToThrow = accumulateException(exceptionToThrow, e);
+ }
+ }
+ if (!rollbackFailed && !sessionAbortFailed) {
+ this.sessionState.set(this.initialSessionState);
+ }
+
+ this.clientInfo.clear();
+ this.sqlWarnings.clear();
+ this.holdability = ResultSet.CLOSE_CURSORS_AT_COMMIT;
+
+ if (exceptionToThrow != null) {
+ throw exceptionToThrow;
+ }
+ } finally {
+ if (callerInterrupted) {
+ Thread.currentThread().interrupt();
+ }
+ LOG.finer("++exit++");
+ }
+ }
+ }
+ }
+
+ private SQLException closeOpenStatements() {
+ SQLException exceptionToThrow = null;
+ for (Statement statement : new ArrayList<>(this.openStatements)) {
+ try {
+ statement.close();
+ } catch (SQLException e) {
+ exceptionToThrow = accumulateException(exceptionToThrow, e);
+ }
+ }
+ this.openStatements.clear();
+ return exceptionToThrow;
+ }
+
+ private static SQLException accumulateException(SQLException current, SQLException next) {
+ if (current == null) {
+ return next;
+ }
+ if (current != next) {
+ current.addSuppressed(next);
+ }
+ return current;
+ }
+
@Override
public DatabaseMetaData getMetaData() throws SQLException {
- if (databaseMetaData == null) {
- databaseMetaData = new BigQueryDatabaseMetaData(this);
+ checkClosed();
+ DatabaseMetaData metaData = getMetaDataInternal();
+ // Adoption signal, recorded once per connection on the first user call. Tied to this flag
+ // rather than to instance creation so the driver's own startup lookup does not consume it.
+ if (this.metadataRetrievalRecorded.compareAndSet(false, true)) {
+ TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL);
}
+ return metaData;
+ }
- TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_METADATA_RETRIEVAL);
-
- return databaseMetaData;
+ /**
+ * Same instance as {@link #getMetaData()} without the usage-telemetry record. Driver-internal.
+ */
+ DatabaseMetaData getMetaDataInternal() {
+ DatabaseMetaData result = this.databaseMetaData;
+ if (result == null) {
+ synchronized (this.metaDataLock) {
+ result = this.databaseMetaData;
+ if (result == null) {
+ result = new BigQueryDatabaseMetaData(this);
+ this.databaseMetaData = result;
+ }
+ }
+ }
+ return result;
}
@Override
@@ -1081,152 +1350,146 @@ public void setHoldability(int holdability) throws SQLException {
*/
@Override
public void close() throws SQLException {
- if (isClosed()) {
- return;
+ synchronized (this.closeStateLock) {
+ if (this.isClosed || this.closeInitiated) {
+ return;
+ }
+ this.closeInitiated = true;
}
- LOG.fine("Closing Connection " + this);
- closeImpl();
- }
-
- private void closeImpl() throws SQLException {
- SQLException exceptionToThrow = null;
+ String previousConnectionId = BigQueryJdbcMdc.getConnectionId();
try {
- if (this.bigQueryReadClient != null) {
- this.bigQueryReadClient.shutdown();
- }
- if (this.bigQueryWriteClient != null) {
- this.bigQueryWriteClient.shutdown();
- }
- if (this.metadataExecutor != null) {
- this.metadataExecutor.shutdown();
- }
- if (this.queryExecutor != null) {
- this.queryExecutor.shutdown();
+ BigQueryJdbcMdc.registerInstance(this.connectionId);
+ LOG.fine("Closing Connection %s", this);
+ closeImpl();
+ } finally {
+ if (previousConnectionId != null && !previousConnectionId.equals(this.connectionId)) {
+ BigQueryJdbcMdc.registerInstance(previousConnectionId);
}
+ }
+ }
- for (Statement statement : this.openStatements) {
- try {
- statement.close();
- } catch (SQLException e) {
- if (exceptionToThrow == null) {
- exceptionToThrow = e;
- } else {
- exceptionToThrow.addSuppressed(e);
- }
+ private void closeImpl() throws SQLException {
+ synchronized (this.lifecycleLock) {
+ SQLException exceptionToThrow = null;
+ boolean callerInterrupted = Thread.interrupted();
+ try {
+ if (this.bigQueryReadClient != null) {
+ this.bigQueryReadClient.shutdown();
+ }
+ if (this.bigQueryWriteClient != null) {
+ this.bigQueryWriteClient.shutdown();
+ }
+ if (this.metadataExecutor != null) {
+ this.metadataExecutor.shutdown();
+ }
+ if (this.queryExecutor != null) {
+ this.queryExecutor.shutdown();
}
- }
- this.openStatements.clear();
- if (isTransactionStarted()) {
- try {
- // It looks like there's no need to start a new transaction after a rollback,
- // but the commit behavior is preserved since close() may still fail before isClosed is
- // updated.
- rollbackImpl();
- } catch (SQLException e) {
- if (exceptionToThrow == null) {
- exceptionToThrow = e;
- } else {
- exceptionToThrow.addSuppressed(e);
+ exceptionToThrow = closeOpenStatements();
+
+ if (isTransactionStarted()) {
+ try {
+ rollbackImpl(false);
+ } catch (SQLException e) {
+ exceptionToThrow = accumulateException(exceptionToThrow, e);
}
}
- }
- SessionState snapshot = this.sessionState.get();
- if (snapshot.sessionInfo != null && snapshot.createdByDriver) {
- try {
- abortSession(snapshot);
- } catch (SQLException e) {
- if (exceptionToThrow == null) {
- exceptionToThrow = e;
- } else {
- exceptionToThrow.addSuppressed(e);
+ SessionState snapshot = this.sessionState.get();
+ if (snapshot.sessionInfo != null && snapshot.createdByDriver) {
+ try {
+ abortSession(snapshot, false);
+ } catch (SQLException e) {
+ exceptionToThrow = accumulateException(exceptionToThrow, e);
}
}
- }
- boolean interrupted = Thread.currentThread().isInterrupted();
- InterruptedException terminationInterruptedException = null;
+ boolean interrupted = callerInterrupted || Thread.currentThread().isInterrupted();
+ InterruptedException terminationInterruptedException = null;
- try {
- if (this.bigQueryReadClient != null) {
- if (interrupted) {
+ try {
+ if (this.bigQueryReadClient != null) {
+ if (interrupted) {
+ this.bigQueryReadClient.shutdownNow();
+ } else {
+ this.bigQueryReadClient.awaitTermination(1, TimeUnit.MINUTES);
+ }
+ }
+ if (this.bigQueryWriteClient != null) {
+ if (interrupted) {
+ this.bigQueryWriteClient.shutdownNow();
+ } else {
+ this.bigQueryWriteClient.awaitTermination(1, TimeUnit.MINUTES);
+ }
+ }
+ if (this.metadataExecutor != null) {
+ if (interrupted || !this.metadataExecutor.awaitTermination(10, TimeUnit.SECONDS)) {
+ this.metadataExecutor.shutdownNow();
+ }
+ }
+ if (this.queryExecutor != null) {
+ if (interrupted || !this.queryExecutor.awaitTermination(10, TimeUnit.SECONDS)) {
+ this.queryExecutor.shutdownNow();
+ }
+ }
+ } catch (InterruptedException e) {
+ interrupted = true;
+ terminationInterruptedException = e;
+ if (this.bigQueryReadClient != null) {
this.bigQueryReadClient.shutdownNow();
- } else {
- this.bigQueryReadClient.awaitTermination(1, TimeUnit.MINUTES);
}
- }
- if (this.bigQueryWriteClient != null) {
- if (interrupted) {
+ if (this.bigQueryWriteClient != null) {
this.bigQueryWriteClient.shutdownNow();
- } else {
- this.bigQueryWriteClient.awaitTermination(1, TimeUnit.MINUTES);
}
- }
- if (this.metadataExecutor != null) {
- if (interrupted || !this.metadataExecutor.awaitTermination(10, TimeUnit.SECONDS)) {
+ if (this.metadataExecutor != null) {
this.metadataExecutor.shutdownNow();
}
- }
- if (this.queryExecutor != null) {
- if (interrupted || !this.queryExecutor.awaitTermination(10, TimeUnit.SECONDS)) {
+ if (this.queryExecutor != null) {
this.queryExecutor.shutdownNow();
}
+ } finally {
+ try {
+ if (this.bigQueryReadClient != null) {
+ this.bigQueryReadClient.close();
+ }
+ } finally {
+ if (this.bigQueryWriteClient != null) {
+ this.bigQueryWriteClient.close();
+ }
+ }
}
- } catch (InterruptedException e) {
- interrupted = true;
- terminationInterruptedException = e;
- if (this.bigQueryReadClient != null) {
- this.bigQueryReadClient.shutdownNow();
- }
- if (this.bigQueryWriteClient != null) {
- this.bigQueryWriteClient.shutdownNow();
- }
- if (this.metadataExecutor != null) {
- this.metadataExecutor.shutdownNow();
+
+ if (interrupted) {
+ Thread.currentThread().interrupt();
}
- if (this.queryExecutor != null) {
- this.queryExecutor.shutdownNow();
+ if (terminationInterruptedException != null) {
+ exceptionToThrow =
+ accumulateException(
+ exceptionToThrow,
+ new BigQueryJdbcException(
+ "Interrupted during close", terminationInterruptedException));
}
+ } catch (ConcurrentModificationException ex) {
+ throw new BigQueryJdbcException("Concurrent modification during close", ex);
} finally {
- try {
- if (this.bigQueryReadClient != null) {
- this.bigQueryReadClient.close();
- }
- } finally {
- if (this.bigQueryWriteClient != null) {
- this.bigQueryWriteClient.close();
- }
+ this.isClosed = true;
+ if (callerInterrupted) {
+ Thread.currentThread().interrupt();
}
- }
-
- if (interrupted) {
- Thread.currentThread().interrupt();
- }
- if (terminationInterruptedException != null) {
- BigQueryJdbcException interruptedException =
- new BigQueryJdbcException("Interrupted during close", terminationInterruptedException);
- if (exceptionToThrow == null) {
- exceptionToThrow = interruptedException;
- } else {
- exceptionToThrow.addSuppressed(interruptedException);
+ if (this.connectionId.equals(BigQueryJdbcMdc.getConnectionId())) {
+ BigQueryJdbcMdc.clear();
}
+ BigQueryJdbcRootLogger.closeConnectionHandler(this.connectionId);
+ BigQueryJdbcOpenTelemetry.unregisterConnection(this.connectionId);
+ BigQueryJdbcOpenTelemetry.releaseSdk(this.openTelemetry);
+ this.openTelemetry = null;
}
- } catch (ConcurrentModificationException ex) {
- throw new BigQueryJdbcException("Concurrent modification during close", ex);
- } finally {
- BigQueryJdbcMdc.clear();
- BigQueryJdbcRootLogger.closeConnectionHandler(this.connectionId);
- BigQueryJdbcOpenTelemetry.unregisterConnection(this.connectionId);
- BigQueryJdbcOpenTelemetry.releaseSdk(this.openTelemetry);
- this.openTelemetry = null;
- }
- this.isClosed = true;
-
- if (exceptionToThrow != null) {
- throw exceptionToThrow;
+ if (exceptionToThrow != null) {
+ throw exceptionToThrow;
+ }
}
}
@@ -1244,7 +1507,7 @@ public boolean isClosed() {
}
private void checkClosed() throws BigQueryJdbcException {
- if (isClosed()) {
+ if (this.isClosed || this.closeInitiated) {
throw new BigQueryJdbcException("This " + getClass().getName() + " has been closed");
}
}
@@ -1333,6 +1596,7 @@ private OpenTelemetry getOpenTelemetryInstance() {
effectiveProjectId,
this.credentials,
this.proxyProperties);
+ this.openTelemetry = openTelemetry;
boolean hasExternalOtel = this.customOpenTelemetry != null || this.useGlobalOpenTelemetry;
Logging localLoggingClient = null;
@@ -1344,7 +1608,8 @@ private OpenTelemetry getOpenTelemetryInstance() {
this.gcpTelemetryCredentials,
effectiveProjectId,
this.credentials,
- this.headerProvider);
+ this.headerProvider,
+ this.universeDomain);
}
if (this.enableGcpLogExporter || hasExternalOtel) {
@@ -1589,32 +1854,44 @@ private void commitTransaction() throws BigQueryJdbcException {
Collections.singletonList(this.sessionState.get().sessionInfo))
.build();
Job commitJob = this.bigQuery.create(JobInfo.of(transactionCommitJobConfig));
- commitJob.waitFor();
+ waitForTransactionJob(commitJob, "commit");
this.transactionStarted = false;
+ } catch (BigQueryException ex) {
+ throw new BigQueryJdbcException("Failed to commit transaction", ex);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new BigQueryJdbcException("Interrupted during commitTransaction", ex);
}
}
- private void abortSession(SessionState snapshot) throws BigQueryJdbcException {
+ private void abortSession(SessionState snapshot, boolean throwOnError)
+ throws BigQueryJdbcException {
+ boolean clearLocalSession = false;
try {
- LOG.fine("Aborting session on connection close: %s", snapshot.sessionInfo.getValue());
+ LOG.fine("Aborting session: %s", snapshot.sessionInfo.getValue());
QueryJobConfiguration abortSessionJobConfig =
QueryJobConfiguration.newBuilder("CALL BQ.ABORT_SESSION();")
.setConnectionProperties(Collections.singletonList(snapshot.sessionInfo))
.build();
this.bigQuery.query(abortSessionJobConfig);
+ clearLocalSession = true;
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new BigQueryJdbcException("Interrupted during session abort", ex);
} catch (BigQueryException ex) {
+ if (throwOnError) {
+ throw new BigQueryJdbcException("Failed to abort session", ex);
+ }
LOG.warning(
- "Failed to abort session during session abort (session may have already ended): "
- + ex.getMessage());
+ ex,
+ "Failed to abort session during session abort (session may have already ended): %s",
+ ex.getMessage());
+ clearLocalSession = true;
} finally {
- this.sessionState.updateAndGet(SessionState::withoutSession);
- this.transactionStarted = false;
+ if (clearLocalSession) {
+ this.sessionState.updateAndGet(SessionState::withoutSession);
+ this.transactionStarted = false;
+ }
}
}
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java
index c912fc1e6f7e..fcd6c4c5296f 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java
@@ -1568,7 +1568,8 @@ void appendGraphTableRows(
validateCatalogIdentifier(project);
String formattedSql = replaceSqlParameters(getGraphTablesSqlContent(), project, scope);
- try (PreparedStatement statement = this.connection.prepareStatement(formattedSql, true)) {
+ try (PreparedStatement statement =
+ this.connection.prepareStatementInternal(formattedSql, true)) {
statement.setString(1, effectiveSchemaPattern == null ? "%" : effectiveSchemaPattern);
statement.setString(2, effectiveTablePattern);
@@ -1868,7 +1869,8 @@ void appendGraphColumnRows(
}
String formattedSql = replaceSqlParameters(getGraphColumnsSqlContent(), project, scope);
- try (PreparedStatement statement = this.connection.prepareStatement(formattedSql, true)) {
+ try (PreparedStatement statement =
+ this.connection.prepareStatementInternal(formattedSql, true)) {
statement.setString(1, effectiveSchemaLike);
statement.setString(2, effectiveTableLike);
statement.setString(3, effectiveColumnLike);
@@ -2460,7 +2462,8 @@ private void appendGraphPrimaryKeys(
validateCatalogIdentifier(project);
String formattedSql = replaceSqlParameters(getGraphPrimaryKeysSqlContent(), project, scope);
- try (PreparedStatement statement = this.connection.prepareStatement(formattedSql, true)) {
+ try (PreparedStatement statement =
+ this.connection.prepareStatementInternal(formattedSql, true)) {
statement.setString(1, table); // exact "."
try (ResultSet rs = statement.executeQuery()) {
while (rs.next()) {
@@ -2623,7 +2626,7 @@ public ResultSet getExportedKeys(String catalog, String schema, String table)
validateSchemaIdentifier(schema);
String sql = getExportedKeysSqlContent();
String formattedSql = replaceSqlParameters(sql, catalog, schema);
- PreparedStatement stmt = this.connection.prepareStatement(formattedSql, true);
+ PreparedStatement stmt = this.connection.prepareStatementInternal(formattedSql, true);
if (stmt == null) {
throw new BigQueryJdbcException("Failed to prepare statement for getExportedKeys");
}
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java
index 67e74d74c114..de14bdbfc1da 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java
@@ -150,6 +150,7 @@ public Connection connect(String url, Properties info) throws SQLException {
Level logLevel;
String logPath;
+ boolean ignoredUrlLogPath;
try {
// LogLevel
String logLevelStr =
@@ -161,14 +162,11 @@ public Connection connect(String url, Properties info) throws SQLException {
logLevel = BigQueryJdbcUrlUtility.parseLogLevel(logLevelStr);
// LogPath
- logPath =
+ String urlLogPath =
BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME);
- if (logPath == null) {
- logPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR);
- }
+ String envLogPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR);
- // Fallback to default path only if not specified and not in Cloud-Only mode
String enableGcpLogExporterStr =
BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME);
@@ -179,9 +177,10 @@ public Connection connect(String url, Properties info) throws SQLException {
enableGcpLogExporterStr,
BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME);
}
- if (logPath == null && !enableGcpLogExporter) {
- logPath = BigQueryJdbcUrlUtility.DEFAULT_LOG_PATH;
- }
+ ignoredUrlLogPath = !BigQueryJdbcUrlUtility.isUrlLogPathAllowed() && urlLogPath != null;
+ logPath =
+ BigQueryJdbcUrlUtility.resolveEffectiveLogPath(
+ urlLogPath, envLogPath, !enableGcpLogExporter);
BigQueryJdbcRootLogger.setLevel(logLevel, logPath);
} catch (RuntimeException e) {
@@ -190,34 +189,47 @@ public Connection connect(String url, Properties info) throws SQLException {
}
// Logging starts from here.
- DataSource ds;
- try {
- ds = DataSource.fromUrl(connectionUri);
- } catch (BigQueryJdbcRuntimeException e) {
- LOG.log(Level.SEVERE, "Failed to parse connection URL", e);
- throw new BigQueryJdbcException("Failed to parse connection URL", e);
+ BigQueryConnection connection;
+ try (BigQueryJdbcMdc.MdcCloseable preConnect =
+ BigQueryJdbcRootLogger.openPreConnectScope(logLevel, logPath)) {
+ if (ignoredUrlLogPath) {
+ LOG.warning(
+ "Ignoring URL/Properties %s because system property %s is false.",
+ BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME,
+ BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY);
+ }
+ DataSource ds;
+ try {
+ ds = DataSource.fromUrl(connectionUri);
+ } catch (BigQueryJdbcRuntimeException e) {
+ LOG.log(Level.SEVERE, "Failed to parse connection URL", e);
+ throw new BigQueryJdbcException("Failed to parse connection URL", e);
+ }
+ authType = TelemetryManager.toAuthenticationType(ds.getOAuthType());
+ if (customOpenTelemetryObj instanceof OpenTelemetry) {
+ ds.setCustomOpenTelemetry((OpenTelemetry) customOpenTelemetryObj);
+ }
+ connection = new BigQueryConnection(connectionUri, ds);
}
- authType = TelemetryManager.toAuthenticationType(ds.getOAuthType());
- if (customOpenTelemetryObj instanceof OpenTelemetry) {
- ds.setCustomOpenTelemetry((OpenTelemetry) customOpenTelemetryObj);
+ try (BigQueryJdbcMdc.MdcCloseable mdc =
+ BigQueryJdbcMdc.registerInstance(connection.getConnectionId())) {
+ DatabaseMetaData metaData = connection.getMetaDataInternal();
+ LOG.info(
+ "Driver info : { {Database Product Name : %s}, "
+ + "{Database Product Version : %s}, "
+ + "{Driver Name : %s}, "
+ + "{Driver Version : %s}, "
+ + "{LogLevel : %s}, "
+ + "{LogPath : %s}, "
+ + "{Driver Instance : %s} }",
+ metaData.getDatabaseProductName(),
+ metaData.getDatabaseProductVersion(),
+ metaData.getDriverName(),
+ metaData.getDriverVersion(),
+ logLevel,
+ logPath,
+ this.toString());
}
- BigQueryConnection connection = new BigQueryConnection(connectionUri, ds);
- DatabaseMetaData metaData = connection.getMetaData();
- LOG.info(
- "Driver info : { {Database Product Name : %s}, "
- + "{Database Product Version : %s}, "
- + "{Driver Name : %s}, "
- + "{Driver Version : %s}, "
- + "{LogLevel : %s}, "
- + "{LogPath : %s}, "
- + "{Driver Instance : %s} }",
- metaData.getDatabaseProductName(),
- metaData.getDatabaseProductVersion(),
- metaData.getDriverName(),
- metaData.getDriverVersion(),
- logLevel,
- logPath,
- this.toString());
Connection wrapped = BigQueryJdbcContextProxy.wrap(connection, Connection.class);
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcContextProxy.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcContextProxy.java
index fc724e53e543..a80774e90c31 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcContextProxy.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcContextProxy.java
@@ -35,11 +35,13 @@ class BigQueryJdbcContextProxy implements InvocationHandler {
private final Object target;
private final String connectionId;
+ private final ConnectionLogContext connectionContext;
private final Class> interfaceType;
private BigQueryJdbcContextProxy(Object target, String connectionId, Class> interfaceType) {
this.target = target;
this.connectionId = connectionId;
+ this.connectionContext = BigQueryJdbcRootLogger.resolveContext(connectionId);
this.interfaceType = interfaceType;
}
@@ -132,7 +134,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl
}
// Wrap execution in the context of the active connection for all non-bypassed methods
- try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) {
+ try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.withContext(connectionContext)) {
boolean isFinerLoggable = LOG.isLoggable(Level.FINER);
String targetClassName = null;
if (isFinerLoggable) {
@@ -173,7 +175,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl
// Unified Context Logger: Captures and logs every exception exactly once with the Connection
// context
- try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) {
+ try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.withContext(connectionContext)) {
String errMsg = cause.getMessage() != null ? cause.getMessage() : cause.toString();
LOG.severe("Exception occurred during " + methodName + ": " + errMsg, cause);
}
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLogger.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLogger.java
index 0acea77e5bf6..5d730143ddc4 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLogger.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLogger.java
@@ -17,11 +17,13 @@
package com.google.cloud.bigquery.jdbc;
import java.util.function.Supplier;
+import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class BigQueryJdbcCustomLogger extends Logger {
+ private volatile boolean hasOwnHandlers;
protected BigQueryJdbcCustomLogger(String name, String resourceBundleName) {
super(name, resourceBundleName);
@@ -32,6 +34,42 @@ public BigQueryJdbcCustomLogger(String name) {
this(name, null);
}
+ @Override
+ public synchronized void addHandler(Handler handler) throws SecurityException {
+ super.addHandler(handler);
+ this.hasOwnHandlers = getHandlers().length > 0;
+ }
+
+ @Override
+ public synchronized void removeHandler(Handler handler) throws SecurityException {
+ super.removeHandler(handler);
+ this.hasOwnHandlers = getHandlers().length > 0;
+ }
+
+ @Override
+ public boolean isLoggable(Level level) {
+ if (!isSuperLoggable(level)) {
+ return false;
+ }
+ return isLoggableAfterSuper(level, BigQueryJdbcMdc.getConnectionContext());
+ }
+
+ boolean isSuperLoggable(Level level) {
+ return level != null && super.isLoggable(level);
+ }
+
+ boolean isLoggableAfterSuper(Level level, ConnectionLogContext context) {
+ if (this.getLevel() != null
+ || this.hasOwnHandlers
+ || BigQueryJdbcRootLogger.hasExternalHandler()) {
+ return true;
+ }
+ if (context != null && context.hasExplicitLevel()) {
+ return context.isLoggable(level);
+ }
+ return true;
+ }
+
private void logWithCaller(Level level, Supplier msgSupplier) {
logWithCaller(level, null, msgSupplier);
}
@@ -116,6 +154,7 @@ private static boolean isLoggerClass(String className) {
|| className.equals("com.google.cloud.bigquery.jdbc.BigQueryJdbcResultSetLogger")
|| className.startsWith("com.google.cloud.bigquery.jdbc.BigQueryJdbcRootLogger")
|| className.equals("com.google.cloud.bigquery.jdbc.PerConnectionFileHandler")
+ || className.startsWith("com.google.cloud.bigquery.jdbc.PerConnectionFileHandler$")
|| className.equals(BigQueryJdbcLogRecord.class.getName());
}
}
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdc.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdc.java
index 254cdc5cc2fa..e9638cd8beeb 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdc.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcMdc.java
@@ -33,26 +33,54 @@ class BigQueryJdbcMdc {
private static final BigQueryJdbcCustomLogger LOG =
new BigQueryJdbcCustomLogger(BigQueryJdbcMdc.class.getName());
- private static final InheritableThreadLocal currentConnectionId =
+ private static final InheritableThreadLocal currentContext =
new InheritableThreadLocal<>();
- /** Sets the current connection context on the executing thread. */
+ /**
+ * Sets the current connection context on the executing thread and restores any prior connection
+ * context when closed.
+ */
static MdcCloseable registerInstance(String connectionId) {
- if (connectionId != null) {
- currentConnectionId.set(connectionId);
+ if (connectionId == null) {
+ return withContext(null);
+ }
+ ConnectionLogContext context = BigQueryJdbcRootLogger.getConnectionContext(connectionId);
+ if (context == null) {
+ context = ConnectionLogContext.unregistered(connectionId);
+ }
+ return withContext(context);
+ }
+
+ static MdcCloseable withContext(ConnectionLogContext context) {
+ ConnectionLogContext previous = currentContext.get();
+ if (context != null) {
+ currentContext.set(context);
+ } else {
+ currentContext.remove();
}
- return () -> clear();
+ return () -> {
+ if (previous != null) {
+ currentContext.set(previous);
+ } else {
+ currentContext.remove();
+ }
+ };
+ }
+
+ static ConnectionLogContext getConnectionContext() {
+ return currentContext.get();
}
/**
* Returns the connection ID carried by any registered active connection on the current thread.
*/
static String getConnectionId() {
- return currentConnectionId.get();
+ ConnectionLogContext context = currentContext.get();
+ return context != null ? context.connectionId() : null;
}
static void clear() {
- currentConnectionId.remove();
+ currentContext.remove();
}
/**
@@ -179,18 +207,18 @@ public void execute(Runnable command) {
@Override
protected RunnableFuture newTaskFor(Runnable runnable, T value) {
- return new MdcFutureTask<>(runnable, value, getConnectionId());
+ return new MdcFutureTask<>(runnable, value, getConnectionContext());
}
@Override
protected RunnableFuture newTaskFor(Callable callable) {
- return new MdcFutureTask<>(callable, getConnectionId());
+ return new MdcFutureTask<>(callable, getConnectionContext());
}
private static Runnable wrap(Runnable runnable) {
- String connectionId = getConnectionId();
+ ConnectionLogContext context = getConnectionContext();
return () -> {
- try (MdcCloseable mdc = registerInstance(connectionId)) {
+ try (MdcCloseable mdc = withContext(context)) {
runnable.run();
}
};
@@ -198,21 +226,21 @@ private static Runnable wrap(Runnable runnable) {
}
private static class MdcFutureTask extends FutureTask {
- private final String connectionId;
+ private final ConnectionLogContext context;
- public MdcFutureTask(Runnable runnable, V result, String connectionId) {
+ public MdcFutureTask(Runnable runnable, V result, ConnectionLogContext context) {
super(runnable, result);
- this.connectionId = connectionId;
+ this.context = context;
}
- public MdcFutureTask(Callable callable, String connectionId) {
+ public MdcFutureTask(Callable callable, ConnectionLogContext context) {
super(callable);
- this.connectionId = connectionId;
+ this.context = context;
}
@Override
public void run() {
- try (MdcCloseable mdc = registerInstance(connectionId)) {
+ try (MdcCloseable mdc = withContext(context)) {
super.run();
}
}
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthCallbackServer.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthCallbackServer.java
new file mode 100644
index 000000000000..8a19e6604e5e
--- /dev/null
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthCallbackServer.java
@@ -0,0 +1,431 @@
+/*
+ * Copyright 2026 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.cloud.bigquery.jdbc;
+
+import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException;
+import java.io.BufferedInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketTimeoutException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+// Uses java.net.ServerSocket (java.base) to avoid requiring jdk.httpserver in custom jlink or OSGi
+// runtimes.
+final class BigQueryJdbcOAuthCallbackServer implements AutoCloseable {
+
+ static final int MAX_HTTP_REQUEST_LINE_BYTES = 8192;
+ static final int MAX_HTTP_HEADER_BYTES = 65536;
+
+ private static final int USER_AUTH_DRAIN_TIMEOUT_MS = 50;
+ private static final int USER_AUTH_BACKLOG = 8;
+ private static final int MAX_OAUTH_ERROR_LENGTH = 64;
+
+ private static final String USER_AUTH_SUCCESS_HTML_BODY =
+ "\n"
+ + "Thank you for using JDBC Driver for Google BigQuery!\n"
+ + "You may now close the window.";
+ private static final String USER_AUTH_BAD_REQUEST_HTML_BODY =
+ "\n"
+ + "Authentication could not be completed. Please close this window and retry.\n"
+ + "";
+ private static final String USER_AUTH_NOT_FOUND_HTML_BODY =
+ "Not Found";
+
+ private static final byte[] USER_AUTH_SUCCESS_HTTP_RESPONSE_BYTES =
+ buildHttpResponseBytes(200, "OK", USER_AUTH_SUCCESS_HTML_BODY);
+ private static final byte[] USER_AUTH_BAD_REQUEST_HTTP_RESPONSE_BYTES =
+ buildHttpResponseBytes(400, "Bad Request", USER_AUTH_BAD_REQUEST_HTML_BODY);
+ private static final byte[] USER_AUTH_NOT_FOUND_HTTP_RESPONSE_BYTES =
+ buildHttpResponseBytes(404, "Not Found", USER_AUTH_NOT_FOUND_HTML_BODY);
+
+ private static final BigQueryJdbcCustomLogger LOG =
+ new BigQueryJdbcCustomLogger(BigQueryJdbcOAuthCallbackServer.class.getName());
+
+ @FunctionalInterface
+ interface ServerSocketSupplier {
+ ServerSocket open() throws IOException;
+ }
+
+ @FunctionalInterface
+ interface LoopbackSocketBinder {
+ ServerSocket bind(InetAddress bindAddress, int backlog) throws IOException;
+ }
+
+ static final class HttpCallbackException extends Exception {
+ private HttpCallbackException(String message) {
+ super(message);
+ }
+ }
+
+ private final ServerSocket serverSocket;
+
+ BigQueryJdbcOAuthCallbackServer(ServerSocket serverSocket) {
+ this.serverSocket = serverSocket;
+ }
+
+ URI getCallbackUri() {
+ return buildLoopbackCallbackUri(serverSocket.getInetAddress(), serverSocket.getLocalPort());
+ }
+
+ String waitForAuthorizationCode(String expectedState, int authTimeoutMs, int socketReadTimeoutMs)
+ throws IOException {
+ LOG.finer("++enter++");
+ try {
+ long overallDeadlineNanos = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(authTimeoutMs);
+ String lastRejectedReason = null;
+ while (true) {
+ int acceptTimeoutMs = remainingMillis(overallDeadlineNanos);
+ if (acceptTimeoutMs <= 0) {
+ throw callbackTimeoutException(lastRejectedReason);
+ }
+ serverSocket.setSoTimeout(acceptTimeoutMs);
+ Socket acceptedSocket;
+ try {
+ acceptedSocket = serverSocket.accept();
+ } catch (SocketTimeoutException acceptTimedOut) {
+ throw callbackTimeoutException(lastRejectedReason);
+ }
+ try (Socket socket = acceptedSocket) {
+ String code =
+ handleCallbackConnection(
+ socket, expectedState, overallDeadlineNanos, socketReadTimeoutMs);
+ if (code != null) {
+ return code;
+ }
+ } catch (HttpCallbackException rejectedRequest) {
+ lastRejectedReason = rejectedRequest.getMessage();
+ }
+ }
+ } finally {
+ LOG.finer("++exit++");
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ serverSocket.close();
+ }
+
+ static ServerSocket openLoopbackServerSocket() throws IOException {
+ return openLoopbackServerSocket((address, backlog) -> new ServerSocket(0, backlog, address));
+ }
+
+ static ServerSocket openLoopbackServerSocket(LoopbackSocketBinder binder) throws IOException {
+ InetAddress ipv4Loopback = InetAddress.getByAddress(new byte[] {127, 0, 0, 1});
+ try {
+ return binder.bind(ipv4Loopback, USER_AUTH_BACKLOG);
+ } catch (IOException ipv4Unavailable) {
+ InetAddress ipv6Loopback =
+ InetAddress.getByAddress(new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1});
+ try {
+ return binder.bind(ipv6Loopback, USER_AUTH_BACKLOG);
+ } catch (IOException ipv6Unavailable) {
+ ipv4Unavailable.addSuppressed(ipv6Unavailable);
+ throw ipv4Unavailable;
+ }
+ }
+ }
+
+ static URI buildLoopbackCallbackUri(InetAddress bindAddress, int port) {
+ if (bindAddress instanceof Inet6Address) {
+ return URI.create("http://[::1]:" + port);
+ }
+ return URI.create("http://127.0.0.1:" + port);
+ }
+
+ static Map parseOAuthQueryParameters(String rawQuery)
+ throws HttpCallbackException {
+ if (rawQuery == null || rawQuery.isEmpty()) {
+ return Collections.emptyMap();
+ }
+ Map params = new HashMap<>();
+ String[] pairs = rawQuery.split("&");
+ for (String pair : pairs) {
+ if (pair.isEmpty()) {
+ continue;
+ }
+ int eqIndex = pair.indexOf('=');
+ String rawKey = eqIndex >= 0 ? pair.substring(0, eqIndex) : pair;
+ String rawValue = eqIndex >= 0 ? pair.substring(eqIndex + 1) : "";
+ String key = urlDecodeUtf8(rawKey);
+ String value = urlDecodeUtf8(rawValue);
+ if (("code".equals(key) || "state".equals(key) || "error".equals(key))
+ && params.containsKey(key)) {
+ throw new HttpCallbackException("Duplicate OAuth callback parameter: " + key);
+ }
+ params.put(key, value);
+ }
+ return params;
+ }
+
+ private static String urlDecodeUtf8(String value) throws HttpCallbackException {
+ try {
+ return URLDecoder.decode(value.replace("+", "%2B"), StandardCharsets.UTF_8.name());
+ } catch (IllegalArgumentException e) {
+ throw new HttpCallbackException("Malformed query parameter encoding in OAuth callback.");
+ } catch (UnsupportedEncodingException e) {
+ throw new IllegalStateException("UTF-8 encoding not supported", e);
+ }
+ }
+
+ private static boolean isValidOAuthState(String expectedState, String actualState) {
+ if (actualState == null) {
+ return false;
+ }
+ return MessageDigest.isEqual(
+ expectedState.getBytes(StandardCharsets.UTF_8),
+ actualState.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private static SocketTimeoutException callbackTimeoutException(String lastRejectedReason) {
+ if (lastRejectedReason == null) {
+ return new SocketTimeoutException("Timed out waiting for OAuth authorization callback.");
+ }
+ return new SocketTimeoutException(
+ "Timed out waiting for OAuth authorization callback. Last rejected callback request: "
+ + lastRejectedReason);
+ }
+
+ private static String handleCallbackConnection(
+ Socket socket, String expectedState, long overallDeadlineNanos, int socketReadTimeoutMs)
+ throws HttpCallbackException {
+ long readDeadlineNanos =
+ Math.min(
+ overallDeadlineNanos,
+ System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(socketReadTimeoutMs));
+ try {
+ BufferedInputStream inputStream = new BufferedInputStream(socket.getInputStream());
+ boolean headersDrained = false;
+ try {
+ String requestLine =
+ readHttpRequestLine(
+ socket, inputStream, readDeadlineNanos, MAX_HTTP_REQUEST_LINE_BYTES);
+ if (requestLine == null) {
+ return null;
+ }
+ URI requestUri = parseHttpGetRequestTarget(requestLine);
+ drainHttpHeaders(socket, inputStream, readDeadlineNanos, MAX_HTTP_HEADER_BYTES);
+ headersDrained = true;
+ if (!"/".equals(requestUri.getPath())) {
+ writeHttpResponseQuietly(socket, USER_AUTH_NOT_FOUND_HTTP_RESPONSE_BYTES);
+ return null;
+ }
+ Map queryParams = parseOAuthQueryParameters(requestUri.getRawQuery());
+ if (!isValidOAuthState(expectedState, queryParams.get("state"))) {
+ throw new HttpCallbackException("Missing or invalid state parameter in OAuth callback.");
+ }
+ String error = queryParams.get("error");
+ if (error != null) {
+ writeHttpResponseQuietly(socket, USER_AUTH_BAD_REQUEST_HTTP_RESPONSE_BYTES);
+ throw new BigQueryJdbcRuntimeException(
+ "OAuth authorization failed: " + sanitizeOAuthErrorCode(error));
+ }
+ String code = queryParams.get("code");
+ if (code == null || code.isEmpty()) {
+ writeHttpResponseQuietly(socket, USER_AUTH_BAD_REQUEST_HTTP_RESPONSE_BYTES);
+ throw new BigQueryJdbcRuntimeException(
+ "Could not retrieve the authorization code from OAuth callback.");
+ }
+ writeHttpResponseQuietly(socket, USER_AUTH_SUCCESS_HTTP_RESPONSE_BYTES);
+ return code;
+ } catch (HttpCallbackException callbackError) {
+ if (!headersDrained) {
+ long drainDeadlineNanos =
+ Math.min(
+ overallDeadlineNanos,
+ System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(USER_AUTH_DRAIN_TIMEOUT_MS));
+ drainHttpHeaders(socket, inputStream, drainDeadlineNanos, MAX_HTTP_HEADER_BYTES);
+ }
+ writeHttpResponseQuietly(socket, USER_AUTH_BAD_REQUEST_HTTP_RESPONSE_BYTES);
+ throw callbackError;
+ }
+ } catch (IOException clientIoError) {
+ return null;
+ }
+ }
+
+ private static int remainingMillis(long deadlineNanos) {
+ long remainingNanos = deadlineNanos - System.nanoTime();
+ if (remainingNanos <= 0L) {
+ return 0;
+ }
+ long millis = TimeUnit.NANOSECONDS.toMillis(remainingNanos);
+ if (millis == 0L) {
+ return 1;
+ }
+ return (int) millis;
+ }
+
+ private static int readByteBeforeDeadline(
+ Socket socket, BufferedInputStream inputStream, long deadlineNanos) throws IOException {
+ if (inputStream.available() > 0) {
+ return inputStream.read();
+ }
+ int remainingMs = remainingMillis(deadlineNanos);
+ if (remainingMs <= 0) {
+ throw new SocketTimeoutException("Timed out reading OAuth callback request.");
+ }
+ socket.setSoTimeout(remainingMs);
+ return inputStream.read();
+ }
+
+ private static String readHttpRequestLine(
+ Socket socket, BufferedInputStream inputStream, long deadlineNanos, int maxBytes)
+ throws IOException, HttpCallbackException {
+ int b = readByteBeforeDeadline(socket, inputStream, deadlineNanos);
+ if (b == -1) {
+ return null;
+ }
+ ByteArrayOutputStream buffer = new ByteArrayOutputStream(256);
+ int totalRead = 0;
+ while (true) {
+ if (b == '\n') {
+ break;
+ }
+ if (b == -1) {
+ throw new HttpCallbackException("Incomplete OAuth callback HTTP request line.");
+ }
+ totalRead++;
+ if (totalRead > maxBytes) {
+ throw new HttpCallbackException(
+ "OAuth callback HTTP request line exceeded maximum length.");
+ }
+ if (b == '\r') {
+ int next = readByteBeforeDeadline(socket, inputStream, deadlineNanos);
+ if (next != '\n') {
+ throw new HttpCallbackException("Invalid bare CR in OAuth callback HTTP request line.");
+ }
+ break;
+ }
+ buffer.write(b);
+ b = readByteBeforeDeadline(socket, inputStream, deadlineNanos);
+ }
+ return new String(buffer.toByteArray(), StandardCharsets.US_ASCII);
+ }
+
+ private static void drainHttpHeaders(
+ Socket socket, BufferedInputStream inputStream, long deadlineNanos, int maxHeaderBytes) {
+ int totalRead = 0;
+ int lineChars = 0;
+ try {
+ while (totalRead < maxHeaderBytes) {
+ int b = readByteBeforeDeadline(socket, inputStream, deadlineNanos);
+ if (b == -1) {
+ return;
+ }
+ totalRead++;
+ if (b == '\n') {
+ if (lineChars == 0) {
+ return;
+ }
+ lineChars = 0;
+ } else if (b != '\r') {
+ lineChars++;
+ }
+ }
+ } catch (IOException ignored) {
+ // Best-effort drain so closing the socket after writing the HTTP response avoids TCP RST.
+ }
+ }
+
+ private static URI parseHttpGetRequestTarget(String requestLine) throws HttpCallbackException {
+ String[] parts = requestLine.split(" ", -1);
+ if (parts.length != 3
+ || !"GET".equals(parts[0])
+ || !parts[1].startsWith("/")
+ || (!"HTTP/1.1".equals(parts[2]) && !"HTTP/1.0".equals(parts[2]))) {
+ throw new HttpCallbackException("Invalid HTTP request line on OAuth callback.");
+ }
+ URI requestUri;
+ try {
+ requestUri = new URI(parts[1]);
+ } catch (URISyntaxException e) {
+ throw new HttpCallbackException("Malformed URI in OAuth callback request.");
+ }
+ if (requestUri.getRawAuthority() != null || requestUri.getRawFragment() != null) {
+ throw new HttpCallbackException("Unexpected URI format in OAuth callback request.");
+ }
+ return requestUri;
+ }
+
+ private static String sanitizeOAuthErrorCode(String error) {
+ if (error.isEmpty()) {
+ return "unknown_error";
+ }
+ int limit = Math.min(error.length(), MAX_OAUTH_ERROR_LENGTH);
+ StringBuilder sb = new StringBuilder(limit);
+ for (int i = 0; i < limit; i++) {
+ char c = error.charAt(i);
+ if (c >= 0x21 && c <= 0x7E && c != '"' && c != '\'') {
+ sb.append(c);
+ } else {
+ sb.append('_');
+ }
+ }
+ return sb.toString();
+ }
+
+ private static byte[] buildHttpResponseBytes(
+ int statusCode, String reasonPhrase, String htmlBody) {
+ byte[] bodyBytes = htmlBody.getBytes(StandardCharsets.UTF_8);
+ String headers =
+ "HTTP/1.1 "
+ + statusCode
+ + " "
+ + reasonPhrase
+ + "\r\n"
+ + "Content-Type: text/html; charset=utf-8\r\n"
+ + "Content-Length: "
+ + bodyBytes.length
+ + "\r\n"
+ + "Cache-Control: no-store\r\n"
+ + "X-Content-Type-Options: nosniff\r\n"
+ + "Content-Security-Policy: default-src 'none'\r\n"
+ + "Connection: close\r\n"
+ + "\r\n";
+ byte[] headerBytes = headers.getBytes(StandardCharsets.US_ASCII);
+ byte[] response = new byte[headerBytes.length + bodyBytes.length];
+ System.arraycopy(headerBytes, 0, response, 0, headerBytes.length);
+ System.arraycopy(bodyBytes, 0, response, headerBytes.length, bodyBytes.length);
+ return response;
+ }
+
+ private static void writeHttpResponseQuietly(Socket socket, byte[] responseBytes) {
+ try {
+ OutputStream outputStream = socket.getOutputStream();
+ outputStream.write(responseBytes);
+ outputStream.flush();
+ socket.shutdownOutput();
+ } catch (IOException ignored) {
+ // Peer may have already closed its side of the connection.
+ }
+ }
+}
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthUtility.java
index 49bff5f6982c..0b328cb31f26 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthUtility.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOAuthUtility.java
@@ -27,6 +27,7 @@
import com.google.auth.oauth2.ExternalAccountCredentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ImpersonatedCredentials;
+import com.google.auth.oauth2.PKCEProvider;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.auth.oauth2.UserAuthorizer;
import com.google.auth.oauth2.UserCredentials;
@@ -37,18 +38,14 @@
import com.google.gson.Strictness;
import com.google.gson.stream.JsonReader;
import java.awt.Desktop;
-import java.io.BufferedReader;
+import java.awt.GraphicsEnvironment;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
-import java.net.ServerSocket;
-import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
@@ -57,31 +54,21 @@
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
+import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
+import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
-import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
final class BigQueryJdbcOAuthUtility {
- private static final String USER_AUTH_SUCCESS_HTTP_RESPONSE =
- "HTTP/1.1 200 OK\n"
- + "Content-Length: 300\n"
- + "Connection: close\n"
- + "Content-Type: text/html; charset=utf-8\n"
- + "\n"
- + "\n"
- + "Thank you for using JDBC Driver for Google BigQuery!\n"
- + "You may now close the window.";
-
static final String BIGQUERY_SCOPE = "https://www.googleapis.com/auth/bigquery";
static final String DRIVE_READONLY_SCOPE = "https://www.googleapis.com/auth/drive.readonly";
@@ -90,6 +77,10 @@ final class BigQueryJdbcOAuthUtility {
Arrays.asList(BIGQUERY_SCOPE, DRIVE_READONLY_SCOPE);
private static final int USER_AUTH_TIMEOUT_MS = 120000;
+ private static final int USER_AUTH_SOCKET_READ_TIMEOUT_MS = 1000;
+ private static final int OAUTH_RANDOM_TOKEN_BYTES = 32;
+ private static final SecureRandom SECURE_RANDOM = new SecureRandom();
+ private static final String EXTERNAL_ACCOUNT_TYPE = "external_account";
private static final BigQueryJdbcCustomLogger LOG =
new BigQueryJdbcCustomLogger(BigQueryJdbcOAuthUtility.class.getName());
@@ -217,10 +208,8 @@ static Map parseOAuthProperties(DataSource ds, String callerClas
BigQueryJdbcUrlUtility.BYOID_SUBJECT_TOKEN_TYPE_PROPERTY_NAME,
ds.getByoidSubjectTokenType());
}
- if (ds.getByoidTokenUri() != null) {
- oauthProperties.put(
- BigQueryJdbcUrlUtility.BYOID_TOKEN_URI_PROPERTY_NAME, ds.getByoidTokenUri());
- }
+ oauthProperties.put(
+ BigQueryJdbcUrlUtility.BYOID_TOKEN_URI_PROPERTY_NAME, ds.getByoidTokenUri());
String universeDomain = ds.getUniverseDomain();
if (universeDomain != null) {
@@ -281,7 +270,11 @@ static GoogleCredentials getCredentials(
case GOOGLE_USER_ACCOUNT:
credentials =
getGoogleUserAccountCredentials(
- authProperties, overrideProperties, httpTransportFactory, callerClassName);
+ authProperties,
+ overrideProperties,
+ Boolean.TRUE.equals(reqGoogleDriveScopeBool),
+ httpTransportFactory,
+ callerClassName);
break;
case PRE_GENERATED_TOKEN:
credentials =
@@ -387,8 +380,9 @@ private static GoogleCredentials getGoogleServiceAccountCredentials(
builder.setTokenServerUri(
new URI(overrideProperties.get(BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME)));
}
- if (overrideProperties.containsKey(
- BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)) {
+ if (stream == null
+ && overrideProperties.containsKey(
+ BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)) {
builder.setUniverseDomain(
overrideProperties.get(BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME));
}
@@ -400,21 +394,61 @@ private static GoogleCredentials getGoogleServiceAccountCredentials(
return builder.build();
}
+ @FunctionalInterface
+ interface BrowserOpener {
+ void open(URI authorizationUri) throws IOException;
+ }
+
+ // DefaultPKCEProvider in google-auth-library-oauth2-http 1.58.0 emits a 172-character padded
+ // code_verifier, outside RFC 7636 Section 4.1 (43..128 unreserved characters, unpadded).
+ private static final class Rfc7636PkceProvider implements PKCEProvider {
+ private static final String CHALLENGE_METHOD_S256 = "S256";
+ private final String codeVerifier;
+ private final String codeChallenge;
+
+ private Rfc7636PkceProvider() {
+ byte[] verifierBytes = new byte[OAUTH_RANDOM_TOKEN_BYTES];
+ SECURE_RANDOM.nextBytes(verifierBytes);
+ this.codeVerifier = Base64.getUrlEncoder().withoutPadding().encodeToString(verifierBytes);
+ this.codeChallenge = computeS256Challenge(this.codeVerifier);
+ }
+
+ private static String computeS256Challenge(String verifier) {
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ byte[] hash = digest.digest(verifier.getBytes(StandardCharsets.US_ASCII));
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(hash);
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 MessageDigest not available", e);
+ }
+ }
+
+ @Override
+ public String getCodeVerifier() {
+ return codeVerifier;
+ }
+
+ @Override
+ public String getCodeChallenge() {
+ return codeChallenge;
+ }
+
+ @Override
+ public String getCodeChallengeMethod() {
+ return CHALLENGE_METHOD_S256;
+ }
+ }
+
static UserAuthorizer getUserAuthorizer(
Map authProperties,
Map overrideProperties,
- int port,
+ boolean requestDriveScope,
+ URI callbackUri,
HttpTransportFactory httpTransportFactory,
String callerClassName)
throws URISyntaxException {
LOG.finer("++enter++\t" + callerClassName);
- List scopes = new ArrayList<>();
- scopes.add("https://www.googleapis.com/auth/bigquery");
-
- List responseTypes = new ArrayList<>();
- responseTypes.add("code");
-
ClientId clientId =
ClientId.of(
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_CLIENT_ID_PROPERTY_NAME),
@@ -422,8 +456,9 @@ static UserAuthorizer getUserAuthorizer(
UserAuthorizer.Builder userAuthorizerBuilder =
UserAuthorizer.newBuilder()
.setClientId(clientId)
- .setScopes(scopes)
- .setCallbackUri(URI.create("http://localhost:" + port));
+ .setScopes(requestDriveScope ? BIGQUERY_WITH_DRIVE_SCOPES : DEFAULT_BIGQUERY_SCOPES)
+ .setCallbackUri(callbackUri)
+ .setPKCEProvider(new Rfc7636PkceProvider());
if (httpTransportFactory != null) {
userAuthorizerBuilder.setHttpTransportFactory(httpTransportFactory);
@@ -440,13 +475,23 @@ static UserAuthorizer getUserAuthorizer(
static UserCredentials getCredentialsFromCode(
UserAuthorizer userAuthorizer,
String code,
+ Map overrideProperties,
HttpTransportFactory httpTransportFactory,
String callerClassName)
throws IOException {
LOG.finer("++enter++\t" + callerClassName);
UserCredentials credentials = userAuthorizer.getCredentialsFromCode(code, URI.create(""));
- if (httpTransportFactory != null) {
- credentials = credentials.toBuilder().setHttpTransportFactory(httpTransportFactory).build();
+ String universeDomain =
+ overrideProperties.get(BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME);
+ if (httpTransportFactory != null || universeDomain != null) {
+ UserCredentials.Builder builder = credentials.toBuilder();
+ if (httpTransportFactory != null) {
+ builder.setHttpTransportFactory(httpTransportFactory);
+ }
+ if (universeDomain != null) {
+ builder.setUniverseDomain(universeDomain);
+ }
+ credentials = builder.build();
}
return credentials;
}
@@ -454,53 +499,76 @@ static UserCredentials getCredentialsFromCode(
private static GoogleCredentials getGoogleUserAccountCredentials(
Map authProperties,
Map overrideProperties,
+ boolean requestDriveScope,
HttpTransportFactory httpTransportFactory,
String callerClassName) {
+ if (!isDesktopBrowseSupported()) {
+ throw new BigQueryJdbcRuntimeException("User auth only supported in desktop environments");
+ }
+ return getGoogleUserAccountCredentials(
+ authProperties,
+ overrideProperties,
+ requestDriveScope,
+ httpTransportFactory,
+ callerClassName,
+ BigQueryJdbcOAuthCallbackServer::openLoopbackServerSocket,
+ uri -> Desktop.getDesktop().browse(uri),
+ USER_AUTH_TIMEOUT_MS,
+ USER_AUTH_SOCKET_READ_TIMEOUT_MS);
+ }
+
+ static GoogleCredentials getGoogleUserAccountCredentials(
+ Map authProperties,
+ Map overrideProperties,
+ boolean requestDriveScope,
+ HttpTransportFactory httpTransportFactory,
+ String callerClassName,
+ BigQueryJdbcOAuthCallbackServer.ServerSocketSupplier serverSocketSupplier,
+ BrowserOpener browserOpener,
+ int authTimeoutMs,
+ int socketReadTimeoutMs) {
LOG.finer("++enter++\t" + callerClassName);
try {
- ServerSocket serverSocket = new ServerSocket(0);
- serverSocket.setSoTimeout(USER_AUTH_TIMEOUT_MS);
- int port = serverSocket.getLocalPort();
- UserAuthorizer userAuthorizer =
- getUserAuthorizer(
- authProperties, overrideProperties, port, httpTransportFactory, callerClassName);
-
- URL authURL = userAuthorizer.getAuthorizationUrl("user", "", URI.create(""));
+ UserAuthorizer userAuthorizer;
String code;
-
- if (Desktop.isDesktopSupported()) {
- Desktop.getDesktop().browse(authURL.toURI());
-
- Socket socket = serverSocket.accept();
-
- OutputStream outputStream = socket.getOutputStream();
- PrintWriter printWriter = new PrintWriter(outputStream);
-
- BufferedReader bufferedReader =
- new BufferedReader(new InputStreamReader(socket.getInputStream()));
- String response = bufferedReader.readLine();
-
- Pattern p = Pattern.compile("(?<=code=).*?(?=&|$)");
- Matcher m = p.matcher(response);
-
- if (!m.find()) {
- throw new BigQueryJdbcRuntimeException("Could not retrieve the code for user auth");
- }
- code = m.group();
-
- printWriter.println(USER_AUTH_SUCCESS_HTTP_RESPONSE);
- printWriter.flush();
- socket.close();
- serverSocket.close();
- } else {
- throw new BigQueryJdbcRuntimeException("User auth only supported in desktop environments");
+ try (BigQueryJdbcOAuthCallbackServer callbackServer =
+ new BigQueryJdbcOAuthCallbackServer(serverSocketSupplier.open())) {
+ userAuthorizer =
+ getUserAuthorizer(
+ authProperties,
+ overrideProperties,
+ requestDriveScope,
+ callbackServer.getCallbackUri(),
+ httpTransportFactory,
+ callerClassName);
+ String expectedState = generateOAuthState();
+ URL authUrl = userAuthorizer.getAuthorizationUrl("user", expectedState, URI.create(""));
+ browserOpener.open(authUrl.toURI());
+ code =
+ callbackServer.waitForAuthorizationCode(
+ expectedState, authTimeoutMs, socketReadTimeoutMs);
}
-
- return getCredentialsFromCode(userAuthorizer, code, httpTransportFactory, callerClassName);
+ return getCredentialsFromCode(
+ userAuthorizer, code, overrideProperties, httpTransportFactory, callerClassName);
} catch (IOException | URISyntaxException ex) {
throw new BigQueryJdbcRuntimeException(
"Failed to establish connection using User Account authentication", ex);
+ } finally {
+ LOG.finer("++exit++\t" + callerClassName);
+ }
+ }
+
+ static boolean isDesktopBrowseSupported() {
+ if (GraphicsEnvironment.isHeadless() || !Desktop.isDesktopSupported()) {
+ return false;
}
+ return Desktop.getDesktop().isSupported(Desktop.Action.BROWSE);
+ }
+
+ private static String generateOAuthState() {
+ byte[] stateBytes = new byte[OAUTH_RANDOM_TOKEN_BYTES];
+ SECURE_RANDOM.nextBytes(stateBytes);
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(stateBytes);
}
private static GoogleCredentials getPreGeneratedAccessTokenCredentials(
@@ -630,22 +698,29 @@ private static GoogleCredentials getExternalAccountAuthCredentials(
credentialsPath =
authProperties.get(BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PATH_PROPERTY_NAME);
} else {
+ // Synthesize an external_account JSON payload. token_url is always present here:
+ // DataSource.getByoidTokenUri() derives https://sts./v1/token from an
+ // explicit universeDomain when BYOID_TokenUri is omitted.
jsonObject = new JsonObject();
+ jsonObject.addProperty("type", EXTERNAL_ACCOUNT_TYPE);
for (String property : BigQueryJdbcUrlUtility.BYOID_PROPERTIES) {
+ if (authProperties.get(property) == null) {
+ continue;
+ }
if (Objects.equals(
property, BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME)) {
jsonObject.add(
BYOID_NAME_MAP.get(property),
JsonParser.parseString(authProperties.get(property)).getAsJsonObject());
- } else if (authProperties.containsKey(property)) {
+ } else {
jsonObject.addProperty(BYOID_NAME_MAP.get(property), authProperties.get(property));
}
}
- if (authProperties.containsKey(
- BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)) {
- jsonObject.addProperty(
- "universe_domain",
- authProperties.get(BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME));
+ String byoidUniverseDomain =
+ BigQueryJdbcUrlUtility.normalizeUniverseDomain(
+ authProperties.get(BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME));
+ if (byoidUniverseDomain != null) {
+ jsonObject.addProperty("universe_domain", byoidUniverseDomain);
}
}
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetry.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetry.java
index a885d8b9008b..fffa3d896091 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetry.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetry.java
@@ -204,6 +204,24 @@ public static Logging createLoggingClient(
String effectiveProjectId,
Credentials fallbackCredentials,
HeaderProvider headerProvider) {
+ return createLoggingClient(
+ enableGcpLogExporter,
+ customOpenTelemetry,
+ effectiveCredentials,
+ effectiveProjectId,
+ fallbackCredentials,
+ headerProvider,
+ null);
+ }
+
+ static Logging createLoggingClient(
+ boolean enableGcpLogExporter,
+ OpenTelemetry customOpenTelemetry,
+ String effectiveCredentials,
+ String effectiveProjectId,
+ Credentials fallbackCredentials,
+ HeaderProvider headerProvider,
+ String universeDomain) {
if (!enableGcpLogExporter || customOpenTelemetry != null) {
return null;
@@ -225,6 +243,9 @@ public static Logging createLoggingClient(
if (headerProvider != null) {
loggingOptionsBuilder.setHeaderProvider(headerProvider);
}
+ if (universeDomain != null) {
+ loggingOptionsBuilder.setUniverseDomain(universeDomain);
+ }
return loggingOptionsBuilder.build().getService();
} catch (Exception e) {
throw new BigQueryJdbcRuntimeException("Failed to initialize Logging client", e);
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java
index 2e5753fa2c46..925e42d155bf 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java
@@ -48,6 +48,7 @@ public final class BigQueryJdbcResultSetLogger {
private final BigQueryJdbcCustomLogger delegate;
private final String targetClassName;
+ private final ConnectionLogContext connectionContext;
private final String connectionId;
private volatile BigQueryJdbcResultSetLogger arrowStructLogger;
@@ -56,25 +57,36 @@ public final class BigQueryJdbcResultSetLogger {
private volatile BigQueryJdbcResultSetLogger jsonArrayLogger;
private BigQueryJdbcResultSetLogger(
- BigQueryJdbcCustomLogger delegate, String targetClassName, String connectionId) {
+ BigQueryJdbcCustomLogger delegate,
+ String targetClassName,
+ ConnectionLogContext connectionContext) {
this.delegate = delegate;
this.targetClassName = targetClassName;
- this.connectionId = connectionId;
+ this.connectionContext = connectionContext;
+ this.connectionId = connectionContext != null ? connectionContext.connectionId() : null;
}
public static BigQueryJdbcResultSetLogger getLogger(Class> clazz) {
- return getLogger(clazz, null);
+ return getLogger(clazz, (ConnectionLogContext) null);
}
public static BigQueryJdbcResultSetLogger getLogger(Class> clazz, String connectionId) {
+ if (connectionId == null || connectionId.isEmpty()) {
+ return getLogger(clazz, (ConnectionLogContext) null);
+ }
+ return getLogger(clazz, BigQueryJdbcRootLogger.resolveContext(connectionId));
+ }
+
+ static BigQueryJdbcResultSetLogger getLogger(
+ Class> clazz, ConnectionLogContext connectionContext) {
String className = clazz.getName();
BigQueryJdbcCustomLogger delegate =
DELEGATES.computeIfAbsent(className, BigQueryJdbcCustomLogger::new);
- if (connectionId == null) {
+ if (connectionContext == null) {
return GLOBAL_FACADES.computeIfAbsent(
className, k -> new BigQueryJdbcResultSetLogger(delegate, k, null));
}
- return new BigQueryJdbcResultSetLogger(delegate, className, connectionId);
+ return new BigQueryJdbcResultSetLogger(delegate, className, connectionContext);
}
public String getConnectionId() {
@@ -87,60 +99,75 @@ BigQueryJdbcCustomLogger delegate() {
}
public boolean isLoggable(Level level) {
- return delegate.isLoggable(level);
+ if (!delegate.isSuperLoggable(level)) {
+ return false;
+ }
+ ConnectionLogContext ctx =
+ connectionContext != null ? connectionContext : BigQueryJdbcMdc.getConnectionContext();
+ return delegate.isLoggableAfterSuper(level, ctx);
}
public BigQueryJdbcResultSetLogger getArrowStructLogger() {
if (arrowStructLogger == null) {
- arrowStructLogger = getLogger(BigQueryArrowStruct.class, connectionId);
+ arrowStructLogger = getLogger(BigQueryArrowStruct.class, connectionContext);
}
return arrowStructLogger;
}
public BigQueryJdbcResultSetLogger getJsonStructLogger() {
if (jsonStructLogger == null) {
- jsonStructLogger = getLogger(BigQueryJsonStruct.class, connectionId);
+ jsonStructLogger = getLogger(BigQueryJsonStruct.class, connectionContext);
}
return jsonStructLogger;
}
public BigQueryJdbcResultSetLogger getArrowArrayLogger() {
if (arrowArrayLogger == null) {
- arrowArrayLogger = getLogger(BigQueryArrowArray.class, connectionId);
+ arrowArrayLogger = getLogger(BigQueryArrowArray.class, connectionContext);
}
return arrowArrayLogger;
}
public BigQueryJdbcResultSetLogger getJsonArrayLogger() {
if (jsonArrayLogger == null) {
- jsonArrayLogger = getLogger(BigQueryJsonArray.class, connectionId);
+ jsonArrayLogger = getLogger(BigQueryJsonArray.class, connectionContext);
}
return jsonArrayLogger;
}
/**
- * Stamps the connection ID into {@code params[0]} and forwards to the shared logger. Does not
- * touch the record's source class/method: hot-path callers set them explicitly, and cold-path
- * callers ({@code severe}, {@code warning}) rely on {@link
+ * Stamps the {@link ConnectionLogContext} into {@code params[0]} and forwards to the shared
+ * logger. Does not touch the record's source class/method: hot-path callers set them explicitly,
+ * and cold-path callers ({@code severe}, {@code warning}) rely on {@link
* BigQueryJdbcCustomLogger.BigQueryJdbcLogRecord} to infer them lazily.
*/
public void log(LogRecord record) {
- if (connectionId != null) {
+ if (record == null || !isLoggable(record.getLevel())) {
+ return;
+ }
+ if (connectionContext != null) {
Object[] existingParams = record.getParameters();
if (existingParams == null || existingParams.length == 0) {
- record.setParameters(new Object[] {connectionId});
- } else {
+ record.setParameters(new Object[] {connectionContext});
+ } else if (!(existingParams[0] instanceof ConnectionLogContext)) {
Object[] newParams = new Object[existingParams.length + 1];
- newParams[0] = connectionId;
+ newParams[0] = connectionContext;
System.arraycopy(existingParams, 0, newParams, 1, existingParams.length);
record.setParameters(newParams);
}
+ if (BigQueryJdbcMdc.getConnectionContext() != connectionContext) {
+ try (BigQueryJdbcMdc.MdcCloseable ignored =
+ BigQueryJdbcMdc.withContext(connectionContext)) {
+ delegate.log(record);
+ }
+ return;
+ }
}
delegate.log(record);
}
private void logTrace(Level level, String methodName, String msg) {
- if (!delegate.isLoggable(level)) {
+ if (!isLoggable(level)) {
return;
}
LogRecord record = new LogRecord(level, msg);
@@ -150,15 +177,18 @@ private void logTrace(Level level, String methodName, String msg) {
}
private void logTrace(Level level, String methodName, Supplier msgSupplier) {
- if (!delegate.isLoggable(level)) {
+ if (!isLoggable(level)) {
return;
}
- logTrace(level, methodName, msgSupplier.get());
+ LogRecord record = new LogRecord(level, msgSupplier.get());
+ record.setSourceClassName(targetClassName);
+ record.setSourceMethodName(methodName);
+ log(record);
}
/** Cold path: builds a record whose caller is inferred lazily by the formatter. */
private void logWithCaller(Level level, Throwable thrown, String msg) {
- if (!delegate.isLoggable(level)) {
+ if (!isLoggable(level)) {
return;
}
LogRecord record = new BigQueryJdbcCustomLogger.BigQueryJdbcLogRecord(level, msg);
@@ -226,7 +256,7 @@ public void fine(Supplier msgSupplier) {
}
public void warning(String format, Object... args) {
- if (!delegate.isLoggable(Level.WARNING)) {
+ if (!isLoggable(Level.WARNING)) {
return;
}
String message = (args == null || args.length == 0) ? format : String.format(format, args);
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java
index b6e1b13afc7e..4b2a94b123a3 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java
@@ -21,30 +21,55 @@
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.context.Context;
import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
import java.lang.management.ManagementFactory;
+import java.lang.ref.PhantomReference;
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.nio.file.InvalidPathException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
+import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/** This class is used to log messages from the BigQuery JDBC Driver. */
class BigQueryJdbcRootLogger {
+ private static final boolean isTest = Boolean.getBoolean("JDBC_TESTS");
+ private static volatile boolean externalHandlerAttached = false;
+
/**
* Note: Each connection will have its own file handler with the level and logPath specified in
* the connection properties. But the logs will be driver logs and not connection specific.
*/
- private static final Logger logger = Logger.getLogger("com.google.cloud.bigquery");
+ private static final Logger logger = createRootLogger();
private static final Logger storageLogger = Logger.getLogger("com.google.cloud.bigquery.storage");
- private static final boolean isTest = Boolean.getBoolean("JDBC_TESTS");
- private static Handler fileHandler = null;
+ private static final long CLEANER_IDLE_KEEPALIVE_MS = 60_000L;
+ private static final ReentrantLock HANDLER_LOCK = new ReentrantLock();
+ private static final ConcurrentHashMap activeConnections =
+ new ConcurrentHashMap<>();
+ private static final Map handlersByPath = new HashMap<>();
+ private static final ReferenceQueue CLEANUP_QUEUE = new ReferenceQueue<>();
+ private static Thread cleanerThread = null;
+ private static int trackedConnectionCount = 0;
+ private static int activePreConnectScopes = 0;
+ private static Level externalRootLevel = null;
+ private static Level lastManagedRootLevel = logger.getLevel();
static final String PROCESS_ID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
@@ -75,12 +100,98 @@ static String getThreadName(long threadId) {
static {
logger.setUseParentHandlers(false);
storageLogger.setUseParentHandlers(true);
- if (isTest) {
- ConsoleHandler consoleHandler = new ConsoleHandler();
+ if (isTest && !hasDriverConsoleHandler(logger)) {
+ ConsoleHandler consoleHandler = new TestConsoleHandler();
consoleHandler.setLevel(Level.SEVERE);
consoleHandler.setFormatter(getFormatter());
logger.addHandler(consoleHandler);
}
+ externalHandlerAttached = scanForExternalHandler(logger);
+ }
+
+ private static Logger createRootLogger() {
+ LogManager manager = LogManager.getLogManager();
+ Logger existing = manager.getLogger("com.google.cloud.bigquery");
+ if (existing != null) {
+ return existing;
+ }
+ RootDriverLogger customRoot = new RootDriverLogger("com.google.cloud.bigquery");
+ if (manager.addLogger(customRoot)) {
+ return customRoot;
+ }
+ return Logger.getLogger("com.google.cloud.bigquery");
+ }
+
+ private static final class RootDriverLogger extends Logger {
+ RootDriverLogger(String name) {
+ super(name, null);
+ super.setUseParentHandlers(false);
+ }
+
+ @Override
+ public synchronized void addHandler(Handler handler) throws SecurityException {
+ super.addHandler(handler);
+ externalHandlerAttached = scanForExternalHandler(this);
+ }
+
+ @Override
+ public synchronized void removeHandler(Handler handler) throws SecurityException {
+ super.removeHandler(handler);
+ externalHandlerAttached = scanForExternalHandler(this);
+ }
+
+ @Override
+ public synchronized void setUseParentHandlers(boolean useParentHandlers) {
+ super.setUseParentHandlers(useParentHandlers);
+ externalHandlerAttached = scanForExternalHandler(this);
+ }
+ }
+
+ private static final class TestConsoleHandler extends ConsoleHandler {}
+
+ private static boolean hasDriverConsoleHandler(Logger target) {
+ String expectedName = TestConsoleHandler.class.getName();
+ for (Handler h : target.getHandlers()) {
+ if (h instanceof TestConsoleHandler
+ || (h != null && expectedName.equals(h.getClass().getName()))) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean isDriverOwnedHandler(Handler handler) {
+ if (handler == null) {
+ return false;
+ }
+ if (handler instanceof PerConnectionFileHandler
+ || handler instanceof OpenTelemetryJulHandler
+ || handler instanceof TestConsoleHandler) {
+ return true;
+ }
+ String className = handler.getClass().getName();
+ return className.equals(PerConnectionFileHandler.class.getName())
+ || className.equals(OpenTelemetryJulHandler.class.getName())
+ || className.equals(TestConsoleHandler.class.getName());
+ }
+
+ static boolean scanForExternalHandler(Logger target) {
+ if (target.getUseParentHandlers()) {
+ return true;
+ }
+ for (Handler h : target.getHandlers()) {
+ if (!isDriverOwnedHandler(h)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ static boolean hasExternalHandler() {
+ if (logger instanceof RootDriverLogger) {
+ return externalHandlerAttached;
+ }
+ return scanForExternalHandler(logger);
}
public static Formatter getFormatter() {
@@ -102,12 +213,10 @@ private void appendTraceBlock(StringBuilder sb) {
@Override
public String format(LogRecord record) {
String date = DATE_FORMATTER.format(Instant.ofEpochMilli(record.getMillis()));
- String connectionId = BigQueryJdbcMdc.getConnectionId();
+ ConnectionLogContext paramContext = ConnectionLogContext.extractFromParameters(record);
+ String connectionId = paramContext != null ? paramContext.connectionId() : null;
if (connectionId == null || connectionId.isEmpty()) {
- Object[] params = record.getParameters();
- if (params != null && params.length > 0 && params[0] instanceof String) {
- connectionId = (String) params[0];
- }
+ connectionId = BigQueryJdbcMdc.getConnectionId();
}
String connStr =
(connectionId != null && !connectionId.isEmpty()) ? connectionId : "NO_CONN";
@@ -148,8 +257,8 @@ public String format(LogRecord record) {
.append(System.lineSeparator());
if (record.getThrown() != null) {
- java.io.StringWriter sw = new java.io.StringWriter();
- record.getThrown().printStackTrace(new java.io.PrintWriter(sw));
+ StringWriter sw = new StringWriter();
+ record.getThrown().printStackTrace(new PrintWriter(sw));
sb.append(sw.toString()).append(System.lineSeparator());
}
@@ -162,48 +271,446 @@ public static Logger getRootLogger() {
return logger;
}
+ static ConnectionLogContext getConnectionContext(String connectionId) {
+ if (connectionId == null) {
+ return null;
+ }
+ ConnectionLogConfig config = activeConnections.get(connectionId);
+ return config != null ? config.context : null;
+ }
+
+ static ConnectionLogContext resolveContext(String connectionId) {
+ if (connectionId == null || connectionId.isEmpty()) {
+ return null;
+ }
+ ConnectionLogConfig config = activeConnections.get(connectionId);
+ return config != null ? config.context : ConnectionLogContext.unregistered(connectionId);
+ }
+
+ static boolean isConnectionActive(String connectionId) {
+ return connectionId != null && activeConnections.containsKey(connectionId);
+ }
+
+ static int activeConnectionCount() {
+ return activeConnections.size();
+ }
+
public static void setLevel(Level level, String logPath) throws IOException {
- if (level != Level.OFF) {
- if (logPath != null) {
- setPath(logPath, level);
+ HANDLER_LOCK.lock();
+ try {
+ captureExternalRootLevelLocked();
+ updateEffectiveRootLevelLocked();
+ } finally {
+ HANDLER_LOCK.unlock();
+ }
+ }
+
+ static BigQueryJdbcMdc.MdcCloseable openPreConnectScope(Level level, String logPath) {
+ Level effectiveLevel = level != null ? level : Level.OFF;
+ ManagedFileHandler tempHandler = null;
+ boolean countedScope = false;
+ HANDLER_LOCK.lock();
+ try {
+ captureExternalRootLevelLocked();
+ if (effectiveLevel != Level.OFF) {
+ activePreConnectScopes++;
+ countedScope = true;
+ if (logPath != null) {
+ try {
+ tempHandler = acquireHandlerLocked(logPath);
+ } catch (Exception ex) {
+ logger.log(Level.WARNING, "Log File warning", ex);
+ }
+ }
+ }
+ updateEffectiveRootLevelLocked();
+ } finally {
+ HANDLER_LOCK.unlock();
+ }
+ Path preConnectDir = tempHandler != null ? tempHandler.handler.getBaseLogPath() : null;
+ BigQueryJdbcMdc.MdcCloseable mdcScope =
+ BigQueryJdbcMdc.withContext(
+ ConnectionLogContext.preConnect(effectiveLevel.intValue(), preConnectDir));
+ final ManagedFileHandler acquired = tempHandler;
+ final boolean decrementScope = countedScope;
+ return () -> {
+ try {
+ mdcScope.close();
+ } finally {
+ if (decrementScope || acquired != null) {
+ HANDLER_LOCK.lock();
+ try {
+ captureExternalRootLevelLocked();
+ if (decrementScope && activePreConnectScopes > 0) {
+ activePreConnectScopes--;
+ }
+ releaseHandlerLocked(acquired);
+ updateEffectiveRootLevelLocked();
+ } finally {
+ HANDLER_LOCK.unlock();
+ }
+ }
}
- } else {
- for (Handler h : logger.getHandlers()) {
- h.close();
- logger.removeHandler(h);
+ };
+ }
+
+ static void registerConnection(String connectionId, String rawLogLevel, String logPath) {
+ if (connectionId == null || connectionId.isEmpty()) {
+ return;
+ }
+ HANDLER_LOCK.lock();
+ try {
+ captureExternalRootLevelLocked();
+ drainCleanupQueueLocked();
+ Level connLevel =
+ rawLogLevel != null
+ ? BigQueryJdbcUrlUtility.parseLogLevel(rawLogLevel)
+ : (externalRootLevel != null ? externalRootLevel : Level.OFF);
+ if (connLevel == null) {
+ connLevel = Level.OFF;
}
- fileHandler = null;
+ ManagedFileHandler managed = null;
+ if (connLevel != Level.OFF && logPath != null) {
+ try {
+ managed = acquireHandlerLocked(logPath);
+ managed.handler.registerConnection(connectionId, connLevel);
+ } catch (Exception ex) {
+ logger.log(Level.WARNING, "Log File warning", ex);
+ }
+ }
+ ConnectionLogConfig previous =
+ activeConnections.put(
+ connectionId,
+ new ConnectionLogConfig(
+ new ConnectionLogContext(connectionId, connLevel.intValue()),
+ connLevel,
+ managed));
+ if (previous != null) {
+ closeConfigLocked(connectionId, previous);
+ }
+ updateEffectiveRootLevelLocked();
+ } finally {
+ HANDLER_LOCK.unlock();
}
- logger.setLevel(level);
}
- static void setPath(String logPath, Level level) {
+ static void trackConnectionLifecycle(BigQueryConnection connection, String connectionId) {
+ if (connection == null || connectionId == null) {
+ return;
+ }
+ HANDLER_LOCK.lock();
try {
- if (logPath == null) {
- logPath = "";
+ boolean reaped = drainCleanupQueueLocked();
+ ConnectionLogConfig config = activeConnections.get(connectionId);
+ if (config != null) {
+ detachCleanableLocked(config);
+ config.cleanable = new ConnectionCleanable(connection, connectionId, CLEANUP_QUEUE);
+ trackedConnectionCount++;
+ ensureCleanerRunningLocked();
}
- if (!logPath.isEmpty() && !logPath.endsWith("/")) {
- logPath = logPath + "/";
+ if (reaped) {
+ updateEffectiveRootLevelLocked();
}
+ } finally {
+ HANDLER_LOCK.unlock();
+ }
+ }
- if (fileHandler != null) {
- fileHandler.close();
- logger.removeHandler(fileHandler);
+ private static void ensureCleanerRunningLocked() {
+ if (cleanerThread != null) {
+ return;
+ }
+ try {
+ Thread cleaner =
+ new Thread(
+ BigQueryJdbcRootLogger::runConnectionCleanerLoop,
+ "BigQuery-JDBC-Connection-Log-Cleaner");
+ cleaner.setDaemon(true);
+ cleaner.setContextClassLoader(BigQueryJdbcRootLogger.class.getClassLoader());
+ cleaner.start();
+ cleanerThread = cleaner;
+ } catch (OutOfMemoryError | SecurityException ignored) {
+ // Best-effort daemon: drainCleanupQueueLocked() still reclaims queued refs on future calls.
+ }
+ }
+
+ private static boolean drainCleanupQueueLocked() {
+ boolean reapedAny = false;
+ Reference extends BigQueryConnection> ref;
+ while ((ref = CLEANUP_QUEUE.poll()) != null) {
+ if (ref instanceof ConnectionCleanable && reapSingleLocked((ConnectionCleanable) ref)) {
+ reapedAny = true;
}
+ }
+ return reapedAny;
+ }
- fileHandler = new PerConnectionFileHandler(logPath, level);
- fileHandler.setLevel(level);
- logger.addHandler(fileHandler);
- logger.setUseParentHandlers(false);
+ private static boolean reapSingleLocked(ConnectionCleanable ref) {
+ ref.clear();
+ ConnectionLogConfig current = activeConnections.get(ref.connectionId);
+ if (current == null || current.cleanable != ref) {
+ return false;
+ }
+ captureExternalRootLevelLocked();
+ activeConnections.remove(ref.connectionId);
+ closeConfigLocked(ref.connectionId, current);
+ return true;
+ }
- } catch (Exception ex) {
- logger.warning("Log File warning : " + ex);
+ private static void runConnectionCleanerLoop() {
+ BigQueryJdbcMdc.clear();
+ while (true) {
+ try {
+ boolean waitIndefinitely;
+ HANDLER_LOCK.lock();
+ try {
+ if (drainCleanupQueueLocked()) {
+ updateEffectiveRootLevelLocked();
+ }
+ waitIndefinitely = trackedConnectionCount > 0;
+ Thread.interrupted();
+ } finally {
+ HANDLER_LOCK.unlock();
+ }
+
+ Reference extends BigQueryConnection> ref =
+ waitIndefinitely
+ ? CLEANUP_QUEUE.remove()
+ : CLEANUP_QUEUE.remove(CLEANER_IDLE_KEEPALIVE_MS);
+
+ HANDLER_LOCK.lock();
+ try {
+ boolean reaped =
+ (ref instanceof ConnectionCleanable) && reapSingleLocked((ConnectionCleanable) ref);
+ try {
+ if (drainCleanupQueueLocked()) {
+ reaped = true;
+ }
+ } finally {
+ if (reaped) {
+ updateEffectiveRootLevelLocked();
+ }
+ }
+ if (ref == null && trackedConnectionCount == 0 && CLEANUP_QUEUE.poll() == null) {
+ if (cleanerThread == Thread.currentThread()) {
+ cleanerThread = null;
+ }
+ return;
+ }
+ } finally {
+ HANDLER_LOCK.unlock();
+ }
+ } catch (InterruptedException ignored) {
+ // Woken when trackedConnectionCount reaches 0 to switch to the idle keep-alive window.
+ } catch (Throwable ignored) {
+ // Survive OOM or unexpected errors while cleaner is active.
+ }
}
}
public static void closeConnectionHandler(String connectionId) {
- if (fileHandler instanceof PerConnectionFileHandler) {
- ((PerConnectionFileHandler) fileHandler).closeHandler(connectionId);
+ if (connectionId == null) {
+ return;
+ }
+ HANDLER_LOCK.lock();
+ try {
+ captureExternalRootLevelLocked();
+ drainCleanupQueueLocked();
+ ConnectionLogConfig removed = activeConnections.remove(connectionId);
+ if (removed != null) {
+ closeConfigLocked(connectionId, removed);
+ }
+ updateEffectiveRootLevelLocked();
+ } finally {
+ HANDLER_LOCK.unlock();
+ }
+ }
+
+ static void resetForTest() {
+ HANDLER_LOCK.lock();
+ try {
+ for (ConnectionLogConfig cfg : activeConnections.values()) {
+ detachCleanableLocked(cfg);
+ cfg.context.setLevelValue(ConnectionLogContext.OFF_VALUE);
+ }
+ trackedConnectionCount = 0;
+ activeConnections.clear();
+ for (ManagedFileHandler managed : handlersByPath.values()) {
+ try {
+ managed.handler.close();
+ } catch (Exception ignored) {
+ } finally {
+ logger.removeHandler(managed.handler);
+ }
+ }
+ handlersByPath.clear();
+ activePreConnectScopes = 0;
+ externalRootLevel = null;
+ lastManagedRootLevel = Level.OFF;
+ logger.setUseParentHandlers(false);
+ logger.setLevel(Level.OFF);
+ externalHandlerAttached = scanForExternalHandler(logger);
+ } finally {
+ HANDLER_LOCK.unlock();
+ }
+ }
+
+ private static void detachCleanableLocked(ConnectionLogConfig config) {
+ if (config.cleanable != null) {
+ config.cleanable.clear();
+ config.cleanable = null;
+ if (trackedConnectionCount > 0) {
+ trackedConnectionCount--;
+ }
+ if (trackedConnectionCount == 0
+ && cleanerThread != null
+ && cleanerThread != Thread.currentThread()) {
+ cleanerThread.interrupt();
+ }
+ }
+ }
+
+ private static void closeConfigLocked(String connectionId, ConnectionLogConfig config) {
+ detachCleanableLocked(config);
+ config.context.setLevelValue(ConnectionLogContext.OFF_VALUE);
+ if (config.managedHandler != null) {
+ try {
+ config.managedHandler.handler.closeHandler(connectionId);
+ } finally {
+ releaseHandlerLocked(config.managedHandler);
+ }
+ }
+ }
+
+ private static void captureExternalRootLevelLocked() {
+ if (!hasExternalHandler()) {
+ externalRootLevel = null;
+ return;
+ }
+ Level current = logger.getLevel();
+ if (current != lastManagedRootLevel) {
+ externalRootLevel = current;
+ }
+ }
+
+ private static Level resolveInheritedLevel(Logger target) {
+ for (Logger parent = target.getParent(); parent != null; parent = parent.getParent()) {
+ Level parentLevel = parent.getLevel();
+ if (parentLevel != null) {
+ return parentLevel;
+ }
+ }
+ return Level.INFO;
+ }
+
+ private static void updateEffectiveRootLevelLocked() {
+ if (activePreConnectScopes > 0) {
+ lastManagedRootLevel = Level.ALL;
+ logger.setLevel(Level.ALL);
+ return;
+ }
+ Level effective = externalRootLevel != null ? externalRootLevel : Level.OFF;
+ int minVal = effective != null ? effective.intValue() : Level.OFF.intValue();
+ for (ConnectionLogConfig cfg : activeConnections.values()) {
+ int connVal = cfg.level.intValue();
+ if (connVal < minVal) {
+ minVal = connVal;
+ effective = cfg.level;
+ }
+ }
+ if (externalRootLevel == null && hasExternalHandler()) {
+ Level inherited = resolveInheritedLevel(logger);
+ if (minVal >= inherited.intValue()) {
+ lastManagedRootLevel = null;
+ logger.setLevel(null);
+ return;
+ }
+ }
+ if (effective == null) {
+ effective = Level.OFF;
+ }
+ lastManagedRootLevel = effective;
+ logger.setLevel(effective);
+ }
+
+ private static String canonicalPathKey(String logPath) {
+ String normalized = logPath == null ? "" : logPath;
+ try {
+ return Paths.get(normalized).toAbsolutePath().normalize().toString();
+ } catch (InvalidPathException e) {
+ return normalized;
+ }
+ }
+
+ private static ManagedFileHandler acquireHandlerLocked(String logPath) {
+ String key = canonicalPathKey(logPath);
+ ManagedFileHandler managed = handlersByPath.get(key);
+ if (managed == null) {
+ String pathArg = logPath == null ? "" : logPath;
+ if (!pathArg.isEmpty() && !pathArg.endsWith("/")) {
+ pathArg = pathArg + "/";
+ }
+ PerConnectionFileHandler created =
+ new PerConnectionFileHandler(
+ pathArg, Level.ALL, PerConnectionFileHandler.resolveMaxLogFileBytes(), true);
+ logger.addHandler(created);
+ managed = new ManagedFileHandler(key, created);
+ handlersByPath.put(key, managed);
+ }
+ managed.refCount++;
+ return managed;
+ }
+
+ private static void releaseHandlerLocked(ManagedFileHandler managed) {
+ if (managed == null) {
+ return;
+ }
+ managed.refCount--;
+ if (managed.refCount <= 0) {
+ handlersByPath.remove(managed.pathKey);
+ try {
+ managed.handler.close();
+ } finally {
+ logger.removeHandler(managed.handler);
+ }
+ }
+ }
+
+ private static final class ManagedFileHandler {
+ final String pathKey;
+ final PerConnectionFileHandler handler;
+ int refCount;
+
+ ManagedFileHandler(String pathKey, PerConnectionFileHandler handler) {
+ this.pathKey = pathKey;
+ this.handler = handler;
+ this.refCount = 0;
+ }
+ }
+
+ private static final class ConnectionLogConfig {
+ final ConnectionLogContext context;
+ final Level level;
+ final ManagedFileHandler managedHandler;
+ ConnectionCleanable cleanable;
+
+ ConnectionLogConfig(
+ ConnectionLogContext context, Level level, ManagedFileHandler managedHandler) {
+ this.context = context;
+ this.level = level;
+ this.managedHandler = managedHandler;
+ }
+ }
+
+ private static final class ConnectionCleanable extends PhantomReference {
+ final String connectionId;
+
+ ConnectionCleanable(
+ BigQueryConnection referent,
+ String connectionId,
+ ReferenceQueue super BigQueryConnection> queue) {
+ super(referent, queue);
+ this.connectionId = connectionId;
}
}
}
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java
index d22846470081..41a1df22f939 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java
@@ -67,6 +67,8 @@ protected boolean removeEldestEntry(Map.Entry> eldes
static final String DEFAULT_QUERY_DIALECT_VALUE = "SQL";
static final String UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME = "universeDomain";
static final String DEFAULT_UNIVERSE_DOMAIN_VALUE = "googleapis.com";
+ static final String GOOGLE_CLOUD_UNIVERSE_DOMAIN_ENV_VAR = "GOOGLE_CLOUD_UNIVERSE_DOMAIN";
+ private static final String STS_TOKEN_URI_FORMAT = "https://sts.%s/v1/token";
static final String PROJECT_ID_PROPERTY_NAME = "ProjectId";
static final String DEFAULT_DATASET_PROPERTY_NAME = "DefaultDataset";
static final String OAUTH_TYPE_PROPERTY_NAME = "OAuthType";
@@ -123,6 +125,8 @@ protected boolean removeEldestEntry(Map.Entry> eldes
static final String LOG_PATH_PROPERTY_NAME = "LogPath";
static final String LOG_LEVEL_ENV_VAR = "BIGQUERY_JDBC_LOG_LEVEL";
static final String LOG_PATH_ENV_VAR = "BIGQUERY_JDBC_LOG_PATH";
+ static final String ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY =
+ "com.google.cloud.bigquery.jdbc.allowUrlLogPath";
static final String ENABLE_SESSION_PROPERTY_NAME = "EnableSession";
static final String ENABLE_TIMESTAMP_PICOS_PROPERTY_NAME = "EnableTimestampPicos";
static final boolean DEFAULT_ENABLE_TIMESTAMP_PICOS_VALUE = false;
@@ -377,8 +381,8 @@ protected boolean removeEldestEntry(Map.Entry> eldes
BigQueryConnectionProperty.newBuilder()
.setName(UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME)
.setDescription(
- "The name of the partner-operated cloud which is a new instance of Google"
- + " production, known as a Trusted Partner Cloud universe.")
+ "The universe domain for the target cloud environment. Defaults to"
+ + " googleapis.com.")
.setDefaultValue(DEFAULT_UNIVERSE_DOMAIN_VALUE)
.build(),
BigQueryConnectionProperty.newBuilder()
@@ -834,7 +838,8 @@ private static Map parseUrlInternal(String url) {
throw new BigQueryJdbcRuntimeException(
String.format("Wrong value or unknown setting: %s", safeRef));
} else {
- LOG.warning("Wrong value or unknown setting: %s", safeRef);
+ LOG.warning(
+ "Wrong value or unknown setting: %s", BigQueryConnection.sanitizeForLog(safeRef));
continue;
}
}
@@ -845,6 +850,33 @@ private static Map parseUrlInternal(String url) {
return Collections.unmodifiableMap(map);
}
+ static boolean isUrlLogPathAllowed() {
+ try {
+ String prop = System.getProperty(ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY);
+ if (prop == null) {
+ return true;
+ }
+ String trimmed = prop.trim();
+ return trimmed.isEmpty() || "true".equalsIgnoreCase(trimmed) || "1".equals(trimmed);
+ } catch (SecurityException e) {
+ return true;
+ }
+ }
+
+ static String resolveEffectiveLogPath(
+ String urlLogPath, String envLogPath, boolean allowDefaultFallback) {
+ if (!isUrlLogPathAllowed()) {
+ return envLogPath;
+ }
+ if (urlLogPath != null) {
+ return urlLogPath;
+ }
+ if (envLogPath != null) {
+ return envLogPath;
+ }
+ return allowDefaultFallback ? DEFAULT_LOG_PATH : null;
+ }
+
/**
* Appends the given properties to the given URL.
*
@@ -853,16 +885,28 @@ private static Map parseUrlInternal(String url) {
* @return The string value of the updated URL.
*/
static String appendPropertiesToURL(String url, String callerClassName, Properties properties) {
- LOG.finest("++enter++ " + callerClassName);
+ LOG.finest(() -> "++enter++ " + callerClassName);
+ if (properties == null || properties.isEmpty()) {
+ return url;
+ }
StringBuilder urlBuilder = new StringBuilder(url);
for (Entry