From 88ab641c3794a5a6505c723d4fd35a7b51e754a9 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Tue, 1 Dec 2026 19:31:03 +0000 Subject: [PATCH] fix(bigquery-jdbc): restrict auto-created LargeResultDataset ACLs to creator and enforce 1h minimum TTL --- java-bigquery-jdbc/docs/USER_GUIDE.md | 4 +- .../bigquery/jdbc/BigQueryConnection.java | 30 ++ .../bigquery/jdbc/BigQueryStatement.java | 26 +- .../jdbc/LargeResultDestinations.java | 255 +++++++++++ .../bigquery/jdbc/BigQueryConnectionTest.java | 72 ++++ .../bigquery/jdbc/BigQueryStatementTest.java | 400 +++++++++++++++++- .../bigquery/jdbc/it/ITStatementTest.java | 5 + 7 files changed, 774 insertions(+), 18 deletions(-) create mode 100644 java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/LargeResultDestinations.java diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index cc12bb2079bc..b11184343536 100644 --- a/java-bigquery-jdbc/docs/USER_GUIDE.md +++ b/java-bigquery-jdbc/docs/USER_GUIDE.md @@ -198,8 +198,8 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443" | `MaxResults` | `10000` | Maximum number of rows returned per page during standard REST result set iteration. | | `AllowLargeResults` | `true` | Allows large query results (required when using legacy SQL destination tables). | | `LargeResultTable` | `null` | Destination table name for query result sets. When specified, results are written with `WRITE_TRUNCATE`. When omitted while `LargeResultDataset` is set, the driver generates a unique temporary table (`temp_table_`) with `WRITE_EMPTY`. | -| `LargeResultDataset` | `null` | Destination dataset name for query result sets. If the specified dataset does not exist, the driver automatically creates it. Under Legacy SQL mode when `LargeResultTable` is set without `LargeResultDataset`, defaults to `_google_jdbc`. | -| `LargeResultsDatasetExpirationTime` | `3600000` (1 hour) | Non-negative expiration time (in milliseconds) for temporary destination tables in auto-created destination datasets (`0` uses the default `3600000` ms). | +| `LargeResultDataset` | `null` | Destination dataset name for query result sets. If the dataset does not exist, the driver automatically creates it with creator-only `OWNER` access (omitting default project-wide group ACLs) and a default table expiration of at least 1 hour (`3600000` ms). Multi-process or shared-dataset deployments using non-service-account credentials should pre-create `LargeResultDataset` with the desired ACLs. Under Legacy SQL mode when `LargeResultTable` is set without `LargeResultDataset`, defaults to `_google_jdbc`. | +| `LargeResultsDatasetExpirationTime` | `3600000` (1 hour) | Non-negative expiration time (in milliseconds) for temporary destination tables in auto-created destination datasets (`0` uses the default `3600000` ms; values under 1 hour are clamped to `3600000` ms on auto-created datasets with a warning). | | `KMSKeyName` | `null` | Cloud KMS key resource name used for encrypting query results and destination tables. | ### Session & Transaction Properties 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 702b3c690df9..d1fd1c25b5cf 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 @@ -25,7 +25,9 @@ import com.google.api.gax.rpc.HeaderProvider; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.auth.Credentials; +import com.google.auth.ServiceAccountSigner; import com.google.auth.http.HttpTransportFactory; +import com.google.auth.oauth2.ExternalAccountCredentials; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.RetryOption; @@ -217,6 +219,7 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { String destinationTable; String destinationDataset; long destinationDatasetExpirationTime; + private final LargeResultDestinations largeResultDestinations = new LargeResultDestinations(); String kmsKeyName; String universeDomain; Map authProperties; @@ -742,6 +745,10 @@ long getDestinationDatasetExpirationTime() { return this.destinationDatasetExpirationTime; } + LargeResultDestinations getLargeResultDestinations() { + return this.largeResultDestinations; + } + String getKmsKeyName() { return this.kmsKeyName; } @@ -756,6 +763,29 @@ public Map getAuthProperties() throws BigQueryJdbcException { return this.authProperties; } + /** + * Returns a service-account email suitable for {@code Acl.User} owner assignment when available, + * or {@code null} for credentials without an email (such as user OAuth, raw access tokens, or + * federated {@code principal://} IAM members, which strip default group ACLs post-create). + */ + String resolveOwnerEmail() { + String email = null; + try { + if (this.credentials instanceof ServiceAccountSigner) { + email = ((ServiceAccountSigner) this.credentials).getAccount(); + } else if (this.credentials instanceof ExternalAccountCredentials) { + email = ((ExternalAccountCredentials) this.credentials).getServiceAccountEmail(); + } + } catch (RuntimeException ex) { + LOG.fine("Could not resolve account email from credentials: %s", ex.getMessage()); + } + if (email == null) { + return null; + } + String trimmed = email.trim(); + return trimmed.contains("@") ? trimmed : null; + } + long getMaxResults() { return maxResults; } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryStatement.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryStatement.java index e60b38eb9aa2..ea9450674916 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryStatement.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryStatement.java @@ -28,9 +28,7 @@ import com.google.cloud.bigquery.BigQuery.TableDataListOption; import com.google.cloud.bigquery.BigQueryException; import com.google.cloud.bigquery.ConnectionProperty; -import com.google.cloud.bigquery.Dataset; import com.google.cloud.bigquery.DatasetId; -import com.google.cloud.bigquery.DatasetInfo; import com.google.cloud.bigquery.EncryptionConfiguration; import com.google.cloud.bigquery.FieldValueList; import com.google.cloud.bigquery.Job; @@ -146,6 +144,7 @@ public class BigQueryStatement extends BigQueryNoOpsStatement { private final BigQuery bigQuery; final BigQuerySettings querySettings; + private final LargeResultDestinations largeResultDestinations; // Variables Required for the ReferenceQueue implementation static ReferenceQueue referenceQueueArrowRs = new ReferenceQueue<>(); @@ -211,6 +210,10 @@ public BigQueryStatement(BigQueryConnection connection) throws SQLException { this.recordTelemetry = recordTelemetry; this.connectionId = connection.getConnectionId(); this.bigQuery = connection.getBigQuery(); + this.largeResultDestinations = + connection.getLargeResultDestinations() != null + ? connection.getLargeResultDestinations() + : new LargeResultDestinations(); this.querySettings = generateBigQuerySettings(); } @@ -1925,18 +1928,13 @@ boolean isEnableTimestampPicos() { } private void checkIfDatasetExistElseCreate(String datasetName) throws BigQueryJdbcException { - Dataset dataset = bigQuery.getDataset(DatasetId.of(datasetName)); - if (dataset == null) { - LOG.info("Creating a hidden dataset: %s ", datasetName); - DatasetInfo.Builder datasetInfoBuilder = - DatasetInfo.newBuilder(datasetName) - .setDefaultTableLifetime(this.querySettings.getDestinationDatasetExpirationTime()); - String location = this.connection.getLocation(); - if (location != null && !location.isEmpty()) { - datasetInfoBuilder.setLocation(location); - } - bigQuery.create(datasetInfoBuilder.build()); - } + BigQueryConnection activeConn = requireOpenConnection(); + this.largeResultDestinations.ensureDatasetExists( + this.bigQuery, + activeConn, + datasetName, + this.querySettings.getDestinationDatasetExpirationTime(), + this::checkNotClosedOrCanceled); } private String getDefaultDestinationTable() { diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/LargeResultDestinations.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/LargeResultDestinations.java new file mode 100644 index 000000000000..17debc0cdd25 --- /dev/null +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/LargeResultDestinations.java @@ -0,0 +1,255 @@ +/* + * 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 + * + * http://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.Acl; +import com.google.cloud.bigquery.BigQuery; +import com.google.cloud.bigquery.BigQueryException; +import com.google.cloud.bigquery.Dataset; +import com.google.cloud.bigquery.DatasetId; +import com.google.cloud.bigquery.DatasetInfo; +import com.google.cloud.bigquery.exception.BigQueryJdbcException; +import java.net.HttpURLConnection; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Coordinates destination dataset provisioning and lifecycle management for {@code + * LargeResultDataset} queries. + */ +final class LargeResultDestinations { + + private static final BigQueryJdbcCustomLogger LOG = + new BigQueryJdbcCustomLogger(LargeResultDestinations.class.getName()); + + static final long MIN_DATASET_DEFAULT_TABLE_LIFETIME_MS = 3_600_000L; + + // BigQuery's default special-group ACLs added automatically on datasets.insert when no explicit + // ACL list is supplied. + private static final Set DEFAULT_DATASET_SPECIAL_GROUPS = + Collections.unmodifiableSet( + new HashSet<>( + Arrays.asList( + Acl.Group.ofProjectOwners(), + Acl.Group.ofProjectWriters(), + Acl.Group.ofProjectReaders()))); + + @FunctionalInterface + interface AbortCheck { + void check() throws BigQueryJdbcException; + } + + private static final class DatasetAclInspection { + private final List nonDefaultGroupAcls; + private final boolean hasDefaultSpecialGroupAcl; + private final boolean hasNonDefaultGroupOwner; + + private DatasetAclInspection( + List nonDefaultGroupAcls, + boolean hasDefaultSpecialGroupAcl, + boolean hasNonDefaultGroupOwner) { + this.nonDefaultGroupAcls = nonDefaultGroupAcls; + this.hasDefaultSpecialGroupAcl = hasDefaultSpecialGroupAcl; + this.hasNonDefaultGroupOwner = hasNonDefaultGroupOwner; + } + } + + Dataset ensureDatasetExists( + BigQuery bigQuery, + BigQueryConnection conn, + String datasetName, + long configuredExpirationMs, + AbortCheck abortCheck) + throws BigQueryJdbcException { + Dataset dataset; + try { + dataset = bigQuery.getDataset(DatasetId.of(datasetName)); + } catch (BigQueryException ex) { + throw new BigQueryJdbcException("Failed to check destination dataset: " + datasetName, ex); + } + if (dataset != null) { + return dataset; + } + abortCheck.check(); + return createDataset(bigQuery, conn, datasetName, configuredExpirationMs); + } + + private Dataset createDataset( + BigQuery bigQuery, BigQueryConnection conn, String datasetName, long configuredExpirationMs) + throws BigQueryJdbcException { + String sanitizedDatasetName = BigQueryConnection.sanitizeForLog(datasetName); + LOG.info("Auto-creating destination dataset: %s", sanitizedDatasetName); + long datasetDefaultTableLifetimeMs = + Math.max(configuredExpirationMs, MIN_DATASET_DEFAULT_TABLE_LIFETIME_MS); + if (configuredExpirationMs < MIN_DATASET_DEFAULT_TABLE_LIFETIME_MS) { + LOG.warning( + "Clamping auto-created dataset %s defaultTableLifetime from %d ms to BigQuery minimum" + + " %d ms.", + sanitizedDatasetName, configuredExpirationMs, MIN_DATASET_DEFAULT_TABLE_LIFETIME_MS); + } + + DatasetInfo.Builder datasetInfoBuilder = + DatasetInfo.newBuilder(datasetName).setDefaultTableLifetime(datasetDefaultTableLifetimeMs); + String location = conn.getLocation(); + if (location != null && !location.isEmpty()) { + datasetInfoBuilder.setLocation(location); + } + String ownerEmail = conn.resolveOwnerEmail(); + if (ownerEmail != null) { + datasetInfoBuilder.setAcl( + Collections.singletonList(Acl.of(new Acl.User(ownerEmail), Acl.Role.OWNER))); + } + + Dataset createdDataset; + try { + createdDataset = bigQuery.create(datasetInfoBuilder.build()); + } catch (BigQueryException ex) { + if (isDatasetConflict(ex)) { + return handleDatasetCreationConflict(bigQuery, datasetName, ownerEmail); + } + throw new BigQueryJdbcException("Failed to create destination dataset: " + datasetName, ex); + } + + if (ownerEmail != null) { + return createdDataset; + } + + try { + return restrictAutoCreatedDatasetAclToCreator(bigQuery, datasetName, createdDataset); + } catch (BigQueryJdbcException ex) { + deleteEmptyDatasetBestEffort(bigQuery, datasetName); + throw ex; + } catch (RuntimeException ex) { + deleteEmptyDatasetBestEffort(bigQuery, datasetName); + throw new BigQueryJdbcException( + "Failed to restrict ACLs on auto-created destination dataset: " + datasetName, ex); + } + } + + private Dataset handleDatasetCreationConflict( + BigQuery bigQuery, String datasetName, String ownerEmail) throws BigQueryJdbcException { + LOG.fine( + "Destination dataset %s already exists (concurrent creation race).", + BigQueryConnection.sanitizeForLog(datasetName)); + Dataset existingDataset; + try { + existingDataset = bigQuery.getDataset(DatasetId.of(datasetName)); + } catch (BigQueryException reloadEx) { + if (ownerEmail == null) { + throw new BigQueryJdbcException( + "Failed to verify ACLs on concurrently created destination dataset: " + datasetName, + reloadEx); + } + LOG.fine( + "Could not reload concurrently created dataset %s: %s", + BigQueryConnection.sanitizeForLog(datasetName), reloadEx.getMessage()); + return null; + } + if (ownerEmail == null) { + verifyConcurrentlyCreatedDatasetAclRestricted(datasetName, existingDataset); + } + return existingDataset; + } + + private static boolean isDatasetConflict(BigQueryException ex) { + return ex.getCode() == HttpURLConnection.HTTP_CONFLICT + || "duplicate".equalsIgnoreCase(ex.getReason()); + } + + private static DatasetAclInspection inspectDatasetAcl(List currentAcl) { + List nonDefaultGroupAcls = new ArrayList<>(); + boolean hasDefaultSpecialGroupAcl = false; + boolean hasNonDefaultGroupOwner = false; + for (Acl acl : currentAcl) { + if (DEFAULT_DATASET_SPECIAL_GROUPS.contains(acl.getEntity())) { + hasDefaultSpecialGroupAcl = true; + } else { + nonDefaultGroupAcls.add(acl); + if (Acl.Role.OWNER.equals(acl.getRole())) { + hasNonDefaultGroupOwner = true; + } + } + } + return new DatasetAclInspection( + nonDefaultGroupAcls, hasDefaultSpecialGroupAcl, hasNonDefaultGroupOwner); + } + + /** + * For non-service-account credentials (whose email/principal is not known before {@code + * datasets.insert}), strips BigQuery's default project-wide special-group ACLs via {@code + * datasets.patch} before any query job writes to the dataset, failing closed if an explicit + * creator {@code OWNER} entry cannot be verified. + */ + private Dataset restrictAutoCreatedDatasetAclToCreator( + BigQuery bigQuery, String datasetName, Dataset createdDataset) throws BigQueryJdbcException { + if (createdDataset == null || createdDataset.getAcl() == null) { + throw new BigQueryJdbcException( + "Could not verify creator-only ACLs on auto-created destination dataset: " + datasetName); + } + DatasetAclInspection inspection = inspectDatasetAcl(createdDataset.getAcl()); + if (!inspection.hasNonDefaultGroupOwner) { + throw new BigQueryJdbcException( + "Auto-created destination dataset does not contain a verifiable creator OWNER ACL: " + + datasetName); + } + if (!inspection.hasDefaultSpecialGroupAcl) { + return createdDataset; + } + try { + return bigQuery.update( + DatasetInfo.newBuilder(datasetName).setAcl(inspection.nonDefaultGroupAcls).build()); + } catch (BigQueryException ex) { + throw new BigQueryJdbcException( + "Failed to restrict ACLs on auto-created destination dataset: " + datasetName, ex); + } + } + + /** + * Fails closed on a {@code 409 Conflict} race for non-service-account credentials without + * mutating ACLs on a dataset that may have been created by another actor. + */ + private static void verifyConcurrentlyCreatedDatasetAclRestricted( + String datasetName, Dataset existingDataset) throws BigQueryJdbcException { + if (existingDataset == null || existingDataset.getAcl() == null) { + throw new BigQueryJdbcException( + "Could not verify ACLs on concurrently created destination dataset: " + + datasetName + + ". Pre-create LargeResultDataset with the desired ACLs."); + } + DatasetAclInspection inspection = inspectDatasetAcl(existingDataset.getAcl()); + if (inspection.hasDefaultSpecialGroupAcl || !inspection.hasNonDefaultGroupOwner) { + throw new BigQueryJdbcException( + "Concurrently created destination dataset does not have verified creator-only ACLs: " + + datasetName + + ". Pre-create LargeResultDataset with the desired ACLs."); + } + } + + private void deleteEmptyDatasetBestEffort(BigQuery bigQuery, String datasetName) { + try { + bigQuery.delete(DatasetId.of(datasetName)); + } catch (RuntimeException ex) { + LOG.warning( + "Failed to clean up empty destination dataset %s after ACL restriction failure: %s", + BigQueryConnection.sanitizeForLog(datasetName), ex.getMessage()); + } + } +} diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java index 153168462667..1c4c7ea26e03 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java @@ -47,6 +47,7 @@ import com.google.api.gax.rpc.HeaderProvider; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.auth.Credentials; +import com.google.auth.ServiceAccountSigner; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.RetryOption; @@ -117,11 +118,14 @@ import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; +import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; @@ -1284,6 +1288,74 @@ public void testConnectionHonorsEnvUniverseDomainWithoutOverwritingJsonCredentia } } + private static String externalAccountJson(String impersonatedEmail) { + String impersonationField = + impersonatedEmail == null + ? "" + : ",\"service_account_impersonation_url\":\"https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/" + + impersonatedEmail + + ":generateAccessToken\""; + return "{\"type\":\"external_account\"," + + "\"audience\":\"//iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/p/providers/pr\"," + + "\"subject_token_type\":\"urn:ietf:params:oauth:tokentype:id_token\"," + + "\"token_url\":\"https://sts.googleapis.com/v1/token\"," + + "\"credential_source\":{\"file\":\"/tmp/nonexistent-token\"}" + + impersonationField + + "}"; + } + + private static Stream ownerEmailUrlCases() { + return Stream.of( + Arguments.of( + getUriOAuthServiceAccount().append("ProjectId", "project").toString(), + "service@account"), + Arguments.of( + getUriOAuthToken() + .append("ProjectId", "project") + .append( + "ServiceAccountImpersonationEmail", "target-sa@project.iam.gserviceaccount.com") + .toString(), + "target-sa@project.iam.gserviceaccount.com"), + Arguments.of( + getBaseUri(4, "project") + .append( + "OAuthPvtKey", externalAccountJson("byoid-sa@project.iam.gserviceaccount.com")) + .toString(), + "byoid-sa@project.iam.gserviceaccount.com"), + Arguments.of( + getBaseUri(4, "project").append("OAuthPvtKey", externalAccountJson(null)).toString(), + null), + Arguments.of(getUriOAuthToken().append("ProjectId", "project").toString(), null)); + } + + @ParameterizedTest + @MethodSource("ownerEmailUrlCases") + public void testResolveOwnerEmailFromUrl(String url, String expectedEmail) throws Exception { + try (BigQueryConnection conn = new BigQueryConnection(url)) { + assertEquals(expectedEmail, conn.resolveOwnerEmail()); + } + } + + @Test + public void testResolveOwnerEmailFromServiceAccountSigner() throws Exception { + try (BigQueryConnection conn = + new BigQueryConnection(getUriOAuthToken().append("ProjectId", "project").toString())) { + Credentials validSigner = + mock(Credentials.class, withSettings().extraInterfaces(ServiceAccountSigner.class)); + when(((ServiceAccountSigner) validSigner).getAccount()) + .thenReturn(" gce-sa@project.iam.gserviceaccount.com "); + conn.credentials = validSigner; + assertEquals("gce-sa@project.iam.gserviceaccount.com", conn.resolveOwnerEmail()); + + when(((ServiceAccountSigner) validSigner).getAccount()).thenReturn("non-email-subject"); + assertNull(conn.resolveOwnerEmail()); + + when(((ServiceAccountSigner) validSigner).getAccount()) + .thenThrow(new RuntimeException("Metadata server unavailable")); + assertNull(conn.resolveOwnerEmail()); + } + } + private static URI storageUri(String universeDomain, String service) { return URI.create( "https://bigquerystorage." diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryStatementTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryStatementTest.java index 48a2c4727a67..0acebaf706b0 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryStatementTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryStatementTest.java @@ -44,6 +44,7 @@ import com.google.api.gax.rpc.StatusCode; import com.google.cloud.ServiceOptions; import com.google.cloud.Tuple; +import com.google.cloud.bigquery.Acl; import com.google.cloud.bigquery.BigQuery; import com.google.cloud.bigquery.BigQuery.JobListOption; import com.google.cloud.bigquery.BigQuery.QueryResultsOption; @@ -138,6 +139,7 @@ import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -1205,9 +1207,10 @@ public void testSetAndGetFetchSize() throws SQLException { @Test public void testTemporaryDatasetCreationRespectsConnectionLocation() throws SQLException, InterruptedException { - // 1. Setup mock connection with location and destination dataset + // 1. Setup mock connection with location, owner email, and destination dataset doReturn("europe-west3").when(bigQueryConnection).getLocation(); doReturn("temp_dataset").when(bigQueryConnection).getDestinationDataset(); + doReturn("owner@project.iam.gserviceaccount.com").when(bigQueryConnection).resolveOwnerEmail(); // Re-instantiate bigQueryStatement so it regenerates querySettings with these mocked connection // values @@ -1234,11 +1237,16 @@ public void testTemporaryDatasetCreationRespectsConnectionLocation() // 5. Execute query statementSpy.executeQuery("SELECT 1"); - // 6. Verify dataset was created with correct location + // 6. Verify dataset was created with correct location, 1h minimum TTL, and creator-only ACL verify(bigquery).create(datasetInfoCaptor.capture()); DatasetInfo createdDatasetInfo = datasetInfoCaptor.getValue(); assertEquals("temp_dataset", createdDatasetInfo.getDatasetId().getDataset()); assertEquals("europe-west3", createdDatasetInfo.getLocation()); + assertEquals(DEFAULT_DATASET_EXPIRATION_MS, createdDatasetInfo.getDefaultTableLifetime()); + assertEquals( + Collections.singletonList( + Acl.of(new Acl.User("owner@project.iam.gserviceaccount.com"), Acl.Role.OWNER)), + createdDatasetInfo.getAcl()); } @Test @@ -2623,4 +2631,392 @@ public void testStatement_nonTerminalQueryWithTimeoutFailureCancelsClientJobId() } verify(bigquery, never()).cancel(any(JobId.class)); } + + private static Stream autoCreatedServiceAccountDatasetCases() { + return Stream.of( + Arguments.of( + BigQueryJdbcBaseTest.getUriOAuthServiceAccount() + .append("ProjectId", PROJECT) + .append("Location", "EU") + .append("LargeResultDataset", "auto_sa_dataset") + .toString(), + "auto_sa_dataset", + "EU", + "service@account", + DEFAULT_DATASET_EXPIRATION_MS), + Arguments.of( + BigQueryJdbcBaseTest.getUriOAuthToken() + .append("ProjectId", PROJECT) + .append( + "ServiceAccountImpersonationEmail", + "impersonated@project.iam.gserviceaccount.com") + .append("LargeResultDataset", "auto_impersonated_dataset") + .append("LargeResultsDatasetExpirationTime", "600000") + .toString(), + "auto_impersonated_dataset", + null, + "impersonated@project.iam.gserviceaccount.com", + DEFAULT_DATASET_EXPIRATION_MS), + Arguments.of( + BigQueryJdbcBaseTest.getUriOAuthServiceAccount() + .append("ProjectId", PROJECT) + .append("LargeResultDataset", "auto_sa_long_ttl_dataset") + .append("LargeResultsDatasetExpirationTime", "7200000") + .toString(), + "auto_sa_long_ttl_dataset", + null, + "service@account", + 7_200_000L), + Arguments.of( + BigQueryJdbcBaseTest.getUriOAuthServiceAccount() + .append("ProjectId", PROJECT) + .append("QueryDialect", "BIG_QUERY") + .append("AllowLargeResults", 1) + .append("LargeResultTable", "explicit_legacy_table") + .toString(), + "_google_jdbc", + null, + "service@account", + DEFAULT_DATASET_EXPIRATION_MS)); + } + + @ParameterizedTest + @MethodSource("autoCreatedServiceAccountDatasetCases") + public void testAutoCreatedDataset_serviceAccountAtomicOwnerAclAndSubHourClamp( + String url, + String expectedDatasetName, + String expectedLocation, + String expectedOwnerEmail, + long expectedDatasetDefaultLifetimeMs) + throws Exception { + doReturn(null).when(bigquery).getDataset(eq(DatasetId.of(expectedDatasetName))); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url); + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT 1")) { + assertNotNull(rs); + } + + ArgumentCaptor datasetCaptor = ArgumentCaptor.forClass(DatasetInfo.class); + verify(bigquery).create(datasetCaptor.capture()); + DatasetInfo createdDataset = datasetCaptor.getValue(); + assertEquals(expectedDatasetName, createdDataset.getDatasetId().getDataset()); + assertEquals(expectedLocation, createdDataset.getLocation()); + assertEquals(expectedDatasetDefaultLifetimeMs, createdDataset.getDefaultTableLifetime()); + assertEquals( + Collections.singletonList(Acl.of(new Acl.User(expectedOwnerEmail), Acl.Role.OWNER)), + createdDataset.getAcl()); + verify(bigquery, never()).update(any(DatasetInfo.class)); + } + + @Test + public void testAutoCreatedDataset_nonServiceAccountStripsDefaultGroupAclsBeforeQuery() + throws Exception { + String datasetName = "auto_user_oauth_dataset"; + String url = + BigQueryJdbcBaseTest.getUriOAuthToken() + .append("ProjectId", PROJECT) + .append("LargeResultDataset", datasetName) + .toString(); + doReturn(null).when(bigquery).getDataset(eq(DatasetId.of(datasetName))); + Dataset serverCreatedDataset = mock(Dataset.class); + Acl creatorUserAcl = Acl.of(new Acl.User("alice@example.com"), Acl.Role.OWNER); + Acl explicitEmailGroupAcl = Acl.of(new Acl.Group("analysts@example.com"), Acl.Role.READER); + Acl creatorIamMemberAcl = + Acl.of( + new Acl.IamMember( + "principal://iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/p/subject/sub"), + Acl.Role.OWNER); + doReturn( + Arrays.asList( + Acl.of(new Acl.Group("projectOwners"), Acl.Role.OWNER), + Acl.of(new Acl.Group("projectWriters"), Acl.Role.WRITER), + Acl.of(new Acl.Group("projectReaders"), Acl.Role.READER), + explicitEmailGroupAcl, + creatorUserAcl, + creatorIamMemberAcl)) + .when(serverCreatedDataset) + .getAcl(); + doReturn(serverCreatedDataset).when(bigquery).create(any(DatasetInfo.class)); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url); + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT 1")) { + assertNotNull(rs); + } + + InOrder inOrder = Mockito.inOrder(bigquery); + ArgumentCaptor createCaptor = ArgumentCaptor.forClass(DatasetInfo.class); + ArgumentCaptor updateCaptor = ArgumentCaptor.forClass(DatasetInfo.class); + inOrder.verify(bigquery).create(createCaptor.capture()); + inOrder.verify(bigquery).update(updateCaptor.capture()); + inOrder.verify(bigquery).queryWithTimeout(any(QueryJobConfiguration.class), any(), any()); + + assertNull(createCaptor.getValue().getAcl()); + assertEquals( + Arrays.asList(explicitEmailGroupAcl, creatorUserAcl, creatorIamMemberAcl), + updateCaptor.getValue().getAcl()); + } + + private static Stream nonServiceAccountPatchRollbackCases() { + return Stream.of( + Arguments.of( + "bq_500_with_rollback_delete_error", + new BigQueryException(500, "Failed to patch dataset ACL"), + new BigQueryException(503, "Rollback delete failed"), + "Failed to patch dataset ACL"), + Arguments.of( + "unexpected_runtime_exception_wrapped_as_jdbc_exception", + new IllegalStateException("Unexpected ACL patch failure"), + null, + "Unexpected ACL patch failure")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("nonServiceAccountPatchRollbackCases") + public void testAutoCreatedDataset_nonServiceAccountRollsBackEmptyDatasetAndWrapsError( + String caseName, + RuntimeException patchFailure, + RuntimeException rollbackDeleteFailure, + String expectedCauseMessage) + throws Exception { + String datasetName = "auto_user_rollback_" + caseName; + String url = + BigQueryJdbcBaseTest.getUriOAuthToken() + .append("ProjectId", PROJECT) + .append("LargeResultDataset", datasetName) + .toString(); + Dataset serverCreatedDataset = mock(Dataset.class); + doReturn( + Arrays.asList( + Acl.of(Acl.Group.ofProjectReaders(), Acl.Role.READER), + Acl.of(new Acl.User("alice@example.com"), Acl.Role.OWNER))) + .when(serverCreatedDataset) + .getAcl(); + doReturn(null).when(bigquery).getDataset(eq(DatasetId.of(datasetName))); + doReturn(serverCreatedDataset).when(bigquery).create(any(DatasetInfo.class)); + doThrow(patchFailure).when(bigquery).update(any(DatasetInfo.class)); + if (rollbackDeleteFailure != null) { + doThrow(rollbackDeleteFailure).when(bigquery).delete(eq(DatasetId.of(datasetName))); + } else { + doReturn(true).when(bigquery).delete(eq(DatasetId.of(datasetName))); + } + + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url); + Statement stmt = conn.createStatement()) { + BigQueryJdbcException ex = + assertThrows(BigQueryJdbcException.class, () -> stmt.executeQuery("SELECT 1")); + assertThat(ex.getCause().getMessage()).contains(expectedCauseMessage); + } + verify(bigquery).delete(eq(DatasetId.of(datasetName))); + verify(bigquery, never()).queryWithTimeout(any(QueryJobConfiguration.class), any(), any()); + } + + @Test + public void testAutoCreatedDataset_conflictRaceAndDatasetRpcErrors() throws Exception { + String datasetName = "conflict_dataset"; + String url = + BigQueryJdbcBaseTest.getUriOAuthServiceAccount() + .append("ProjectId", PROJECT) + .append("LargeResultDataset", datasetName) + .toString(); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + + // 1. 409 Conflict where reload succeeds -> proceeds with query. + Dataset reloadedWithTtl = mock(Dataset.class); + doReturn(DEFAULT_DATASET_EXPIRATION_MS).when(reloadedWithTtl).getDefaultTableLifetime(); + Mockito.when(bigquery.getDataset(eq(DatasetId.of(datasetName)))) + .thenReturn(null) + .thenReturn(reloadedWithTtl); + doThrow(new BigQueryException(409, "Already Exists")) + .when(bigquery) + .create(any(DatasetInfo.class)); + + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url); + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT 1")) { + assertNotNull(rs); + } + + // 2. Non-409 BigQueryException on dataset create -> wrapped as BigQueryJdbcException. + Mockito.reset(bigquery); + doReturn(null).when(bigquery).getDataset(eq(DatasetId.of(datasetName))); + doThrow(new BigQueryException(403, "Dataset create denied")) + .when(bigquery) + .create(any(DatasetInfo.class)); + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url); + Statement stmt = conn.createStatement()) { + assertThrows(BigQueryJdbcException.class, () -> stmt.executeQuery("SELECT 1")); + } + + // 3. BigQueryException on initial getDataset -> wrapped as BigQueryJdbcException. + Mockito.reset(bigquery); + doThrow(new BigQueryException(403, "Dataset get denied")) + .when(bigquery) + .getDataset(eq(DatasetId.of(datasetName))); + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url); + Statement stmt = conn.createStatement()) { + assertThrows(BigQueryJdbcException.class, () -> stmt.executeQuery("SELECT 1")); + } + } + + private static Stream nonServiceAccountFailClosedAclCases() { + return Stream.of( + Arguments.of("null_dataset", false, null), + Arguments.of("null_acl", true, null), + Arguments.of("empty_acl", true, Collections.emptyList()), + Arguments.of( + "group_only_acl", + true, + Arrays.asList( + Acl.of(new Acl.Group("projectOwners"), Acl.Role.OWNER), + Acl.of(new Acl.Group("projectReaders"), Acl.Role.READER))), + Arguments.of( + "non_group_reader_without_owner", + true, + Arrays.asList( + Acl.of(Acl.Group.ofProjectOwners(), Acl.Role.OWNER), + Acl.of(new Acl.Group("analysts@example.com"), Acl.Role.READER)))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("nonServiceAccountFailClosedAclCases") + public void testAutoCreatedDataset_nonServiceAccountFailsClosedWhenCreatorAclUnverifiable( + String caseName, boolean returnDataset, List returnedAcl) throws Exception { + String datasetName = "auto_user_fail_closed_" + caseName; + String url = + BigQueryJdbcBaseTest.getUriOAuthToken() + .append("ProjectId", PROJECT) + .append("LargeResultDataset", datasetName) + .toString(); + doReturn(null).when(bigquery).getDataset(eq(DatasetId.of(datasetName))); + Dataset createdDataset = null; + if (returnDataset) { + createdDataset = mock(Dataset.class); + doReturn(returnedAcl).when(createdDataset).getAcl(); + } + doReturn(createdDataset).when(bigquery).create(any(DatasetInfo.class)); + + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url); + Statement stmt = conn.createStatement()) { + assertThrows(BigQueryJdbcException.class, () -> stmt.executeQuery("SELECT 1")); + } + verify(bigquery).delete(eq(DatasetId.of(datasetName))); + verify(bigquery, never()).update(any(DatasetInfo.class)); + verify(bigquery, never()).queryWithTimeout(any(QueryJobConfiguration.class), any(), any()); + } + + private static Stream nonServiceAccountConflictCases() { + Acl creatorAcl = Acl.of(new Acl.User("alice@example.com"), Acl.Role.OWNER); + return Stream.of( + Arguments.of( + "project_owners_and_reader_fails_closed", + Arrays.asList( + Acl.of(Acl.Group.ofProjectOwners(), Acl.Role.OWNER), + Acl.of(new Acl.Group("analysts@example.com"), Acl.Role.READER)), + false, + false), + Arguments.of( + "default_group_alongside_creator_fails_closed", + Arrays.asList(Acl.of(Acl.Group.ofProjectReaders(), Acl.Role.READER), creatorAcl), + false, + false), + Arguments.of( + "already_restricted_proceeds", Collections.singletonList(creatorAcl), false, true), + Arguments.of("reload_error_fails_closed", null, true, false)); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("nonServiceAccountConflictCases") + public void testAutoCreatedDataset_nonServiceAccountConflictBehavior( + String caseName, List reloadedAcl, boolean reloadThrows, boolean expectSuccess) + throws Exception { + String datasetName = "conflict_user_" + caseName; + String url = + BigQueryJdbcBaseTest.getUriOAuthToken() + .append("ProjectId", PROJECT) + .append("LargeResultDataset", datasetName) + .toString(); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + doThrow(new BigQueryException(409, "Already Exists")) + .when(bigquery) + .create(any(DatasetInfo.class)); + + if (reloadThrows) { + Mockito.when(bigquery.getDataset(eq(DatasetId.of(datasetName)))) + .thenReturn(null) + .thenThrow(new BigQueryException(503, "Reload failed")); + } else { + Dataset reloaded = mock(Dataset.class); + doReturn(DEFAULT_DATASET_EXPIRATION_MS).when(reloaded).getDefaultTableLifetime(); + doReturn(reloadedAcl).when(reloaded).getAcl(); + Mockito.when(bigquery.getDataset(eq(DatasetId.of(datasetName)))) + .thenReturn(null) + .thenReturn(reloaded); + } + + try (BigQueryConnection conn = createConnectionWithMockedBigQuery(url); + Statement stmt = conn.createStatement()) { + if (expectSuccess) { + try (ResultSet rs = stmt.executeQuery("SELECT 1")) { + assertNotNull(rs); + } + verify(bigquery, times(1)).queryWithTimeout(any(QueryJobConfiguration.class), any(), any()); + } else { + assertThrows(BigQueryJdbcException.class, () -> stmt.executeQuery("SELECT 1")); + verify(bigquery, never()).queryWithTimeout(any(QueryJobConfiguration.class), any(), any()); + } + } + verify(bigquery, never()).update(any(DatasetInfo.class)); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + public void testAutoCreatedDataset_concurrentCancelDuringDatasetCheckAbortsWithoutSubmittingJob( + boolean datasetExists) throws Exception { + configureLargeResults( + SCRATCH_DATASET, null, DEFAULT_DATASET_EXPIRATION_MS, DEFAULT_DATASET_EXPIRATION_MS); + Dataset datasetWithTtl = mock(Dataset.class); + doReturn(DEFAULT_DATASET_EXPIRATION_MS).when(datasetWithTtl).getDefaultTableLifetime(); + + CountDownLatch enteredGetDataset = new CountDownLatch(1); + CountDownLatch cancelFinished = new CountDownLatch(1); + Mockito.doAnswer( + invocation -> { + enteredGetDataset.countDown(); + assertTrue(cancelFinished.await(5, TimeUnit.SECONDS)); + return datasetExists ? datasetWithTtl : null; + }) + .when(bigquery) + .getDataset(eq(DatasetId.of(SCRATCH_DATASET))); + + ExecutorService callerPool = Executors.newSingleThreadExecutor(); + try (BigQueryStatement statement = new BigQueryStatement(bigQueryConnection)) { + Future queryFuture = callerPool.submit(() -> statement.executeQuery("SELECT 1")); + assertTrue(enteredGetDataset.await(5, TimeUnit.SECONDS)); + + statement.cancel(); + cancelFinished.countDown(); + + ExecutionException execEx = + assertThrows(ExecutionException.class, () -> queryFuture.get(5, TimeUnit.SECONDS)); + assertThat(execEx.getCause()).isInstanceOf(BigQueryJdbcException.class); + assertEquals("Query was cancelled.", execEx.getCause().getMessage()); + assertFalse(statement.isClosed()); + verify(bigquery, never()).create(any(DatasetInfo.class)); + verify(bigquery, never()).queryWithTimeout(any(QueryJobConfiguration.class), any(), any()); + + // A subsequent execution on the same open Statement clears isCanceled and succeeds. + doReturn(datasetWithTtl).when(bigquery).getDataset(eq(DatasetId.of(SCRATCH_DATASET))); + setupMockLargeResultJobQuery(StatementType.SELECT, null); + try (ResultSet rs = statement.executeQuery("SELECT 2")) { + assertNotNull(rs); + } + verify(bigquery, times(1)).queryWithTimeout(any(QueryJobConfiguration.class), any(), any()); + } finally { + callerPool.shutdownNow(); + } + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITStatementTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITStatementTest.java index 7473086e715c..65c40053de51 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITStatementTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITStatementTest.java @@ -27,6 +27,7 @@ import com.google.api.gax.paging.Page; import com.google.cloud.ServiceOptions; +import com.google.cloud.bigquery.Acl; import com.google.cloud.bigquery.BigQuery; import com.google.cloud.bigquery.Dataset; import com.google.cloud.bigquery.DatasetId; @@ -418,6 +419,10 @@ public void testTemporaryDatasetLocation() throws SQLException, InterruptedExcep Dataset dataset = bigQuery.getDataset(DatasetId.of(tempDatasetName)); assertNotNull(dataset); assertEquals(location, dataset.getLocation()); + assertEquals(3_600_000L, dataset.getDefaultTableLifetime()); + assertNotNull(dataset.getAcl()); + assertTrue(dataset.getAcl().stream().anyMatch(acl -> Acl.Role.OWNER.equals(acl.getRole()))); + assertTrue(dataset.getAcl().stream().noneMatch(acl -> acl.getEntity() instanceof Acl.Group)); // Validate that the query results were written to a table in this dataset Page tables = dataset.list();