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 561cc75d918b..188ca38caa17 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 @@ -33,7 +33,10 @@ import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.logging.Level; @@ -109,6 +112,188 @@ public static BigQueryDriver getRegisteredDriver() throws IllegalStateException throw ex; } + /** + * Result of validating and normalizing caller-supplied {@link Properties} passed to {@link + * Driver} methods without flattening them onto the JDBC URL. + * + *

"Normalized" here means: + * + *

+ */ + static final class ValidatedConnectionProperties { + final Map canonicalProperties; + final List unknownPropertyKeys; + final boolean hasIgnoredInvalidPropertyKeys; + final OpenTelemetry customOpenTelemetry; + + ValidatedConnectionProperties( + Map canonicalProperties, + List unknownPropertyKeys, + boolean hasIgnoredInvalidPropertyKeys, + OpenTelemetry customOpenTelemetry) { + this.canonicalProperties = Collections.unmodifiableMap(canonicalProperties); + this.unknownPropertyKeys = Collections.unmodifiableList(unknownPropertyKeys); + this.hasIgnoredInvalidPropertyKeys = hasIgnoredInvalidPropertyKeys; + this.customOpenTelemetry = customOpenTelemetry; + } + } + + /** + * Validates and normalizes (canonicalizes) caller-supplied {@link Properties} without serializing + * them onto the JDBC URL. Preserves inherited {@link Properties} defaults, non-String values via + * {@link String#valueOf(Object)}, and out-of-band {@code customOpenTelemetry} instances. + */ + static ValidatedConnectionProperties validateAndCanonicalizeProperties( + Properties callerProperties) { + if (callerProperties == null) { + return new ValidatedConnectionProperties( + Collections.emptyMap(), Collections.emptyList(), false, null); + } + Properties propertiesSnapshot = (Properties) callerProperties.clone(); + Map canonicalProperties = new LinkedHashMap<>(); + List unknownPropertyKeys = new ArrayList<>(); + boolean hasIgnoredInvalidPropertyKeys = false; + OpenTelemetry customOpenTelemetry = null; + Object customOpenTelemetryValue = propertiesSnapshot.get("customOpenTelemetry"); + if (customOpenTelemetryValue instanceof OpenTelemetry) { + customOpenTelemetry = (OpenTelemetry) customOpenTelemetryValue; + } else if (customOpenTelemetryValue != null && !"".equals(customOpenTelemetryValue)) { + unknownPropertyKeys.add("customOpenTelemetry"); + } + + // Pass 1: record inherited String defaults that are not directly shadowed in + // propertiesSnapshot. + for (String defaultPropertyKey : propertiesSnapshot.stringPropertyNames()) { + if ("customOpenTelemetry".equals(defaultPropertyKey) + || propertiesSnapshot.containsKey(defaultPropertyKey)) { + continue; + } + String validatedPropertyKey = + BigQueryJdbcUrlUtility.extractValidPropertyKey(defaultPropertyKey); + if (validatedPropertyKey == null) { + hasIgnoredInvalidPropertyKeys = true; + continue; + } + String defaultPropertyValue = propertiesSnapshot.getProperty(defaultPropertyKey); + recordValidatedProperty( + validatedPropertyKey, defaultPropertyValue, canonicalProperties, unknownPropertyKeys); + } + + // Pass 2: overlay direct entries from propertiesSnapshot (both String and non-String values) so + // direct entries always win deterministically over inherited defaults, including case-variant + // keys. + for (Map.Entry directPropertyEntry : propertiesSnapshot.entrySet()) { + Object directKeyObject = directPropertyEntry.getKey(); + Object directValueObject = directPropertyEntry.getValue(); + if ("customOpenTelemetry".equals(directKeyObject)) { + continue; + } + if (directKeyObject != null && directValueObject != null) { + String validatedPropertyKey = + BigQueryJdbcUrlUtility.extractValidPropertyKey(directKeyObject); + if (validatedPropertyKey == null) { + hasIgnoredInvalidPropertyKeys = true; + continue; + } + recordValidatedProperty( + validatedPropertyKey, + String.valueOf(directValueObject), + canonicalProperties, + unknownPropertyKeys); + } + } + + return new ValidatedConnectionProperties( + canonicalProperties, + unknownPropertyKeys, + hasIgnoredInvalidPropertyKeys, + customOpenTelemetry); + } + + private static void recordValidatedProperty( + String propertyKey, + String propertyValue, + Map canonicalProperties, + List unknownPropertyKeys) { + if (propertyValue == null || propertyValue.isEmpty()) { + return; + } + String uppercasePropertyKey = propertyKey.toUpperCase(Locale.ROOT); + String canonicalPropertyName = + BigQueryJdbcUrlUtility.PROPERTY_NAME_MAP.get(uppercasePropertyKey); + if (canonicalPropertyName != null) { + canonicalProperties.put(canonicalPropertyName, propertyValue); + } else { + String truncatedPropertyKey = + uppercasePropertyKey.length() > 32 + ? uppercasePropertyKey.substring(0, 32) + "..." + : uppercasePropertyKey; + unknownPropertyKeys.add(BigQueryConnection.sanitizeForLog(truncatedPropertyKey)); + } + } + + /** + * {@code EndpointOverrides} and {@code PrivateServiceConnectUris} are aliases; a caller value for + * either replaces both so a URL-supplied alias can never shadow it. + */ + private static void removeAliasesOverriddenBy( + Map baseProperties, Map overrideProperties) { + if (overrideProperties.containsKey(BigQueryJdbcUrlUtility.ENDPOINT_OVERRIDES_PROPERTY_NAME) + || overrideProperties.containsKey( + BigQueryJdbcUrlUtility.PRIVATE_SERVICE_CONNECT_PROPERTY_NAME)) { + baseProperties.remove(BigQueryJdbcUrlUtility.ENDPOINT_OVERRIDES_PROPERTY_NAME); + baseProperties.remove(BigQueryJdbcUrlUtility.PRIVATE_SERVICE_CONNECT_PROPERTY_NAME); + } + } + + private static boolean isTelemetryOptOut(String value) { + if (value == null) { + return false; + } + if ("false".equalsIgnoreCase(value)) { + return true; + } + try { + return Integer.parseInt(value) == 0; + } catch (NumberFormatException ignored) { + return false; + } + } + + /** + * Resolves a pre-connect ("bootstrap") setting—one of the four logging/telemetry properties + * ({@code EnableDiagnosticTelemetry}, {@code LogLevel}, {@code LogPath}, {@code + * enableGcpLogExporter}) that must be read before the pre-connect logger opens and before Phase 2 + * URL validation throws—applying strict precedence: {@code DataSource} setter > caller {@link + * Properties} > URL parameter (last-wins). For {@code EnableDiagnosticTelemetry}, callers + * check {@link #isTelemetryOptOut(String)} across all sources first so an opt-out always wins. + */ + private static String resolvePreConnectProperty( + String canonicalPropertyName, + String dataSourceOverrideValue, + ValidatedConnectionProperties propertiesOverrides, + BigQueryJdbcUrlUtility.ParsedConnectionUrl parsedUrl) { + if (dataSourceOverrideValue != null) { + return dataSourceOverrideValue; + } + if (propertiesOverrides != null + && propertiesOverrides.canonicalProperties.containsKey(canonicalPropertyName)) { + return propertiesOverrides.canonicalProperties.get(canonicalPropertyName); + } + return parsedUrl.getPreConnectProperty(canonicalPropertyName); + } + /** * Attempts to establish a BigQuery connection to the given URL, using the provided connection * Properties. @@ -129,116 +314,205 @@ public static BigQueryDriver getRegisteredDriver() throws IllegalStateException @Override public Connection connect(String url, Properties info) throws SQLException { LOG.finest("++enter++"); - AuthenticationType authType = AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED; + if (!acceptsURL(url)) { + return null; + } + ValidatedConnectionProperties propertiesOverrides; try { - if (acceptsURL(url)) { - Properties connectInfo = info == null ? new Properties() : (Properties) info.clone(); - Object customOpenTelemetryObj = connectInfo.remove("customOpenTelemetry"); + propertiesOverrides = validateAndCanonicalizeProperties(info); + } catch (RuntimeException e) { + LOG.log(Level.SEVERE, "Failed to parse connection URL properties", e); + BigQueryJdbcException jdbcException = + new BigQueryJdbcException("Failed to parse connection URL properties", e); + TelemetryManager.recordConnectionAttempt( + Status.STATUS_ERROR, + TelemetryManager.extractErrorCode(jdbcException), + AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED); + throw jdbcException; + } + return connectInternal(url, propertiesOverrides, null); + } + + /** + * Package-private entry point used by {@link DataSource#getConnection()} to pass a defensive + * typed snapshot directly into the driver without flattening fields into a URL string. + */ + Connection connectWithDataSource(String url, DataSource configuredDataSourceSnapshot) + throws SQLException { + LOG.finest("++enter++"); + if (!acceptsURL(url)) { + return null; + } + return connectInternal(url, null, configuredDataSourceSnapshot); + } - String connectionUri = - BigQueryJdbcUrlUtility.appendPropertiesToURL( - url.substring(5), this.toString(), connectInfo); + private Connection connectInternal( + String url, ValidatedConnectionProperties propertiesOverrides, DataSource dataSourceOverrides) + throws SQLException { + AuthenticationType authType = AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED; + try { + BigQueryJdbcUrlUtility.ParsedConnectionUrl parsedUrl = + BigQueryJdbcUrlUtility.parseConnectionUrl(url); - String telemetryOptOut = - BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation( - connectionUri, BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME); + String dataSourceTelemetryFlag = + dataSourceOverrides != null + && dataSourceOverrides.getConfiguredEnableDiagnosticTelemetry() != null + ? String.valueOf(dataSourceOverrides.getConfiguredEnableDiagnosticTelemetry()) + : null; + String propertiesTelemetryFlag = + propertiesOverrides != null + ? propertiesOverrides.canonicalProperties.get( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME) + : null; + String urlTelemetryFlag = + parsedUrl.getPreConnectProperty( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME); + boolean telemetryOptOut = + isTelemetryOptOut(dataSourceTelemetryFlag) + || isTelemetryOptOut(propertiesTelemetryFlag) + || isTelemetryOptOut(urlTelemetryFlag); + String diagnosticTelemetrySetting = + telemetryOptOut + ? "false" + : resolvePreConnectProperty( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, + dataSourceTelemetryFlag, + propertiesOverrides, + parsedUrl); + Properties telemetryProperties = new Properties(); + if (diagnosticTelemetrySetting != null) { + telemetryProperties.setProperty( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, + diagnosticTelemetrySetting); + } + TelemetryManager.getInstance(telemetryProperties); - if (telemetryOptOut != null) { - connectInfo.setProperty( - BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, telemetryOptOut); + Level logLevel; + String logPath; + boolean isConfiguredLogPathIgnored; + try { + String configuredLogLevel = + resolvePreConnectProperty( + BigQueryJdbcUrlUtility.LOG_LEVEL_PROPERTY_NAME, + dataSourceOverrides != null ? dataSourceOverrides.getLogLevel() : null, + propertiesOverrides, + parsedUrl); + if (configuredLogLevel == null) { + configuredLogLevel = System.getenv(BigQueryJdbcUrlUtility.LOG_LEVEL_ENV_VAR); } - TelemetryManager.getInstance(connectInfo); + logLevel = BigQueryJdbcUrlUtility.parseLogLevel(configuredLogLevel); - Level logLevel; - String logPath; - boolean ignoredUrlLogPath; - try { - // LogLevel - String logLevelStr = - BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation( - connectionUri, BigQueryJdbcUrlUtility.LOG_LEVEL_PROPERTY_NAME); - if (logLevelStr == null) { - logLevelStr = System.getenv(BigQueryJdbcUrlUtility.LOG_LEVEL_ENV_VAR); - } - logLevel = BigQueryJdbcUrlUtility.parseLogLevel(logLevelStr); - - // LogPath - String urlLogPath = - BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation( - connectionUri, BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME); - String envLogPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR); - - String enableGcpLogExporterStr = - BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation( - connectionUri, BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME); - boolean enableGcpLogExporter = false; - if (enableGcpLogExporterStr != null) { - enableGcpLogExporter = - BigQueryJdbcUrlUtility.convertToBoolean( - enableGcpLogExporterStr, - BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME); - } - ignoredUrlLogPath = !BigQueryJdbcUrlUtility.isUrlLogPathAllowed() && urlLogPath != null; - logPath = - BigQueryJdbcUrlUtility.resolveEffectiveLogPath( - urlLogPath, envLogPath, !enableGcpLogExporter); - - BigQueryJdbcRootLogger.setLevel(logLevel, logPath); - } catch (RuntimeException e) { - LOG.log(Level.SEVERE, "Failed to parse connection URL properties", e); - throw new BigQueryJdbcException("Failed to parse connection URL properties", e); + String configuredLogPath = + resolvePreConnectProperty( + BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME, + dataSourceOverrides != null ? dataSourceOverrides.getLogPath() : null, + propertiesOverrides, + parsedUrl); + String environmentLogPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR); + + boolean enableGcpLogExporter; + if (dataSourceOverrides != null + && dataSourceOverrides.getConfiguredEnableGcpLogExporter() != null) { + enableGcpLogExporter = dataSourceOverrides.getConfiguredEnableGcpLogExporter(); + } else { + String configuredGcpLogExporter = + resolvePreConnectProperty( + BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME, + null, + propertiesOverrides, + parsedUrl); + enableGcpLogExporter = + configuredGcpLogExporter != null + && BigQueryJdbcUrlUtility.convertToBoolean( + configuredGcpLogExporter, + BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME); } + isConfiguredLogPathIgnored = + !BigQueryJdbcUrlUtility.isUrlLogPathAllowed() && configuredLogPath != null; + logPath = + BigQueryJdbcUrlUtility.resolveEffectiveLogPath( + configuredLogPath, environmentLogPath, !enableGcpLogExporter); - // Logging starts from here. - 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); + BigQueryJdbcRootLogger.setLevel(logLevel, logPath); + } catch (RuntimeException e) { + LOG.log(Level.SEVERE, "Failed to parse connection URL properties", e); + throw new BigQueryJdbcException("Failed to parse connection URL properties", e); + } + + // Logging starts from here. + BigQueryConnection connection; + try (BigQueryJdbcMdc.MdcCloseable preConnect = + BigQueryJdbcRootLogger.openPreConnectScope(logLevel, logPath)) { + if (isConfiguredLogPathIgnored) { + LOG.warning( + "Ignoring URL/Properties %s because system property %s is false.", + BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME, + BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY); + } + String sanitizedDisplayUrl = parsedUrl.toSanitizedDisplayUrl(); + DataSource resolvedDataSource; + try { + Map validatedUrlProperties = parsedUrl.validateAndGetProperties(); + if (propertiesOverrides != null) { + for (String unknownPropertyKey : propertiesOverrides.unknownPropertyKeys) { + LOG.warning("Wrong value or unknown setting: %s", unknownPropertyKey); + } + if (propertiesOverrides.hasIgnoredInvalidPropertyKeys) { + LOG.warning(BigQueryJdbcUrlUtility.IGNORED_PROPERTY_KEY_WARNING); + } } - 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); + if (dataSourceOverrides != null) { + resolvedDataSource = + DataSource.fromCanonicalProperties(sanitizedDisplayUrl, validatedUrlProperties); + dataSourceOverrides.applyConfiguredFieldsTo(resolvedDataSource); + } else { + Map mergedConnectionProperties = + new LinkedHashMap<>(validatedUrlProperties); + if (propertiesOverrides != null) { + removeAliasesOverriddenBy( + mergedConnectionProperties, propertiesOverrides.canonicalProperties); + mergedConnectionProperties.putAll(propertiesOverrides.canonicalProperties); + } + resolvedDataSource = + DataSource.fromCanonicalProperties(sanitizedDisplayUrl, mergedConnectionProperties); + if (propertiesOverrides != null && propertiesOverrides.customOpenTelemetry != null) { + resolvedDataSource.setCustomOpenTelemetry(propertiesOverrides.customOpenTelemetry); + } } - authType = TelemetryManager.toAuthenticationType(ds.getOAuthType()); - if (customOpenTelemetryObj instanceof OpenTelemetry) { - ds.setCustomOpenTelemetry((OpenTelemetry) customOpenTelemetryObj); + if (telemetryOptOut) { + resolvedDataSource.setEnableDiagnosticTelemetry(false); } - connection = new BigQueryConnection(connectionUri, ds); - } - 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()); + } catch (BigQueryJdbcRuntimeException | IllegalArgumentException e) { + LOG.log(Level.SEVERE, "Failed to parse connection URL", e); + throw new BigQueryJdbcException("Failed to parse connection URL", e); } + authType = TelemetryManager.toAuthenticationType(resolvedDataSource.getOAuthType()); + connection = new BigQueryConnection(sanitizedDisplayUrl, resolvedDataSource); + } + 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()); + } - Connection wrapped = BigQueryJdbcContextProxy.wrap(connection, Connection.class); + Connection proxiedConnection = BigQueryJdbcContextProxy.wrap(connection, Connection.class); - TelemetryManager.recordConnectionAttempt(Status.STATUS_SUCCESS, 0, authType); - return wrapped; - } else { - return null; - } + TelemetryManager.recordConnectionAttempt(Status.STATUS_SUCCESS, 0, authType); + return proxiedConnection; } catch (IOException e) { TelemetryManager.recordConnectionAttempt( Status.STATUS_ERROR, TelemetryManager.extractErrorCode(e), authType); diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java index 61f5ac9f581a..9760956e9b5d 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java @@ -25,7 +25,6 @@ import io.opentelemetry.api.OpenTelemetry; import java.io.PrintWriter; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.SQLException; import java.util.Map; import java.util.Properties; @@ -124,12 +123,10 @@ public class DataSource implements javax.sql.DataSource { private String privateServiceConnect; private Long connectionPoolSize; private Long listenerPoolSize; - private boolean enableGcpTraceExporter = - BigQueryJdbcUrlUtility.DEFAULT_ENABLE_GCP_TRACE_EXPORTER_VALUE; - private boolean enableGcpLogExporter = - BigQueryJdbcUrlUtility.DEFAULT_ENABLE_GCP_LOG_EXPORTER_VALUE; + private Boolean enableGcpTraceExporter; + private Boolean enableGcpLogExporter; private OpenTelemetry customOpenTelemetry; - private boolean useGlobalOpenTelemetry = BigQueryJdbcUrlUtility.DEFAULT_USE_GLOBAL_OTEL_VALUE; + private Boolean useGlobalOpenTelemetry; private Boolean enableDiagnosticTelemetry; private Boolean enableGraphMetadata; @@ -254,7 +251,10 @@ public class DataSource implements javax.sql.DataSource { .put( BigQueryJdbcUrlUtility.MAX_RESULTS_PROPERTY_NAME, (ds, val) -> ds.setMaxResults(Long.parseLong(val))) - .put(BigQueryJdbcUrlUtility.PARTNER_TOKEN_PROPERTY_NAME, DataSource::setPartnerToken) + .put( + BigQueryJdbcUrlUtility.PARTNER_TOKEN_PROPERTY_NAME, + (ds, val) -> + ds.setPartnerToken(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue(val))) .put( BigQueryJdbcUrlUtility.ENABLE_WRITE_API_PROPERTY_NAME, (ds, val) -> @@ -406,17 +406,26 @@ public class DataSource implements javax.sql.DataSource { .build(); public static DataSource fromUrl(String url) { + return fromCanonicalProperties(url, BigQueryJdbcUrlUtility.parseUrl(url)); + } + + /** + * Builds a {@link DataSource} from already-validated canonical property names (keys from {@link + * BigQueryJdbcUrlUtility#PROPERTY_NAME_MAP}) and decoded string values. + */ + static DataSource fromCanonicalProperties( + String connectionUrl, Map canonicalProperties) { DataSource dataSource = new DataSource(); - dataSource.setURL(url); - Map properties = BigQueryJdbcUrlUtility.parseUrl(url); - for (Map.Entry entry : properties.entrySet()) { - BiConsumer setter = PROPERTY_SETTERS.get(entry.getKey()); - if (setter != null) { + dataSource.setURL(connectionUrl); + for (Map.Entry propertyEntry : canonicalProperties.entrySet()) { + BiConsumer propertySetter = PROPERTY_SETTERS.get(propertyEntry.getKey()); + if (propertySetter != null) { try { - setter.accept(dataSource, entry.getValue()); + propertySetter.accept(dataSource, propertyEntry.getValue()); } catch (NumberFormatException e) { throw new BigQueryJdbcRuntimeException( - String.format("Invalid value for %s. It must be a valid integer.", entry.getKey()), + String.format( + "Invalid value for %s. It must be a valid integer.", propertyEntry.getKey()), e); } } @@ -452,19 +461,291 @@ public DataSource() {} @Override public Connection getConnection() throws SQLException { - if (getURL() == null) { + String connectionUrl = getURL(); + if (connectionUrl == null) { throw new BigQueryJdbcException( "Connection URL is null. Please specify a valid Connection URL to get Connection."); } - if (!BigQueryDriver.getRegisteredDriver().acceptsURL(getURL())) { + if (!BigQueryDriver.getRegisteredDriver().acceptsURL(connectionUrl)) { throw new BigQueryJdbcException( - "The URL " + getURL() + " is invalid. Please specify a valid Connection URL. "); + "The connection URL is invalid. Please specify a valid Connection URL starting with" + + " 'jdbc:bigquery:'."); + } + return BigQueryDriver.getRegisteredDriver() + .connectWithDataSource(connectionUrl, snapshotConfiguredFields()); + } + + /** Returns an unshared snapshot of all explicitly configured JavaBean fields on this instance. */ + DataSource snapshotConfiguredFields() { + DataSource configuredSnapshot = new DataSource(); + applyConfiguredFieldsTo(configuredSnapshot); + // Preserve the unformatted partnerToken on the snapshot so an explicit non-GPN token (e.g. + // "(env)") still clears any URL-supplied PartnerToken when applied onto the URL-parsed + // DataSource. + configuredSnapshot.partnerToken = this.partnerToken; + return configuredSnapshot; + } + + /** Empty strings mean "not configured", matching the {@code Properties} path. */ + private static boolean isConfigured(String value) { + return value != null && !value.isEmpty(); + } + + /** + * Copies every configured field (non-null, and non-empty for strings) on this {@link DataSource} + * onto {@code targetDataSource}, preserving typed {@link Map} values and explicit {@code false} + * flags without serializing back into a flat URL string. + */ + void applyConfiguredFieldsTo(DataSource targetDataSource) { + if (isConfigured(this.projectId)) { + targetDataSource.projectId = this.projectId; + } + if (isConfigured(this.defaultDataset)) { + targetDataSource.defaultDataset = this.defaultDataset; + } + if (isConfigured(this.location)) { + targetDataSource.location = this.location; + } + if (isConfigured(this.userAgent)) { + targetDataSource.userAgent = this.userAgent; + } + if (this.enableHighThroughputAPI != null) { + targetDataSource.enableHighThroughputAPI = this.enableHighThroughputAPI; + } + if (this.highThroughputMinTableSize != null) { + targetDataSource.highThroughputMinTableSize = this.highThroughputMinTableSize; + } + if (this.highThroughputActivationRatio != null) { + targetDataSource.highThroughputActivationRatio = this.highThroughputActivationRatio; + } + if (this.unsupportedHTAPIFallback != null) { + targetDataSource.unsupportedHTAPIFallback = this.unsupportedHTAPIFallback; + } + if (isConfigured(this.kmsKeyName)) { + targetDataSource.kmsKeyName = this.kmsKeyName; + } + if (this.queryProperties != null) { + targetDataSource.queryProperties = this.queryProperties; + } + if (isConfigured(this.logLevel)) { + targetDataSource.logLevel = this.logLevel; + } + if (this.enableSession != null) { + targetDataSource.enableSession = this.enableSession; + } + if (this.enableTimestampPicos != null) { + targetDataSource.enableTimestampPicos = this.enableTimestampPicos; + } + if (isConfigured(this.logPath)) { + targetDataSource.logPath = this.logPath; + } + if (isConfigured(this.gcpTelemetryProjectId)) { + targetDataSource.gcpTelemetryProjectId = this.gcpTelemetryProjectId; + } + if (isConfigured(this.gcpTelemetryCredentials)) { + targetDataSource.gcpTelemetryCredentials = this.gcpTelemetryCredentials; + } + if (this.oAuthType != null) { + targetDataSource.oAuthType = this.oAuthType; + } + if (isConfigured(this.oAuthServiceAcctEmail)) { + targetDataSource.oAuthServiceAcctEmail = this.oAuthServiceAcctEmail; + } + if (isConfigured(this.oAuthPvtKeyPath)) { + targetDataSource.oAuthPvtKeyPath = this.oAuthPvtKeyPath; + } + if (isConfigured(this.oAuthPvtKey)) { + targetDataSource.oAuthPvtKey = this.oAuthPvtKey; + } + if (isConfigured(this.oAuthAccessToken)) { + targetDataSource.oAuthAccessToken = this.oAuthAccessToken; + } + if (this.oAuthAccessTokenReadonly != null) { + targetDataSource.oAuthAccessTokenReadonly = this.oAuthAccessTokenReadonly; + } + if (isConfigured(this.oAuthRefreshToken)) { + targetDataSource.oAuthRefreshToken = this.oAuthRefreshToken; + } + if (this.useQueryCache != null) { + targetDataSource.useQueryCache = this.useQueryCache; + } + if (isConfigured(this.queryDialect)) { + targetDataSource.queryDialect = this.queryDialect; + } + if (this.allowLargeResults != null) { + targetDataSource.allowLargeResults = this.allowLargeResults; + } + if (isConfigured(this.destinationTable)) { + targetDataSource.destinationTable = this.destinationTable; + } + if (isConfigured(this.destinationDataset)) { + targetDataSource.destinationDataset = this.destinationDataset; + } + if (this.destinationDatasetExpirationTime != null) { + targetDataSource.destinationDatasetExpirationTime = this.destinationDatasetExpirationTime; + } + if (isConfigured(this.universeDomain)) { + targetDataSource.universeDomain = this.universeDomain; + } + if (isConfigured(this.proxyHost)) { + targetDataSource.proxyHost = this.proxyHost; + } + if (isConfigured(this.proxyPort)) { + targetDataSource.proxyPort = this.proxyPort; + } + if (isConfigured(this.proxyUid)) { + targetDataSource.proxyUid = this.proxyUid; + } + if (isConfigured(this.proxyPwd)) { + targetDataSource.proxyPwd = this.proxyPwd; + } + if (isConfigured(this.oAuthClientId)) { + targetDataSource.oAuthClientId = this.oAuthClientId; + } + if (isConfigured(this.oAuthClientSecret)) { + targetDataSource.oAuthClientSecret = this.oAuthClientSecret; + } + if (this.jobCreationMode != null) { + targetDataSource.jobCreationMode = this.jobCreationMode; + } + if (this.maxResults != null) { + targetDataSource.maxResults = this.maxResults; + } + if (this.partnerToken != null && !this.partnerToken.isEmpty()) { + targetDataSource.partnerToken = + BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue(this.partnerToken); + } + if (this.enableWriteAPI != null) { + targetDataSource.enableWriteAPI = this.enableWriteAPI; + } + if (isConfigured(this.additionalProjects)) { + targetDataSource.additionalProjects = this.additionalProjects; + } + if (this.filterTablesOnDefaultDataset != null) { + targetDataSource.filterTablesOnDefaultDataset = this.filterTablesOnDefaultDataset; + } + if (this.enableProjectDiscovery != null) { + targetDataSource.enableProjectDiscovery = this.enableProjectDiscovery; + } + if (this.requestGoogleDriveScope != null) { + targetDataSource.requestGoogleDriveScope = this.requestGoogleDriveScope; + } + if (this.metadataFetchThreadCount != null) { + targetDataSource.metadataFetchThreadCount = this.metadataFetchThreadCount; + } + if (isConfigured(this.sslTrustStorePath)) { + targetDataSource.sslTrustStorePath = this.sslTrustStorePath; + } + if (isConfigured(this.sslTrustStorePassword)) { + targetDataSource.sslTrustStorePassword = this.sslTrustStorePassword; + } + if (isConfigured(this.sslTrustStoreType)) { + targetDataSource.sslTrustStoreType = this.sslTrustStoreType; + } + if (isConfigured(this.sslTrustStoreProvider)) { + targetDataSource.sslTrustStoreProvider = this.sslTrustStoreProvider; + } + if (this.labels != null) { + targetDataSource.labels = this.labels; + } + if (isConfigured(this.requestReason)) { + targetDataSource.requestReason = this.requestReason; + } + if (this.timeout != null) { + targetDataSource.timeout = this.timeout; + } + if (this.jobTimeout != null) { + targetDataSource.jobTimeout = this.jobTimeout; + } + if (this.retryInitialDelay != null) { + targetDataSource.retryInitialDelay = this.retryInitialDelay; + } + if (this.retryMaxDelay != null) { + targetDataSource.retryMaxDelay = this.retryMaxDelay; + } + if (this.httpConnectTimeout != null) { + targetDataSource.httpConnectTimeout = this.httpConnectTimeout; + } + if (this.httpReadTimeout != null) { + targetDataSource.httpReadTimeout = this.httpReadTimeout; + } + if (this.maximumBytesBilled != null) { + targetDataSource.maximumBytesBilled = this.maximumBytesBilled; + } + if (this.swaActivationRowCount != null) { + targetDataSource.swaActivationRowCount = this.swaActivationRowCount; + } + if (this.swaAppendRowCount != null) { + targetDataSource.swaAppendRowCount = this.swaAppendRowCount; + } + if (isConfigured(this.oAuthP12Password)) { + targetDataSource.oAuthP12Password = this.oAuthP12Password; + } + if (isConfigured(this.oAuthSAImpersonationEmail)) { + targetDataSource.oAuthSAImpersonationEmail = this.oAuthSAImpersonationEmail; + } + if (isConfigured(this.oAuthSAImpersonationChain)) { + targetDataSource.oAuthSAImpersonationChain = this.oAuthSAImpersonationChain; + } + if (isConfigured(this.oAuthSAImpersonationScopes)) { + targetDataSource.oAuthSAImpersonationScopes = this.oAuthSAImpersonationScopes; + } + if (isConfigured(this.oAuthSAImpersonationTokenLifetime)) { + targetDataSource.oAuthSAImpersonationTokenLifetime = this.oAuthSAImpersonationTokenLifetime; + } + if (isConfigured(this.oAuth2TokenUri)) { + targetDataSource.oAuth2TokenUri = this.oAuth2TokenUri; + } + if (isConfigured(this.byoidAudienceUri)) { + targetDataSource.byoidAudienceUri = this.byoidAudienceUri; + } + if (isConfigured(this.byoidCredentialSource)) { + targetDataSource.byoidCredentialSource = this.byoidCredentialSource; + } + if (isConfigured(this.byoidPoolUserProject)) { + targetDataSource.byoidPoolUserProject = this.byoidPoolUserProject; + } + if (isConfigured(this.byoidSAImpersonationUri)) { + targetDataSource.byoidSAImpersonationUri = this.byoidSAImpersonationUri; + } + if (isConfigured(this.byoidSubjectTokenType)) { + targetDataSource.byoidSubjectTokenType = this.byoidSubjectTokenType; + } + if (isConfigured(this.byoidTokenUri)) { + targetDataSource.byoidTokenUri = this.byoidTokenUri; + } + // EndpointOverrides and PrivateServiceConnectUris are aliases: overriding either replaces + // both, so a URL-supplied alias can never shadow the caller's value. + if (isConfigured(this.endpointOverrides) || isConfigured(this.privateServiceConnect)) { + targetDataSource.endpointOverrides = + isConfigured(this.endpointOverrides) ? this.endpointOverrides : null; + targetDataSource.privateServiceConnect = + isConfigured(this.privateServiceConnect) ? this.privateServiceConnect : null; + } + if (this.connectionPoolSize != null) { + targetDataSource.connectionPoolSize = this.connectionPoolSize; + } + if (this.listenerPoolSize != null) { + targetDataSource.listenerPoolSize = this.listenerPoolSize; + } + if (this.enableGcpTraceExporter != null) { + targetDataSource.enableGcpTraceExporter = this.enableGcpTraceExporter; + } + if (this.enableGcpLogExporter != null) { + targetDataSource.enableGcpLogExporter = this.enableGcpLogExporter; } - Properties props = createProperties(); if (this.customOpenTelemetry != null) { - props.put("customOpenTelemetry", this.customOpenTelemetry); + targetDataSource.customOpenTelemetry = this.customOpenTelemetry; + } + if (this.useGlobalOpenTelemetry != null) { + targetDataSource.useGlobalOpenTelemetry = this.useGlobalOpenTelemetry; + } + if (this.enableDiagnosticTelemetry != null) { + targetDataSource.enableDiagnosticTelemetry = this.enableDiagnosticTelemetry; + } + if (this.enableGraphMetadata != null) { + targetDataSource.enableGraphMetadata = this.enableGraphMetadata; } - return DriverManager.getConnection(getURL(), props); } Properties createProperties() { @@ -730,17 +1011,17 @@ Properties createProperties() { BigQueryJdbcUrlUtility.LISTENER_POOL_SIZE_PROPERTY_NAME, String.valueOf(this.listenerPoolSize)); } - if (this.enableGcpTraceExporter) { + if (this.enableGcpTraceExporter != null) { connectionProperties.setProperty( BigQueryJdbcUrlUtility.ENABLE_GCP_TRACE_EXPORTER_PROPERTY_NAME, String.valueOf(this.enableGcpTraceExporter)); } - if (this.enableGcpLogExporter) { + if (this.enableGcpLogExporter != null) { connectionProperties.setProperty( BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME, String.valueOf(this.enableGcpLogExporter)); } - if (this.useGlobalOpenTelemetry) { + if (this.useGlobalOpenTelemetry != null) { connectionProperties.setProperty( BigQueryJdbcUrlUtility.USE_GLOBAL_OTEL_PROPERTY_NAME, String.valueOf(this.useGlobalOpenTelemetry)); @@ -750,9 +1031,11 @@ Properties createProperties() { BigQueryJdbcUrlUtility.ENABLE_GRAPH_METADATA_PROPERTY_NAME, String.valueOf(this.enableGraphMetadata)); } - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, - String.valueOf(getEnableDiagnosticTelemetry())); + if (this.enableDiagnosticTelemetry != null) { + connectionProperties.setProperty( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, + String.valueOf(this.enableDiagnosticTelemetry)); + } return connectionProperties; } @@ -887,7 +1170,9 @@ public void setListenerPoolSize(Long listenerPoolSize) { } public boolean getEnableGcpTraceExporter() { - return enableGcpTraceExporter; + return enableGcpTraceExporter != null + ? enableGcpTraceExporter + : BigQueryJdbcUrlUtility.DEFAULT_ENABLE_GCP_TRACE_EXPORTER_VALUE; } public void setEnableGcpTraceExporter(boolean enableGcpTraceExporter) { @@ -895,6 +1180,16 @@ public void setEnableGcpTraceExporter(boolean enableGcpTraceExporter) { } public boolean getEnableGcpLogExporter() { + return enableGcpLogExporter != null + ? enableGcpLogExporter + : BigQueryJdbcUrlUtility.DEFAULT_ENABLE_GCP_LOG_EXPORTER_VALUE; + } + + /** + * Returns the boxed value set via {@link #setEnableGcpLogExporter(boolean)}, or {@code null} when + * unset so URL parameters or defaults apply. + */ + Boolean getConfiguredEnableGcpLogExporter() { return enableGcpLogExporter; } @@ -911,7 +1206,9 @@ public void setCustomOpenTelemetry(OpenTelemetry customOpenTelemetry) { } public boolean getUseGlobalOpenTelemetry() { - return useGlobalOpenTelemetry; + return useGlobalOpenTelemetry != null + ? useGlobalOpenTelemetry + : BigQueryJdbcUrlUtility.DEFAULT_USE_GLOBAL_OTEL_VALUE; } public void setUseGlobalOpenTelemetry(boolean useGlobalOpenTelemetry) { @@ -1629,6 +1926,14 @@ public Boolean getEnableDiagnosticTelemetry() { return TelemetryPropertyUtility.DEFAULT_ENABLE_DIAGNOSTIC_TELEMETRY_VALUE; } + /** + * Returns the boxed value set via {@link #setEnableDiagnosticTelemetry(Boolean)}, or {@code null} + * when unset so URL parameters or defaults apply. + */ + Boolean getConfiguredEnableDiagnosticTelemetry() { + return this.enableDiagnosticTelemetry; + } + public void setEnableDiagnosticTelemetry(Boolean enableDiagnosticTelemetry) { this.enableDiagnosticTelemetry = enableDiagnosticTelemetry; } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java index dde6b644e1e6..cf032920d6dd 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java @@ -155,6 +155,19 @@ public void testConnect_withCustomOpenTelemetry_injectsIntoDataSource() throws S assertThat(connection).isNotNull(); assertThat(connection.isClosed()).isFalse(); + + // Non-OpenTelemetry value records a warning key; empty string is ignored like other properties. + Properties wrongTypeProps = new Properties(); + wrongTypeProps.setProperty("customOpenTelemetry", "not-an-otel-instance"); + BigQueryDriver.ValidatedConnectionProperties wrongTypeValidated = + BigQueryDriver.validateAndCanonicalizeProperties(wrongTypeProps); + assertThat(wrongTypeValidated.customOpenTelemetry).isNull(); + assertThat(wrongTypeValidated.unknownPropertyKeys).containsExactly("customOpenTelemetry"); + + Properties emptyOtelProps = new Properties(); + emptyOtelProps.setProperty("customOpenTelemetry", ""); + assertThat(BigQueryDriver.validateAndCanonicalizeProperties(emptyOtelProps).unknownPropertyKeys) + .isEmpty(); } @Test @@ -338,7 +351,6 @@ public void testAllowUrlLogPathFalseBlocksUrlAndPropertiesLogPath(@TempDir Path } assertThat(BigQueryJdbcMdc.getConnectionId()).isEqualTo("enclosing-caller-conn"); assertThat(Files.exists(blockedUrlDir)).isFalse(); - assertThat(assertLogContains("Appending OAuthAccessToken with value ***** to URL")).isTrue(); assertThat(assertLogContains("Ignoring URL/Properties LogPath")).isTrue(); assertThat(assertLogContains("connect-secret-token")).isFalse(); @@ -414,4 +426,183 @@ public void testAllowUrlLogPathFalseBlocksUrlAndPropertiesLogPath(@TempDir Path } } } + + @Test + public void testConnect_propertiesOverrideUrlPreConnectLogAndTelemetry(@TempDir Path tempDir) + throws SQLException { + Path urlLogDir = tempDir.resolve("url_log_dir"); + Path overrideLogDir = tempDir.resolve("override_log_dir"); + String connectionUrl = + getUriOAuthToken() + .append("ProjectId", "tenant-proj") + .append("LogLevel", 7) + .append("LogPath", urlLogDir.toString()) + .append("enableGcpLogExporter", 0) + .append("EnableDiagnosticTelemetry", 0) + .toString(); + + Properties overrideProperties = new Properties(); + overrideProperties.setProperty("LogLevel", "3"); + overrideProperties.setProperty("LogPath", overrideLogDir.toString()); + overrideProperties.setProperty("EnableDiagnosticTelemetry", "1"); + + try (Connection connection = bigQueryDriver.connect(connectionUrl, overrideProperties)) { + assertThat(connection).isNotNull(); + assertThat(connection.isClosed()).isFalse(); + } + assertThat(Files.exists(overrideLogDir)).isTrue(); + assertThat(Files.exists(urlLogDir)).isFalse(); + // Telemetry opt-out in URL must always win over Properties trying to re-enable it. + assertThat(TelemetryManager.isInitialized()).isFalse(); + + // Telemetry opt-out in Properties must also win over URL enabling it. + TelemetryTestUtils.reset(); + String urlTelemetryEnabled = + getUriOAuthToken() + .append("ProjectId", "tenant-proj") + .append("EnableDiagnosticTelemetry", 1) + .toString(); + Properties optOutProperties = new Properties(); + optOutProperties.setProperty("EnableDiagnosticTelemetry", "0"); + try (Connection connection = bigQueryDriver.connect(urlTelemetryEnabled, optOutProperties)) { + assertThat(connection).isNotNull(); + assertThat(connection.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isFalse(); + } + + @Test + public void testDataSourceLogPathOverridesUrl(@TempDir Path tempDir) throws SQLException { + Path urlLogDir = tempDir.resolve("url_log_dir"); + Path setterLogDir = tempDir.resolve("setter_log_dir"); + DataSource dataSource = new DataSource(); + dataSource.setURL( + getUriOAuthToken() + .append("ProjectId", "tenant-proj") + .append("LogLevel", 3) + .append("LogPath", urlLogDir.toString()) + .append("EnableDiagnosticTelemetry", 0) + .toString()); + dataSource.setLogPath(setterLogDir.toString()); + dataSource.setEnableDiagnosticTelemetry(true); + try (Connection connection = dataSource.getConnection()) { + assertThat(connection.isClosed()).isFalse(); + } + assertThat(Files.exists(setterLogDir)).isTrue(); + assertThat(Files.exists(urlLogDir)).isFalse(); + // Telemetry opt-out in URL must always win over DataSource setter trying to re-enable it. + assertThat(TelemetryManager.isInitialized()).isFalse(); + + // Telemetry opt-out on DataSource setter must also win over URL enabling it. + TelemetryTestUtils.reset(); + DataSource optOutDataSource = new DataSource(); + optOutDataSource.setURL( + getUriOAuthToken() + .append("ProjectId", "tenant-proj") + .append("EnableDiagnosticTelemetry", 1) + .toString()); + optOutDataSource.setEnableDiagnosticTelemetry(false); + try (Connection connection = optOutDataSource.getConnection()) { + assertThat(connection.isClosed()).isFalse(); + } + assertThat(TelemetryManager.isInitialized()).isFalse(); + } + + @Test + public void testConnect_invalidPropertiesKeyIsIgnoredWithWarningThatDoesNotEchoKey() + throws SQLException { + Properties injectedProperties = new Properties(); + injectedProperties.setProperty("custom=1;SECRET_KEY_FRAGMENT", "value"); + try (Connection connection = + bigQueryDriver.connect( + VALID_TOKEN_URL + "LogLevel=3;LogPath=target/;", injectedProperties)) { + assertThat(connection.isClosed()).isFalse(); + } + assertThat(assertLogContains(BigQueryJdbcUrlUtility.IGNORED_PROPERTY_KEY_WARNING)).isTrue(); + assertThat(assertLogContains("SECRET_KEY_FRAGMENT")).isFalse(); + } + + @Test + public void testConnect_propertiesPrivateServiceConnectReplacesUrlEndpointOverridesAlias() + throws SQLException { + String urlWithEndpointOverrides = + getUriOAuthToken() + .append("ProjectId", "alias-proj") + .append("EndpointOverrides", "BIGQUERY=https://bigquery-url.p.googleapis.com") + .toString(); + Properties pscProperties = new Properties(); + pscProperties.setProperty( + "PrivateServiceConnectUris", "BIGQUERY=https://bigquery-psc.p.googleapis.com"); + try (Connection connection = bigQueryDriver.connect(urlWithEndpointOverrides, pscProperties)) { + BigQueryConnection bigQueryConnection = connection.unwrap(BigQueryConnection.class); + assertThat( + bigQueryConnection.overrideProperties.get( + BigQueryJdbcUrlUtility.BIGQUERY_ENDPOINT_OVERRIDE_PROPERTY_NAME)) + .isEqualTo("https://bigquery-psc.p.googleapis.com"); + } + } + + @Test + public void testConnect_ignoresPropertiesKeyInjectionAndFormatsPartnerToken() + throws SQLException { + String baseConnectionUrl = getUriOAuthToken().append("ProjectId", "locked-proj").toString(); + + Properties semicolonInjectedProperties = new Properties(); + semicolonInjectedProperties.setProperty( + "custom_tag=1;EndpointOverrides", "BIGQUERY=https://127.0.0.1:8443"); + try (Connection connection = + bigQueryDriver.connect(baseConnectionUrl, semicolonInjectedProperties)) { + assertThat(connection.unwrap(BigQueryConnection.class).overrideProperties) + .doesNotContainKey(BigQueryJdbcUrlUtility.BIGQUERY_ENDPOINT_OVERRIDE_PROPERTY_NAME); + } + + Properties equalsInjectedProperties = new Properties(); + equalsInjectedProperties.setProperty( + "EndpointOverrides=BIGQUERY=https://127.0.0.1:8443,DUMMY", "1"); + try (Connection connection = + bigQueryDriver.connect(baseConnectionUrl, equalsInjectedProperties)) { + assertThat(connection.unwrap(BigQueryConnection.class).overrideProperties) + .doesNotContainKey(BigQueryJdbcUrlUtility.BIGQUERY_ENDPOINT_OVERRIDE_PROPERTY_NAME); + } + + Properties partnerTokenProperties = new Properties(); + partnerTokenProperties.setProperty("PartnerToken", "(GPN:acme_partner; prod)"); + try (Connection connection = + bigQueryDriver.connect(baseConnectionUrl, partnerTokenProperties)) { + BigQueryConnection bigQueryConnection = connection.unwrap(BigQueryConnection.class); + assertThat(bigQueryConnection.getPartnerToken()).isEqualTo(" (GPN:acme_partner; prod)"); + } + + // Properties with parent defaults: direct child entries (both non-String and case-variant + // keys) must deterministically override inherited defaults while preserving unoverridden ones. + Properties defaultProperties = new Properties(); + defaultProperties.setProperty("location", "US"); + defaultProperties.setProperty("MaxResults", "100"); + defaultProperties.setProperty("RequestReason", "default-reason"); + Properties childProperties = new Properties(defaultProperties); + childProperties.setProperty("Location", "EU"); + childProperties.put("MaxResults", 250); + childProperties.setProperty("PartnerToken", "(GPN:partner%20name)"); + try (Connection connection = bigQueryDriver.connect(baseConnectionUrl, childProperties)) { + BigQueryConnection bigQueryConnection = connection.unwrap(BigQueryConnection.class); + assertThat(bigQueryConnection.getLocation()).isEqualTo("EU"); + assertThat(bigQueryConnection.getMaxResults()).isEqualTo(250L); + assertThat(bigQueryConnection.requestReason).isEqualTo("default-reason"); + assertThat(bigQueryConnection.getPartnerToken()).isEqualTo(" (GPN:partner%20name)"); + } + + // Invalid boolean and enum-style integer properties must surface as BigQueryJdbcException + // (SQLException) rather than escaping connect() as an unchecked IllegalArgumentException. + Properties invalidBooleanProperties = new Properties(); + invalidBooleanProperties.setProperty("EnableHighThroughputAPI", "maybe"); + Assertions.assertThrows( + BigQueryJdbcException.class, + () -> bigQueryDriver.connect(baseConnectionUrl, invalidBooleanProperties)); + + Properties invalidJobCreationModeProperties = new Properties(); + invalidJobCreationModeProperties.setProperty("JobCreationMode", "99"); + Assertions.assertThrows( + BigQueryJdbcException.class, + () -> bigQueryDriver.connect(baseConnectionUrl, invalidJobCreationModeProperties)); + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java index 32ddd7292d0e..1ffe6c562030 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java @@ -25,14 +25,33 @@ import static org.mockito.Mockito.CALLS_REAL_METHODS; import static org.mockito.Mockito.mockStatic; +import com.google.auth.oauth2.ImpersonatedCredentials; +import com.google.cloud.bigquery.ConnectionProperty; import com.google.cloud.bigquery.exception.BigQueryJdbcException; import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager; +import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryTestUtils; +import com.google.common.collect.ImmutableMap; +import io.opentelemetry.api.OpenTelemetry; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.sql.Connection; import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; public class DataSourceTest { + @BeforeEach + @AfterEach + public void resetTelemetry() { + TelemetryTestUtils.reset(); + } + @Test public void testWrapperMethods() throws SQLException { DataSource dataSource = new DataSource(); @@ -138,4 +157,244 @@ public void testNormalizeUniverseDomain() { "custom-universe.example.com", BigQueryJdbcUrlUtility.resolveEnvUniverseDomain(" custom-universe.example.com ")); } + + @Test + public void testGetConnection_preservesSecurityBeanPropertiesAndExplicitFalseFlags() + throws SQLException { + DataSource dataSource = new DataSource(); + dataSource.setURL( + BigQueryJdbcBaseTest.getUriOAuthToken() + .append("ProjectId", "tenant-project") + .append("enableGcpTraceExporter", 1) + .append("enableGcpLogExporter", 1) + .append("useGlobalOpenTelemetry", 1) + .append("EnableDiagnosticTelemetry", 0) + .toString()); + dataSource.setOAuthSAImpersonationEmail("restricted@tenant-project.iam.gserviceaccount.com"); + dataSource.setOAuthSAImpersonationChain("hop1@tenant-project.iam.gserviceaccount.com"); + dataSource.setOAuthSAImpersonationScopes("https://www.googleapis.com/auth/bigquery.readonly"); + dataSource.setOAuthSAImpersonationTokenLifetime("1800"); + dataSource.setPrivateServiceConnect( + "BIGQUERY=https://bigquery-psc.p.googleapis.com,READ_API=bigqueryread-psc.p.googleapis.com:443"); + dataSource.setGcpTelemetryProjectId("isolated-telemetry-project"); + dataSource.setGcpTelemetryCredentials("/path/to/telemetry-creds.json"); + dataSource.setEnableGcpTraceExporter(false); + dataSource.setEnableGcpLogExporter(false); + dataSource.setUseGlobalOpenTelemetry(false); + dataSource.setPartnerToken("(GPN:partner_co; prod)"); + + try (Connection connection = dataSource.getConnection()) { + BigQueryConnection bigQueryConnection = connection.unwrap(BigQueryConnection.class); + assertTrue(bigQueryConnection.credentials instanceof ImpersonatedCredentials); + assertEquals( + "restricted@tenant-project.iam.gserviceaccount.com", + bigQueryConnection + .getAuthProperties() + .get(BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_EMAIL_PROPERTY_NAME)); + assertEquals( + "hop1@tenant-project.iam.gserviceaccount.com", + bigQueryConnection + .getAuthProperties() + .get(BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_CHAIN_PROPERTY_NAME)); + assertEquals( + "https://www.googleapis.com/auth/bigquery.readonly", + bigQueryConnection + .getAuthProperties() + .get(BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_SCOPES_PROPERTY_NAME)); + assertEquals( + "1800", + bigQueryConnection + .getAuthProperties() + .get(BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_TOKEN_LIFETIME_PROPERTY_NAME)); + assertEquals( + "https://bigquery-psc.p.googleapis.com", + bigQueryConnection.overrideProperties.get( + BigQueryJdbcUrlUtility.BIGQUERY_ENDPOINT_OVERRIDE_PROPERTY_NAME)); + assertEquals( + "bigqueryread-psc.p.googleapis.com:443", + bigQueryConnection.overrideProperties.get( + BigQueryJdbcUrlUtility.HTAPI_ENDPOINT_OVERRIDE_PROPERTY_NAME)); + assertEquals("isolated-telemetry-project", bigQueryConnection.gcpTelemetryProjectId); + assertEquals("/path/to/telemetry-creds.json", bigQueryConnection.gcpTelemetryCredentials); + assertFalse(bigQueryConnection.enableGcpTraceExporter); + assertFalse(bigQueryConnection.enableGcpLogExporter); + assertFalse(bigQueryConnection.useGlobalOpenTelemetry); + assertEquals(" (GPN:partner_co; prod)", bigQueryConnection.getPartnerToken()); + // Unset enableDiagnosticTelemetry on DataSource must not override URL opt-out (=0). + assertFalse(TelemetryManager.isInitialized()); + } + } + + @Test + public void testGetConnection_typedMapsWithDelimitersDoNotInjectSiblingKeys() + throws SQLException { + DataSource dataSource = new DataSource(); + dataSource.setURL( + BigQueryJdbcBaseTest.getUriOAuthToken().append("ProjectId", "gateway-proj").toString()); + dataSource.setEnableSession(true); + dataSource.setQueryProperties( + ImmutableMap.of( + "dataset_project_id", + "tenant_a_proj", + "time_zone", + "UTC,dataset_project_id=tenant_b_proj,session_id=VICTIM_SESSION_ID")); + dataSource.setLabels( + ImmutableMap.of("tenant", "tenant_a", "user_note", "report,tenant=tenant_b")); + + try (Connection connection = dataSource.getConnection()) { + BigQueryConnection bigQueryConnection = connection.unwrap(BigQueryConnection.class); + List queryProperties = bigQueryConnection.getQueryProperties(); + assertEquals(2, queryProperties.size()); + assertEquals("dataset_project_id", queryProperties.get(0).getKey()); + assertEquals("tenant_a_proj", queryProperties.get(0).getValue()); + assertEquals("time_zone", queryProperties.get(1).getKey()); + assertEquals( + "UTC,dataset_project_id=tenant_b_proj,session_id=VICTIM_SESSION_ID", + queryProperties.get(1).getValue()); + assertNull(bigQueryConnection.getSessionInfoConnectionProperty()); + + Map labels = bigQueryConnection.getLabels(); + assertEquals(2, labels.size()); + assertEquals("tenant_a", labels.get("tenant")); + assertEquals("report,tenant=tenant_b", labels.get("user_note")); + } + } + + @Test + public void testGetConnection_privateServiceConnectSetterReplacesUrlEndpointOverridesAlias() + throws SQLException { + DataSource dataSource = new DataSource(); + dataSource.setURL( + BigQueryJdbcBaseTest.getUriOAuthToken() + .append("ProjectId", "alias-proj") + .append("EndpointOverrides", "BIGQUERY=https://bigquery-url.p.googleapis.com") + .toString()); + dataSource.setPrivateServiceConnect("BIGQUERY=https://bigquery-psc.p.googleapis.com"); + + try (Connection connection = dataSource.getConnection()) { + BigQueryConnection bigQueryConnection = connection.unwrap(BigQueryConnection.class); + assertEquals( + "https://bigquery-psc.p.googleapis.com", + bigQueryConnection.overrideProperties.get( + BigQueryJdbcUrlUtility.BIGQUERY_ENDPOINT_OVERRIDE_PROPERTY_NAME)); + } + } + + @Test + public void testApplyConfiguredFieldsTo_emptyAliasIsCopiedAsUnset() { + DataSource dataSource = new DataSource(); + dataSource.setEndpointOverrides(""); + dataSource.setPrivateServiceConnect("BIGQUERY=https://bigquery-psc.p.googleapis.com"); + DataSource targetDataSource = new DataSource(); + targetDataSource.setEndpointOverrides("BIGQUERY=https://bigquery-url.p.googleapis.com"); + + dataSource.applyConfiguredFieldsTo(targetDataSource); + + assertNull(targetDataSource.getEndpointOverrides()); + assertEquals( + "BIGQUERY=https://bigquery-psc.p.googleapis.com", + targetDataSource.getPrivateServiceConnect()); + } + + @Test + public void testGetConnection_emptyStringSettersAreTreatedAsUnset() throws SQLException { + DataSource dataSource = new DataSource(); + dataSource.setURL( + BigQueryJdbcBaseTest.getUriOAuthToken() + .append("ProjectId", "empty-proj") + .append("Location", "US") + .toString()); + dataSource.setLogLevel(""); + dataSource.setLocation(""); + + try (Connection connection = dataSource.getConnection()) { + assertEquals("US", connection.unwrap(BigQueryConnection.class).getLocation()); + } + } + + @Test + public void testGetConnection_invalidUrlExceptionRedactsSecrets() { + DataSource dataSource = new DataSource(); + dataSource.setURL( + "bigquery://https://localhost:443;ProjectId=p;OAuthType=2;" + + "OAuthAccessToken=SUPER_SECRET_INVALID_URL_TOKEN"); + + BigQueryJdbcException invalidUrlException = + assertThrows(BigQueryJdbcException.class, dataSource::getConnection); + assertFalse(invalidUrlException.getMessage().contains("SUPER_SECRET_INVALID_URL_TOKEN")); + } + + @Test + public void testSnapshotConfiguredFields_coversEveryNonUrlDataSourceField() throws Exception { + DataSource populatedDataSource = new DataSource(); + int populatedFieldCount = 0; + for (Field field : DataSource.class.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || "URL".equals(field.getName())) { + continue; + } + field.setAccessible(true); + Class fieldType = field.getType(); + Object sampleValue; + if (fieldType == String.class) { + sampleValue = + "partnerToken".equals(field.getName()) + ? "(GPN:test_partner)" + : "val_" + field.getName(); + } else if (fieldType == Boolean.class) { + sampleValue = Boolean.FALSE; + } else if (fieldType == Integer.class) { + sampleValue = 42; + } else if (fieldType == Long.class) { + sampleValue = 99L; + } else if (fieldType == Map.class) { + sampleValue = ImmutableMap.of("k", "v"); + } else if (fieldType == OpenTelemetry.class) { + sampleValue = OpenTelemetry.noop(); + } else { + throw new AssertionError( + "Unhandled DataSource field type for " + field.getName() + ": " + fieldType); + } + field.set(populatedDataSource, sampleValue); + populatedFieldCount++; + } + + DataSource copiedSnapshot = populatedDataSource.snapshotConfiguredFields(); + assertTrue(populatedFieldCount >= 80); + for (Field field : DataSource.class.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || "URL".equals(field.getName())) { + continue; + } + field.setAccessible(true); + Object copiedFieldValue = field.get(copiedSnapshot); + assertEquals( + field.get(populatedDataSource), + copiedFieldValue, + "DataSource.applyConfiguredFieldsTo missed field: " + field.getName()); + } + } + + @Test + public void testGetConnection_partnerTokenOverlayParityAndNoDoubleDecode() throws SQLException { + String urlWithPartnerToken = + BigQueryJdbcBaseTest.getUriOAuthToken() + .append("ProjectId", "partner-proj") + .append("PartnerToken", "(GPN:url_partner)") + .toString(); + + DataSource invalidPartnerTokenDataSource = new DataSource(); + invalidPartnerTokenDataSource.setURL(urlWithPartnerToken); + invalidPartnerTokenDataSource.setPartnerToken("(env)"); + try (Connection connection = invalidPartnerTokenDataSource.getConnection()) { + BigQueryConnection bigQueryConnection = connection.unwrap(BigQueryConnection.class); + assertNull(bigQueryConnection.getPartnerToken()); + } + + DataSource literalPercentDataSource = new DataSource(); + literalPercentDataSource.setURL(urlWithPartnerToken); + literalPercentDataSource.setPartnerToken("(GPN:partner%20name)"); + try (Connection connection = literalPercentDataSource.getConnection()) { + BigQueryConnection bigQueryConnection = connection.unwrap(BigQueryConnection.class); + assertEquals(" (GPN:partner%20name)", bigQueryConnection.getPartnerToken()); + } + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSourceTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSourceTest.java index a486d28ecd7b..8d6333ad5064 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSourceTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSourceTest.java @@ -27,12 +27,15 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import com.google.cloud.bigquery.ConnectionProperty; import com.google.cloud.bigquery.exception.BigQueryJdbcException; import com.google.cloud.bigquery.jdbc.utils.TestUtilities.TestConnectionListener; +import com.google.common.collect.ImmutableMap; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; @@ -417,4 +420,35 @@ public void testStandalonePooledConnectionListenerOnDataSourceConnection_closesO pc2.close(); } } + + @Test + public void testGetPooledConnection_preservesSecurityPropertiesAndTypedMaps() + throws SQLException { + PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); + pooledDataSource.setURL(buildTestUrl(4L, 10L)); + pooledDataSource.setEndpointOverrides("BIGQUERY=https://psc.internal.example.com"); + pooledDataSource.setGcpTelemetryProjectId("audit-telemetry-proj"); + pooledDataSource.setQueryProperties( + ImmutableMap.of( + "dataset_project_id", "tenant_a", "time_zone", "UTC,session_id=VICTIM_SID")); + pooledDataSource.setLabels(ImmutableMap.of("tenant", "tenant_a", "note", "ok,tenant=tenant_b")); + + PooledConnection pooledConnection = pooledDataSource.getPooledConnection(); + try (Connection connection = pooledConnection.getConnection()) { + BigQueryConnection physicalConnection = connection.unwrap(BigQueryConnection.class); + assertEquals( + "https://psc.internal.example.com", + physicalConnection.overrideProperties.get( + BigQueryJdbcUrlUtility.BIGQUERY_ENDPOINT_OVERRIDE_PROPERTY_NAME)); + assertEquals("audit-telemetry-proj", physicalConnection.gcpTelemetryProjectId); + List queryProperties = physicalConnection.getQueryProperties(); + assertEquals(2, queryProperties.size()); + assertNull(physicalConnection.getSessionInfoConnectionProperty()); + Map labels = physicalConnection.getLabels(); + assertEquals("tenant_a", labels.get("tenant")); + assertEquals("ok,tenant=tenant_b", labels.get("note")); + } finally { + pooledConnection.close(); + } + } }