diff --git a/java-bigquery-jdbc/DEVELOPMENT.md b/java-bigquery-jdbc/DEVELOPMENT.md index 825da028d7b2..506afbfeb6b7 100644 --- a/java-bigquery-jdbc/DEVELOPMENT.md +++ b/java-bigquery-jdbc/DEVELOPMENT.md @@ -41,7 +41,7 @@ graph TD - **`BigQueryDriver`**: JDBC entry point registered with `java.sql.DriverManager`. Intercepts `jdbc:bigquery://` URLs, initializes early logger state, and instantiates `BigQueryConnection`. - **`BigQueryConnection`**: Represents an active BigQuery session, holding dataset defaults, connection configuration maps, and transaction/session state (`EnableSession=true`, `session_id`). -- **`BigQueryJdbcUrlUtility`**: Parses and validates connection string parameters using a bounded LRU parse cache (`PARSE_CACHE`) to avoid heavy allocations during frequent connection creation. +- **`BigQueryJdbcUrlUtility`**: Parses and validates connection string parameters in a single pass (`parseConnectionUrl`). It keeps no static cache, so URLs that carry credentials are not retained across connections. - **`BigQueryJdbcContextProxy`**: A dynamic proxy layer (`java.lang.reflect.Proxy`) wrapping JDBC statements, connections, and metadata. Intercepts calls to propagate ThreadLocal MDC parameters (`connectionId`) across execution threads and enforce state validation (`checkClosed()`). - **`BigQueryTypeRegistry` & `TypeDescriptor`**: Centralized, bidirectional mapping between JDBC SQL types, Java classes and BigQuery types (`StandardSQLTypeName`), including the coercion of raw values (`Date`, `Timestamp`, `BigDecimal`, etc.) into the expected Java type. - **`BigQueryArrowResultSet`**: Custom result set implementation accelerating large query result retrieval via the BigQuery Storage Read API gRPC stream. diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index cb2f7cc28e92..2a16a5dcfb17 100644 --- a/java-bigquery-jdbc/docs/USER_GUIDE.md +++ b/java-bigquery-jdbc/docs/USER_GUIDE.md @@ -286,6 +286,21 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443" | `gcpTelemetryCredentials` | `null` | File path or raw JSON credentials string for OpenTelemetry GCP exporters. | | `useGlobalOpenTelemetry` | `false` | Instructs the driver to register with the global OpenTelemetry instance (`GlobalOpenTelemetry`) in the JVM environment. | +### Configuration precedence and credential handling + +- When a property is set in more than one place, `DataSource` setters win over + `Properties`, which win over the JDBC URL. An explicit + `EnableDiagnosticTelemetry` opt-out (`0` or `false`) in any source always wins. +- `DatabaseMetaData.getURL()` returns only the connection endpoint, without any + connection properties, so it cannot be used to open a second connection. +- `Driver.getPropertyInfo()` returns `null` as the value of credentials and of any + other property that is not on the driver's safe-to-log list. +- `Labels` and `QueryProperties` reject duplicate or empty keys. +- `Properties` keys that contain `;`, `=`, control characters, or leading or + trailing spaces are ignored with a warning. +- Empty values (`""`), whether from `Properties` or `DataSource` setters, are + treated as unset. + --- ## 5. Data Type Mapping Reference 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 8699c261a60a..3e0249bd2636 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 @@ -154,6 +154,8 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { BigQueryJdbcUrlUtility.ENABLE_PROJECT_DISCOVERY_PROPERTY_NAME, BigQueryJdbcUrlUtility.REQUEST_GOOGLE_DRIVE_SCOPE_PROPERTY_NAME, BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PROPERTY_NAME, + BigQueryJdbcUrlUtility.SSL_TRUST_STORE_TYPE_PROPERTY_NAME, + BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PROVIDER_PROPERTY_NAME, BigQueryJdbcUrlUtility.MAX_BYTES_BILLED_PROPERTY_NAME, BigQueryJdbcUrlUtility.LABELS_PROPERTY_NAME, BigQueryJdbcUrlUtility.REQUEST_REASON_PROPERTY_NAME, @@ -171,6 +173,10 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { BigQueryJdbcUrlUtility.OAUTH_SA_EMAIL_PROPERTY_NAME, BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PATH_PROPERTY_NAME, BigQueryJdbcUrlUtility.OAUTH_CLIENT_ID_PROPERTY_NAME, + BigQueryJdbcUrlUtility.GCP_TELEMETRY_PROJECT_ID_PROPERTY_NAME, + BigQueryJdbcUrlUtility.ENABLE_GCP_TRACE_EXPORTER_PROPERTY_NAME, + BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME, + BigQueryJdbcUrlUtility.USE_GLOBAL_OTEL_PROPERTY_NAME, BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, BigQueryJdbcUrlUtility.ENABLE_GRAPH_METADATA_PROPERTY_NAME) .build(); @@ -297,11 +303,19 @@ static String sanitizeForLog(String value) { return sb == null ? value : sb.toString(); } + /** + * Returns whether {@code propertyName} is in the fail-closed {@link #SAFE_TO_LOG_PROPERTIES} + * allowlist. Any unknown or sensitive property returns {@code false}. + */ + static boolean isSafeToLogProperty(String propertyName) { + return propertyName != null && SAFE_TO_LOG_PROPERTIES.contains(propertyName); + } + static String maskPropertyValue(String key, Object value) { if (value == null) { return null; } - if (key == null || !SAFE_TO_LOG_PROPERTIES.contains(key)) { + if (!isSafeToLogProperty(key)) { return "*****"; } return sanitizeForLog(String.valueOf(value)); @@ -332,15 +346,11 @@ static String maskPropertyValue(String key, Object value) { ExecutorService createdQueryExecutor = null; ExecutorService createdMetadataExecutor = null; try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(this.connectionId)) { - this.connectionUrl = url; + // DatabaseMetaData.getURL() exposes only the connection endpoint, never connection + // properties, whether the connection came from Driver, DataSource, or the constructor. + this.connectionUrl = BigQueryJdbcUrlUtility.sanitizeUrlForDisplay(url); if (LOG.isLoggable(Level.CONFIG)) { - Properties connectionProps = ds.createProperties(); - Properties maskedProps = new Properties(); - for (String name : connectionProps.stringPropertyNames()) { - maskedProps.setProperty( - sanitizeForLog(name), maskPropertyValue(name, connectionProps.getProperty(name))); - } - LOG.config("Connection properties: %s", maskedProps.toString()); + LOG.config("Connection properties: %s", ds.toMaskedLogMap().toString()); } this.openStatements = ConcurrentHashMap.newKeySet(); this.autoCommit = true; diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java index fcd6c4c5296f..2572a1759d51 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java @@ -192,6 +192,7 @@ public boolean allTablesAreSelectable() { @Override public String getURL() { + // Returns only the sanitized jdbc:bigquery: connection endpoint (no connection properties). return this.URL; } 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 de14bdbfc1da..75b3e9227683 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; @@ -108,6 +111,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. @@ -128,116 +313,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); + } - String connectionUri = - BigQueryJdbcUrlUtility.appendPropertiesToURL( - url.substring(5), this.toString(), connectInfo); + /** + * 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 telemetryOptOut = - BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation( - connectionUri, BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME); + private Connection connectInternal( + String url, ValidatedConnectionProperties propertiesOverrides, DataSource dataSourceOverrides) + throws SQLException { + AuthenticationType authType = AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED; + try { + BigQueryJdbcUrlUtility.ParsedConnectionUrl parsedUrl = + BigQueryJdbcUrlUtility.parseConnectionUrl(url); - if (telemetryOptOut != null) { - connectInfo.setProperty( - BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, telemetryOptOut); - } - TelemetryManager.getInstance(connectInfo); + 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); - 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); + 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); } + logLevel = BigQueryJdbcUrlUtility.parseLogLevel(configuredLogLevel); - // 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.", + String configuredLogPath = + resolvePreConnectProperty( BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME, - BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY); + 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); + + 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); @@ -269,33 +543,73 @@ public boolean acceptsURL(String url) throws SQLException { * @param url the BigQuery connection URL * @param info a proposed list BigQuery connection properties * @return an array of {@code DriverPropertyInfo} objects describing possible properties. + * @throws SQLException if the connection URL or properties cannot be parsed * @see Driver#getPropertyInfo(String, Properties) */ @Override - public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) { + public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { + try { + return describeProperties(url, info); + } catch (BigQueryJdbcRuntimeException | IllegalArgumentException e) { + throw new BigQueryJdbcException("Failed to parse connection URL properties", e); + } + } + + private DriverPropertyInfo[] describeProperties(String url, Properties info) { LOG.finest("++enter++"); - String connectionUri = - BigQueryJdbcUrlUtility.appendPropertiesToURL(url.substring(5), this.toString(), info); - List propertyInfoList = new ArrayList<>(); + if (url == null || !url.startsWith("jdbc:bigquery:")) { + return new DriverPropertyInfo[0]; + } + BigQueryJdbcUrlUtility.ParsedConnectionUrl parsedUrl = + BigQueryJdbcUrlUtility.parseConnectionUrl(url); + Map mergedConnectionProperties = + new LinkedHashMap<>(parsedUrl.validateAndGetProperties()); + ValidatedConnectionProperties propertiesOverrides = validateAndCanonicalizeProperties(info); + mergedConnectionProperties.putAll(propertiesOverrides.canonicalProperties); + // Mirror connect(): an EnableDiagnosticTelemetry opt-out from any source wins. + String telemetryPropertyName = BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME; + if (isTelemetryOptOut(parsedUrl.getPreConnectProperty(telemetryPropertyName)) + || isTelemetryOptOut(propertiesOverrides.canonicalProperties.get(telemetryPropertyName))) { + mergedConnectionProperties.put(telemetryPropertyName, "false"); + } - for (BigQueryConnectionProperty prop : BigQueryJdbcUrlUtility.VALID_PROPERTIES) { + List propertyInfoList = new ArrayList<>(); + for (BigQueryConnectionProperty connectionProperty : BigQueryJdbcUrlUtility.VALID_PROPERTIES) { + String propertyName = connectionProperty.getName(); DriverPropertyInfo driverProperty = new DriverPropertyInfo( - prop.getName(), - BigQueryJdbcUrlUtility.parseUriProperty(connectionUri, prop.getName())); - driverProperty.description = prop.getDescription(); + propertyName, + redactPropertyInfoValue(propertyName, mergedConnectionProperties.get(propertyName))); + driverProperty.description = connectionProperty.getDescription(); propertyInfoList.add(driverProperty); } - DataSource ds = DataSource.fromUrl(connectionUri); - Map oAuthProperties = - BigQueryJdbcOAuthUtility.parseOAuthProperties(ds, this.toString()); - for (Map.Entry authProperty : oAuthProperties.entrySet()) { - propertyInfoList.add(new DriverPropertyInfo(authProperty.getKey(), authProperty.getValue())); + if (mergedConnectionProperties.containsKey(BigQueryJdbcUrlUtility.OAUTH_TYPE_PROPERTY_NAME)) { + DataSource parsedDataSource = + DataSource.fromCanonicalProperties( + parsedUrl.toSanitizedDisplayUrl(), mergedConnectionProperties); + Map oAuthProperties = + BigQueryJdbcOAuthUtility.parseOAuthProperties(parsedDataSource, this.toString()); + for (Map.Entry authProperty : oAuthProperties.entrySet()) { + propertyInfoList.add( + new DriverPropertyInfo( + authProperty.getKey(), + redactPropertyInfoValue(authProperty.getKey(), authProperty.getValue()))); + } } return propertyInfoList.toArray(new DriverPropertyInfo[0]); } + private static String redactPropertyInfoValue(String propertyName, String propertyValue) { + // Return null (per JDBC Driver.getPropertyInfo contract) for non-allowlisted secret properties + // rather than plaintext or "*****", preventing credential disclosure and ensuring GUI/BI tools + // never resubmit a masked placeholder as a live credential. + if (!BigQueryConnection.isSafeToLogProperty(propertyName)) { + return null; + } + return propertyValue; + } + @Override public int getMajorVersion() { LOG.finest("++enter++"); diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java index 41a1df22f939..608967ac40da 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java @@ -23,17 +23,16 @@ import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryPropertyUtility; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; -import com.google.common.net.UrlEscapers; import java.security.KeyStore; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; import java.util.Set; import java.util.logging.Level; import java.util.regex.Matcher; @@ -45,14 +44,6 @@ */ final class BigQueryJdbcUrlUtility { - private static final Map> PARSE_CACHE = - Collections.synchronizedMap( - new LinkedHashMap>(50, 0.75f, true) { - protected boolean removeEldestEntry(Map.Entry> eldest) { - return size() > 50; // bound cache size - } - }); - // TODO: Add all Connection options static final String ALLOW_LARGE_RESULTS_PROPERTY_NAME = "AllowLargeResults"; static final String LARGE_RESULTS_TABLE_PROPERTY_NAME = "LargeResultTable"; @@ -710,27 +701,27 @@ protected boolean removeEldestEntry(Map.Entry> eldes ENDPOINT_OVERRIDES_PROPERTY_NAME, PRIVATE_SERVICE_CONNECT_PROPERTY_NAME); - private static final Map PROPERTY_NAME_MAP; + static final Map PROPERTY_NAME_MAP; static { Map map = new HashMap<>(); for (BigQueryConnectionProperty p : VALID_PROPERTIES) { - map.put(p.getName().toUpperCase(), p.getName()); + map.put(p.getName().toUpperCase(Locale.ROOT), p.getName()); } for (BigQueryConnectionProperty p : AUTH_PROPERTIES) { - map.put(p.getName().toUpperCase(), p.getName()); + map.put(p.getName().toUpperCase(Locale.ROOT), p.getName()); } for (BigQueryConnectionProperty p : PROXY_PROPERTIES) { - map.put(p.getName().toUpperCase(), p.getName()); + map.put(p.getName().toUpperCase(Locale.ROOT), p.getName()); } for (String p : OVERRIDE_PROPERTIES) { - map.put(p.toUpperCase(), p); + map.put(p.toUpperCase(Locale.ROOT), p); } for (String p : BYOID_PROPERTIES) { - map.put(p.toUpperCase(), p); + map.put(p.toUpperCase(Locale.ROOT), p); } for (String p : NETWORK_PROPERTIES) { - map.put(p.toUpperCase(), p); + map.put(p.toUpperCase(Locale.ROOT), p); } PROPERTY_NAME_MAP = Collections.unmodifiableMap(map); } @@ -746,108 +737,306 @@ private BigQueryJdbcUrlUtility() {} */ static String parseUriProperty(String uri, String property) { Map map = parseUrl(uri); - if (PROPERTY_NAME_MAP.containsKey(property.toUpperCase())) { - return map.get(PROPERTY_NAME_MAP.get(property.toUpperCase())); + if (PROPERTY_NAME_MAP.containsKey(property.toUpperCase(Locale.ROOT))) { + return map.get(PROPERTY_NAME_MAP.get(property.toUpperCase(Locale.ROOT))); } return map.get(property); } /** - * Parses a URI property from the given URI without validating any other properties. + * Immutable result of a single-pass, non-throwing parse of a BigQuery JDBC connection URL. * - * @param uri The URI to parse. - * @param property The name of the property to parse. - * @return The String value of the property, or null if the property is not found. + *

Connection setup uses this result in two phases: + * + *

    + *
  • Phase 1 (pre-connect / bootstrap lookup): "Bootstrap" here refers strictly to the + * pre-connect logging and telemetry settings ({@code EnableDiagnosticTelemetry}, {@code + * LogLevel}, {@code LogPath}, {@code enableGcpLogExporter}) that must be read using + * last-wins semantics before opening the pre-connect log scope and before full URL + * validation throws. + *
  • Phase 2 (validation): Once logging is active, callers invoke {@link + * #validateAndGetProperties()} to reject malformed segments or invalid percent-encoding (by + * 1-based segment position only, never echoing raw secret slices) and warn on unknown keys. + *
*/ - static String parseUriPropertyWithoutValidation(String uri, String property) { - if (uri == null) { - return null; + static final class ParsedConnectionUrl { + private final String urlPrefix; + private final Map canonicalProperties; + private final List malformedSegmentPositions; + private final List invalidPercentEncodingPositions; + private final List unknownPropertyKeys; + + ParsedConnectionUrl( + String urlPrefix, + Map canonicalProperties, + List malformedSegmentPositions, + List invalidPercentEncodingPositions, + List unknownPropertyKeys) { + this.urlPrefix = urlPrefix; + this.canonicalProperties = Collections.unmodifiableMap(canonicalProperties); + this.malformedSegmentPositions = Collections.unmodifiableList(malformedSegmentPositions); + this.invalidPercentEncodingPositions = + Collections.unmodifiableList(invalidPercentEncodingPositions); + this.unknownPropertyKeys = Collections.unmodifiableList(unknownPropertyKeys); } - int start = 0; - int len = uri.length(); - while (start < len) { - int nextSemi = uri.indexOf(';', start); - int end = (nextSemi == -1) ? len : nextSemi; - int eqIndex = uri.indexOf('=', start); - if (eqIndex > start && eqIndex < end) { - String key = uri.substring(start, eqIndex).trim(); - if (key.equalsIgnoreCase(property)) { - String value = uri.substring(eqIndex + 1, end); - return CharEscapers.decodeUriPath(value.replace("+", "%2B")); - } + /** + * Phase 1 non-throwing last-wins lookup for a pre-connect (bootstrap) property such as {@code + * LogLevel}, {@code LogPath}, {@code enableGcpLogExporter}, or {@code + * EnableDiagnosticTelemetry}, matched case-insensitively. + */ + String getPreConnectProperty(String propertyName) { + if (propertyName == null) { + return null; } + String canonicalPropertyName = PROPERTY_NAME_MAP.get(propertyName.toUpperCase(Locale.ROOT)); + return canonicalPropertyName != null + ? canonicalProperties.get(canonicalPropertyName) + : canonicalProperties.get(propertyName); + } - start = end + 1; + /** + * Phase 2 validation step: rejects malformed segments or invalid percent-encoding without + * echoing raw parameter text, logs warnings for unknown property keys, and returns the + * canonicalized URL property map. + */ + Map validateAndGetProperties() { + if (!malformedSegmentPositions.isEmpty()) { + throw new BigQueryJdbcRuntimeException( + String.format( + "Malformed connection property segment at index %d. Expected key=value format.", + malformedSegmentPositions.get(0))); + } + if (!invalidPercentEncodingPositions.isEmpty()) { + throw new BigQueryJdbcRuntimeException( + String.format( + "Invalid URL-encoded value at connection property segment %d.", + invalidPercentEncodingPositions.get(0))); + } + for (String unknownPropertyKey : unknownPropertyKeys) { + LOG.warning("Wrong value or unknown setting: %s", unknownPropertyKey); + } + return canonicalProperties; + } + + /** + * Builds the display URL returned by {@code DatabaseMetaData.getURL()}: the caller's connection + * endpoint only, for example {@code + * jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443}. + */ + String toSanitizedDisplayUrl() { + if (urlPrefix == null) { + return null; + } + String sanitizedUrlPrefix = BigQueryConnection.sanitizeForLog(urlPrefix); + String normalizedUrlPrefix = + sanitizedUrlPrefix.startsWith("bigquery:") + ? "jdbc:" + sanitizedUrlPrefix + : sanitizedUrlPrefix; + if (normalizedUrlPrefix.indexOf('=') >= 0 + || normalizedUrlPrefix.indexOf('?') >= 0 + || normalizedUrlPrefix.indexOf('@') >= 0) { + // A well-formed prefix is scheme://host[:port]; anything else may carry a credential. + normalizedUrlPrefix = "jdbc:bigquery:"; + } + // The display URL is informational only, so no connection properties are appended: with + // credentials removed it could not open a new connection anyway, and omitting every property + // guarantees no configuration or secret is exposed through metadata, traces, or logs. The + // caller's endpoint is kept so PSC and custom-universe connections remain identifiable. + return normalizedUrlPrefix; } - return null; } /** - * Parses the URL into a map of key-value pairs, validating that all keys are known properties. + * Formats an already-decoded {@code PartnerToken} value into the canonical {@code " (GPN:...)"} + * user-agent header suffix by trimming surrounding whitespace, stripping optional outer + * parentheses, and requiring a case-insensitive {@code GPN:} prefix. Returns {@code null} when + * the value does not carry a {@code GPN:} partner identifier. * - * @param url The URL to parse. - * @return A map of property names to values. - * @throws BigQueryJdbcRuntimeException if an unknown property is found or the URL is malformed. + *

URL percent-decoding is intentionally performed only once in {@link + * #parseConnectionUrl(String)} so URL values are never double-decoded and discrete {@code + * Properties}/{@code DataSource} values preserve literal {@code %} sequences. */ - static Map parseUrl(String url) { - return PARSE_CACHE.computeIfAbsent(url, BigQueryJdbcUrlUtility::parseUrlInternal); + static String formatPartnerTokenHeaderValue(String partnerTokenValue) { + if (partnerTokenValue == null) { + return null; + } + String trimmedToken = partnerTokenValue.trim(); + String unwrappedToken = + (trimmedToken.startsWith("(") && trimmedToken.endsWith(")") && trimmedToken.length() >= 2) + ? trimmedToken.substring(1, trimmedToken.length() - 1).trim() + : trimmedToken; + if (!unwrappedToken.equals(BigQueryConnection.sanitizeForLog(unwrappedToken))) { + return null; // control characters must never reach the user-agent header + } + if (unwrappedToken.toUpperCase(Locale.ROOT).startsWith("GPN:")) { + return " (" + unwrappedToken + ")"; + } + return null; } - private static Map parseUrlInternal(String url) { - Map map = new HashMap<>(); - if (url == null) { - return map; + /** + * Performs a single-pass, non-throwing parse of {@code connectionUrl} using last-wins semantics. + * + *

URLs are intentionally not cached in static memory to avoid retaining plaintext credentials + * across connections and to avoid global lock contention during concurrent connect bursts. + */ + static ParsedConnectionUrl parseConnectionUrl(String connectionUrl) { + if (connectionUrl == null) { + return new ParsedConnectionUrl( + null, + Collections.emptyMap(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList()); } - String[] urlParts = url.split(";", 2); - if (urlParts.length < 2) { - return map; + int firstSemicolonIndex = connectionUrl.indexOf(';'); + if (firstSemicolonIndex == -1) { + return new ParsedConnectionUrl( + connectionUrl, + Collections.emptyMap(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList()); } - String urlToParse = urlParts[1]; + String urlPrefix = connectionUrl.substring(0, firstSemicolonIndex); + String parameterSection = connectionUrl.substring(firstSemicolonIndex + 1); + Map canonicalProperties = new LinkedHashMap<>(); + List malformedSegmentPositions = new ArrayList<>(); + List invalidPercentEncodingPositions = new ArrayList<>(); + List unknownPropertyKeys = new ArrayList<>(); - // Parse PartnerToken separately as it contains ';' - Matcher matcher = PARTNER_TOKEN_PATTERN.matcher(urlToParse); - if (matcher.find()) { - String rawToken = matcher.group(1).trim(); - String token = - (rawToken.startsWith("(") && rawToken.endsWith(")")) - ? rawToken.substring(1, rawToken.length() - 1).trim() - : rawToken; - - if (token.toUpperCase().startsWith("GPN:")) { - map.put(PARTNER_TOKEN_PROPERTY_NAME, " (" + token + ")"); + // Parse all PartnerToken occurrences separately because valid tokens may contain ';'. + Matcher partnerTokenMatcher = PARTNER_TOKEN_PATTERN.matcher(parameterSection); + StringBuffer remainingParameterSection = null; + while (partnerTokenMatcher.find()) { + if (remainingParameterSection == null) { + remainingParameterSection = new StringBuffer(); + } + String encodedPartnerToken = partnerTokenMatcher.group(1); + String decodedPartnerToken = encodedPartnerToken; + if (decodedPartnerToken.indexOf('%') >= 0) { + try { + decodedPartnerToken = CharEscapers.decodeUriPath(decodedPartnerToken.replace("+", "%2B")); + } catch (IllegalArgumentException ignored) { + // Keep original partner token text when '%' is not a valid percent-escape. + } + } + String formattedPartnerToken = formatPartnerTokenHeaderValue(decodedPartnerToken); + if (formattedPartnerToken != null) { + canonicalProperties.put(PARTNER_TOKEN_PROPERTY_NAME, formattedPartnerToken); + } else { + canonicalProperties.remove(PARTNER_TOKEN_PROPERTY_NAME); } - urlToParse = matcher.replaceFirst(""); + partnerTokenMatcher.appendReplacement(remainingParameterSection, ""); } + if (remainingParameterSection != null) { + partnerTokenMatcher.appendTail(remainingParameterSection); + parameterSection = remainingParameterSection.toString(); + } + + int segmentPosition = 0; + int segmentStart = 0; + int parameterSectionLength = parameterSection.length(); + while (segmentStart <= parameterSectionLength) { + int nextSemicolonIndex = parameterSection.indexOf(';', segmentStart); + int segmentEnd = (nextSemicolonIndex == -1) ? parameterSectionLength : nextSemicolonIndex; + String segment = parameterSection.substring(segmentStart, segmentEnd); + segmentStart = + (nextSemicolonIndex == -1) ? parameterSectionLength + 1 : nextSemicolonIndex + 1; - String[] parts = urlToParse.split(";"); - for (String part : parts) { - if (part.trim().isEmpty()) { + if (segment.trim().isEmpty()) { continue; } - String[] kv = part.split("=", 2); - String key = kv[0].trim().toUpperCase(); - if (kv.length != 2 || !PROPERTY_NAME_MAP.containsKey(key)) { - String ref = (kv.length == 2) ? key : part; - String safeRef = ref.length() > 32 ? ref.substring(0, 32) + "..." : ref; - // Some tools can pass unknown keys. In order not to break compatibility, throw - // an exception only with incorrect format, otherwise log an error. - if (kv.length != 2) { - throw new BigQueryJdbcRuntimeException( - String.format("Wrong value or unknown setting: %s", safeRef)); - } else { - LOG.warning( - "Wrong value or unknown setting: %s", BigQueryConnection.sanitizeForLog(safeRef)); - continue; - } + segmentPosition++; + + int equalsIndex = segment.indexOf('='); + if (equalsIndex <= 0 || segment.substring(0, equalsIndex).trim().isEmpty()) { + malformedSegmentPositions.add(segmentPosition); + continue; + } + String uppercasePropertyKey = + segment.substring(0, equalsIndex).trim().toUpperCase(Locale.ROOT); + String canonicalPropertyName = PROPERTY_NAME_MAP.get(uppercasePropertyKey); + if (canonicalPropertyName == null) { + // Some tools pass unknown keys; preserve compatibility by warning in Phase 2 instead of + // failing the connection. + String truncatedPropertyKey = + uppercasePropertyKey.length() > 32 + ? uppercasePropertyKey.substring(0, 32) + "..." + : uppercasePropertyKey; + unknownPropertyKeys.add(BigQueryConnection.sanitizeForLog(truncatedPropertyKey)); + continue; + } + + String encodedPropertyValue = segment.substring(equalsIndex + 1); + String decodedPropertyValue; + try { + decodedPropertyValue = CharEscapers.decodeUriPath(encodedPropertyValue.replace("+", "%2B")); + } catch (IllegalArgumentException e) { + invalidPercentEncodingPositions.add(segmentPosition); + continue; } - String propertyName = PROPERTY_NAME_MAP.get(key); - String value = CharEscapers.decodeUriPath(kv[1].replace("+", "%2B")); - map.put(propertyName, value); + canonicalProperties.put(canonicalPropertyName, decodedPropertyValue); } - return Collections.unmodifiableMap(map); + + return new ParsedConnectionUrl( + urlPrefix, + canonicalProperties, + malformedSegmentPositions, + invalidPercentEncodingPositions, + unknownPropertyKeys); + } + + /** + * Returns the display URL for {@code connectionUrl}: the {@code jdbc:bigquery:} connection + * endpoint only, without any connection properties. + */ + static String sanitizeUrlForDisplay(String connectionUrl) { + return parseConnectionUrl(connectionUrl).toSanitizedDisplayUrl(); + } + + /** Warning logged when {@link #extractValidPropertyKey(Object)} ignores a property key. */ + static final String IGNORED_PROPERTY_KEY_WARNING = + "Ignoring a connection property key that is blank, has leading or trailing whitespace, or" + + " contains ';', '=', or control characters."; + + /** + * Returns a caller-supplied {@code Properties} key, or {@code null} if the key must be ignored + * because it is blank, has leading/trailing whitespace, or contains {@code ';'}, {@code '='}, or + * ASCII control characters. Such keys can never name a connection property. + * + * @throws BigQueryJdbcRuntimeException if the key is {@code null} or not a {@link String}; JDBC + * defines connection properties as String key/value pairs. + */ + static String extractValidPropertyKey(Object propertyKeyObject) { + if (!(propertyKeyObject instanceof String)) { + throw new BigQueryJdbcRuntimeException("Connection property keys must be non-null strings."); + } + String propertyKey = (String) propertyKeyObject; + if (propertyKey.isEmpty() || !propertyKey.equals(propertyKey.trim())) { + return null; + } + for (int index = 0; index < propertyKey.length(); index++) { + char character = propertyKey.charAt(index); + if (character == ';' || character == '=' || character < 0x20 || character == 0x7F) { + return null; + } + } + return propertyKey; + } + + /** + * Parses the URL into a map of key-value pairs, validating that all segments are well-formed. + * + * @param url The URL to parse. + * @return An unmodifiable map of canonical property names to decoded values. + * @throws BigQueryJdbcRuntimeException if any segment is malformed or has invalid URL encoding. + */ + static Map parseUrl(String url) { + return parseConnectionUrl(url).validateAndGetProperties(); } static boolean isUrlLogPathAllowed() { @@ -877,41 +1066,6 @@ static String resolveEffectiveLogPath( return allowDefaultFallback ? DEFAULT_LOG_PATH : null; } - /** - * Appends the given properties to the given URL. - * - * @param url The URL to append the properties to. - * @param properties The properties to append. - * @return The string value of the updated URL. - */ - static String appendPropertiesToURL(String url, String callerClassName, Properties properties) { - LOG.finest(() -> "++enter++ " + callerClassName); - if (properties == null || properties.isEmpty()) { - return url; - } - StringBuilder urlBuilder = new StringBuilder(url); - for (Entry entry : properties.entrySet()) { - Object rawKey = entry.getKey(); - Object rawValue = entry.getValue(); - if (rawKey != null && rawValue != null) { - String key = String.valueOf(rawKey); - String valueStr = String.valueOf(rawValue); - if (!valueStr.isEmpty()) { - LOG.finest( - () -> - String.format( - "Appending %s with value %s to URL", - BigQueryConnection.sanitizeForLog(key), - BigQueryConnection.maskPropertyValue(key, valueStr))); - String encodedValue = - UrlEscapers.urlFormParameterEscaper().escape(valueStr).replace("+", "%20"); - urlBuilder.append(";").append(key).append("=").append(encodedValue); - } - } - } - return urlBuilder.toString(); - } - static boolean convertToBoolean(String value, String propertyName) { int integerValue; @@ -983,15 +1137,26 @@ static Map parsePropertiesMapFromValue( LOG.fine("Unable to parse property name: %s from context: %s", propertyName, context); return null; } - Map propertiesMap = new HashMap<>(); + Map propertiesMap = new LinkedHashMap<>(); for (String keyValuePair : Splitter.on(",").split(propertiesString)) { - List parts = Splitter.on("=").limit(2).splitToList(keyValuePair); - if (parts.size() == 2) { - propertiesMap.put(parts.get(0), parts.get(1)); + List keyValueParts = Splitter.on("=").limit(2).splitToList(keyValuePair); + if (keyValueParts.size() == 2) { + String entryKey = keyValueParts.get(0).trim(); + if (entryKey.isEmpty()) { + throw new BigQueryJdbcRuntimeException( + String.format("Invalid empty key in %s.", propertyName)); + } + if (propertiesMap.containsKey(entryKey)) { + throw new BigQueryJdbcRuntimeException( + String.format( + "Duplicate key '%s' in %s.", + BigQueryConnection.sanitizeForLog(entryKey), propertyName)); + } + propertiesMap.put(entryKey, keyValueParts.get(1)); } else { LOG.warning( "Invalid KeyValue pair: %s found in context: %s for property name: %s", - keyValuePair, context, propertyName); + BigQueryConnection.sanitizeForLog(keyValuePair), context, propertyName); } } return propertiesMap; 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..04a8da4cc0ae 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 @@ -19,16 +19,14 @@ import com.google.cloud.bigquery.exception.BigQueryJdbcException; import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException; import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryPropertyUtility; -import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import io.opentelemetry.api.OpenTelemetry; import java.io.PrintWriter; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.SQLException; +import java.util.LinkedHashMap; import java.util.Map; -import java.util.Properties; import java.util.function.BiConsumer; import java.util.logging.Logger; import java.util.regex.Matcher; @@ -124,12 +122,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 +250,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 +405,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,315 +460,583 @@ 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:'."); } - Properties props = createProperties(); - if (this.customOpenTelemetry != null) { - props.put("customOpenTelemetry", this.customOpenTelemetry); - } - return DriverManager.getConnection(getURL(), props); + 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; } - Properties createProperties() { - Properties connectionProperties = new Properties(); - if (this.projectId != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.PROJECT_ID_PROPERTY_NAME, this.projectId); + /** 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 (this.defaultDataset != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.DEFAULT_DATASET_PROPERTY_NAME, this.defaultDataset); + if (isConfigured(this.defaultDataset)) { + targetDataSource.defaultDataset = this.defaultDataset; } - if (this.location != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.LOCATION_PROPERTY_NAME, this.location); + if (isConfigured(this.location)) { + targetDataSource.location = this.location; } - if (this.enableHighThroughputAPI != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_HTAPI_PROPERTY_NAME, - String.valueOf(this.enableHighThroughputAPI)); + if (isConfigured(this.userAgent)) { + targetDataSource.userAgent = this.userAgent; } - if (this.unsupportedHTAPIFallback != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.UNSUPPORTED_HTAPI_FALLBACK_PROPERTY_NAME, - String.valueOf(this.unsupportedHTAPIFallback)); + if (this.enableHighThroughputAPI != null) { + targetDataSource.enableHighThroughputAPI = this.enableHighThroughputAPI; } if (this.highThroughputMinTableSize != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.HTAPI_MIN_TABLE_SIZE_PROPERTY_NAME, - String.valueOf(this.highThroughputMinTableSize)); + targetDataSource.highThroughputMinTableSize = this.highThroughputMinTableSize; } if (this.highThroughputActivationRatio != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.HTAPI_ACTIVATION_RATIO_PROPERTY_NAME, - String.valueOf(this.highThroughputActivationRatio)); + targetDataSource.highThroughputActivationRatio = this.highThroughputActivationRatio; } - if (this.kmsKeyName != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.KMS_KEY_NAME_PROPERTY_NAME, this.kmsKeyName); + if (this.unsupportedHTAPIFallback != null) { + targetDataSource.unsupportedHTAPIFallback = this.unsupportedHTAPIFallback; + } + if (isConfigured(this.kmsKeyName)) { + targetDataSource.kmsKeyName = this.kmsKeyName; } if (this.queryProperties != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.QUERY_PROPERTIES_NAME, serializeMap(this.queryProperties)); + targetDataSource.queryProperties = this.queryProperties; + } + if (isConfigured(this.logLevel)) { + targetDataSource.logLevel = this.logLevel; } if (this.enableSession != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_SESSION_PROPERTY_NAME, String.valueOf(this.enableSession)); + targetDataSource.enableSession = this.enableSession; } if (this.enableTimestampPicos != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_TIMESTAMP_PICOS_PROPERTY_NAME, - String.valueOf(this.enableTimestampPicos)); + targetDataSource.enableTimestampPicos = this.enableTimestampPicos; } - if (this.logLevel != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.LOG_LEVEL_PROPERTY_NAME, this.logLevel); + if (isConfigured(this.logPath)) { + targetDataSource.logPath = this.logPath; } - if (this.logPath != null) { - connectionProperties.setProperty(BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME, this.logPath); + if (isConfigured(this.gcpTelemetryProjectId)) { + targetDataSource.gcpTelemetryProjectId = this.gcpTelemetryProjectId; + } + if (isConfigured(this.gcpTelemetryCredentials)) { + targetDataSource.gcpTelemetryCredentials = this.gcpTelemetryCredentials; } if (this.oAuthType != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_TYPE_PROPERTY_NAME, String.valueOf(this.oAuthType)); + targetDataSource.oAuthType = this.oAuthType; } - if (this.oAuthServiceAcctEmail != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_SA_EMAIL_PROPERTY_NAME, this.oAuthServiceAcctEmail); + if (isConfigured(this.oAuthServiceAcctEmail)) { + targetDataSource.oAuthServiceAcctEmail = this.oAuthServiceAcctEmail; } - if (this.oAuthPvtKeyPath != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PATH_PROPERTY_NAME, this.oAuthPvtKeyPath); + if (isConfigured(this.oAuthPvtKeyPath)) { + targetDataSource.oAuthPvtKeyPath = this.oAuthPvtKeyPath; } - if (this.oAuthPvtKey != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PROPERTY_NAME, this.oAuthPvtKey); + if (isConfigured(this.oAuthPvtKey)) { + targetDataSource.oAuthPvtKey = this.oAuthPvtKey; } - if (this.oAuthAccessToken != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_ACCESS_TOKEN_PROPERTY_NAME, this.oAuthAccessToken); + if (isConfigured(this.oAuthAccessToken)) { + targetDataSource.oAuthAccessToken = this.oAuthAccessToken; } if (this.oAuthAccessTokenReadonly != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_ACCESS_TOKEN_READONLY_PROPERTY_NAME, - String.valueOf(this.oAuthAccessTokenReadonly)); + targetDataSource.oAuthAccessTokenReadonly = this.oAuthAccessTokenReadonly; } - if (this.oAuthRefreshToken != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_REFRESH_TOKEN_PROPERTY_NAME, this.oAuthRefreshToken); + if (isConfigured(this.oAuthRefreshToken)) { + targetDataSource.oAuthRefreshToken = this.oAuthRefreshToken; } if (this.useQueryCache != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.USE_QUERY_CACHE_PROPERTY_NAME, String.valueOf(this.useQueryCache)); + targetDataSource.useQueryCache = this.useQueryCache; } - if (this.queryDialect != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.QUERY_DIALECT_PROPERTY_NAME, this.queryDialect); + if (isConfigured(this.queryDialect)) { + targetDataSource.queryDialect = this.queryDialect; } if (this.allowLargeResults != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ALLOW_LARGE_RESULTS_PROPERTY_NAME, - String.valueOf(this.allowLargeResults)); + targetDataSource.allowLargeResults = this.allowLargeResults; } - if (this.destinationTable != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.LARGE_RESULTS_TABLE_PROPERTY_NAME, this.destinationTable); + if (isConfigured(this.destinationTable)) { + targetDataSource.destinationTable = this.destinationTable; } - if (this.destinationDataset != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.LARGE_RESULTS_DATASET_PROPERTY_NAME, this.destinationDataset); + if (isConfigured(this.destinationDataset)) { + targetDataSource.destinationDataset = this.destinationDataset; } if (this.destinationDatasetExpirationTime != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.DESTINATION_DATASET_EXPIRATION_TIME_PROPERTY_NAME, - String.valueOf(this.destinationDatasetExpirationTime)); + targetDataSource.destinationDatasetExpirationTime = this.destinationDatasetExpirationTime; } - if (this.universeDomain != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME, this.universeDomain); + if (isConfigured(this.universeDomain)) { + targetDataSource.universeDomain = this.universeDomain; } - if (this.proxyHost != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME, this.proxyHost); + if (isConfigured(this.proxyHost)) { + targetDataSource.proxyHost = this.proxyHost; } - if (this.proxyPort != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME, this.proxyPort); + if (isConfigured(this.proxyPort)) { + targetDataSource.proxyPort = this.proxyPort; } - if (this.proxyUid != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME, this.proxyUid); + if (isConfigured(this.proxyUid)) { + targetDataSource.proxyUid = this.proxyUid; } - if (this.proxyPwd != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME, this.proxyPwd); + if (isConfigured(this.proxyPwd)) { + targetDataSource.proxyPwd = this.proxyPwd; } - if (this.oAuthClientId != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_CLIENT_ID_PROPERTY_NAME, this.oAuthClientId); + if (isConfigured(this.oAuthClientId)) { + targetDataSource.oAuthClientId = this.oAuthClientId; } - if (this.oAuthClientSecret != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_CLIENT_SECRET_PROPERTY_NAME, this.oAuthClientSecret); + if (isConfigured(this.oAuthClientSecret)) { + targetDataSource.oAuthClientSecret = this.oAuthClientSecret; } if (this.jobCreationMode != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.JOB_CREATION_MODE_PROPERTY_NAME, - String.valueOf(this.jobCreationMode)); + targetDataSource.jobCreationMode = this.jobCreationMode; } if (this.maxResults != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.MAX_RESULTS_PROPERTY_NAME, String.valueOf(this.maxResults)); + targetDataSource.maxResults = this.maxResults; } if (this.partnerToken != null && !this.partnerToken.isEmpty()) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.PARTNER_TOKEN_PROPERTY_NAME, this.partnerToken); + targetDataSource.partnerToken = + BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue(this.partnerToken); } if (this.enableWriteAPI != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_WRITE_API_PROPERTY_NAME, - String.valueOf(this.enableWriteAPI)); + targetDataSource.enableWriteAPI = this.enableWriteAPI; } - if (this.additionalProjects != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ADDITIONAL_PROJECTS_PROPERTY_NAME, this.additionalProjects); + if (isConfigured(this.additionalProjects)) { + targetDataSource.additionalProjects = this.additionalProjects; } if (this.filterTablesOnDefaultDataset != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.FILTER_TABLES_ON_DEFAULT_DATASET_PROPERTY_NAME, - String.valueOf(this.filterTablesOnDefaultDataset)); + targetDataSource.filterTablesOnDefaultDataset = this.filterTablesOnDefaultDataset; } if (this.enableProjectDiscovery != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_PROJECT_DISCOVERY_PROPERTY_NAME, - String.valueOf(this.enableProjectDiscovery)); + targetDataSource.enableProjectDiscovery = this.enableProjectDiscovery; } if (this.requestGoogleDriveScope != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.REQUEST_GOOGLE_DRIVE_SCOPE_PROPERTY_NAME, - String.valueOf(this.requestGoogleDriveScope)); + targetDataSource.requestGoogleDriveScope = this.requestGoogleDriveScope; } if (this.metadataFetchThreadCount != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.METADATA_FETCH_THREAD_COUNT_PROPERTY_NAME, - String.valueOf(this.metadataFetchThreadCount)); + targetDataSource.metadataFetchThreadCount = this.metadataFetchThreadCount; } - - if (this.sslTrustStorePath != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PROPERTY_NAME, - String.valueOf(this.sslTrustStorePath)); + if (isConfigured(this.sslTrustStorePath)) { + targetDataSource.sslTrustStorePath = this.sslTrustStorePath; } - if (this.sslTrustStorePassword != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PWD_PROPERTY_NAME, - String.valueOf(this.sslTrustStorePassword)); + if (isConfigured(this.sslTrustStorePassword)) { + targetDataSource.sslTrustStorePassword = this.sslTrustStorePassword; } - if (this.sslTrustStoreType != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.SSL_TRUST_STORE_TYPE_PROPERTY_NAME, this.sslTrustStoreType); + if (isConfigured(this.sslTrustStoreType)) { + targetDataSource.sslTrustStoreType = this.sslTrustStoreType; } - if (this.sslTrustStoreProvider != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PROVIDER_PROPERTY_NAME, - this.sslTrustStoreProvider); + if (isConfigured(this.sslTrustStoreProvider)) { + targetDataSource.sslTrustStoreProvider = this.sslTrustStoreProvider; } if (this.labels != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.LABELS_PROPERTY_NAME, serializeMap(this.labels)); + targetDataSource.labels = this.labels; } - if (this.requestReason != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.REQUEST_REASON_PROPERTY_NAME, this.requestReason); + if (isConfigured(this.requestReason)) { + targetDataSource.requestReason = this.requestReason; } if (this.timeout != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.RETRY_TIMEOUT_IN_SECS_PROPERTY_NAME, String.valueOf(this.timeout)); + targetDataSource.timeout = this.timeout; } if (this.jobTimeout != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.JOB_TIMEOUT_PROPERTY_NAME, String.valueOf(this.jobTimeout)); + targetDataSource.jobTimeout = this.jobTimeout; } if (this.retryInitialDelay != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.RETRY_INITIAL_DELAY_PROPERTY_NAME, - String.valueOf(this.retryInitialDelay)); + targetDataSource.retryInitialDelay = this.retryInitialDelay; } if (this.retryMaxDelay != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.RETRY_MAX_DELAY_PROPERTY_NAME, String.valueOf(this.retryMaxDelay)); + targetDataSource.retryMaxDelay = this.retryMaxDelay; } if (this.httpConnectTimeout != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.HTTP_CONNECT_TIMEOUT_PROPERTY_NAME, - String.valueOf(this.httpConnectTimeout)); + targetDataSource.httpConnectTimeout = this.httpConnectTimeout; } if (this.httpReadTimeout != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.HTTP_READ_TIMEOUT_PROPERTY_NAME, - String.valueOf(this.httpReadTimeout)); + targetDataSource.httpReadTimeout = this.httpReadTimeout; } if (this.maximumBytesBilled != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.MAX_BYTES_BILLED_PROPERTY_NAME, - String.valueOf(this.maximumBytesBilled)); + targetDataSource.maximumBytesBilled = this.maximumBytesBilled; } if (this.swaActivationRowCount != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.SWA_ACTIVATION_ROW_COUNT_PROPERTY_NAME, - String.valueOf(this.swaActivationRowCount)); + targetDataSource.swaActivationRowCount = this.swaActivationRowCount; } if (this.swaAppendRowCount != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.SWA_APPEND_ROW_COUNT_PROPERTY_NAME, - String.valueOf(this.swaAppendRowCount)); + 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) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.CONNECTION_POOL_SIZE_PROPERTY_NAME, - String.valueOf(this.connectionPoolSize)); + targetDataSource.connectionPoolSize = this.connectionPoolSize; } if (this.listenerPoolSize != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.LISTENER_POOL_SIZE_PROPERTY_NAME, - String.valueOf(this.listenerPoolSize)); + targetDataSource.listenerPoolSize = this.listenerPoolSize; + } + if (this.enableGcpTraceExporter != null) { + targetDataSource.enableGcpTraceExporter = this.enableGcpTraceExporter; } - if (this.enableGcpTraceExporter) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_GCP_TRACE_EXPORTER_PROPERTY_NAME, - String.valueOf(this.enableGcpTraceExporter)); + if (this.enableGcpLogExporter != null) { + targetDataSource.enableGcpLogExporter = this.enableGcpLogExporter; } - if (this.enableGcpLogExporter) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME, - String.valueOf(this.enableGcpLogExporter)); + if (this.customOpenTelemetry != null) { + targetDataSource.customOpenTelemetry = this.customOpenTelemetry; + } + if (this.useGlobalOpenTelemetry != null) { + targetDataSource.useGlobalOpenTelemetry = this.useGlobalOpenTelemetry; } - if (this.useGlobalOpenTelemetry) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.USE_GLOBAL_OTEL_PROPERTY_NAME, - String.valueOf(this.useGlobalOpenTelemetry)); + if (this.enableDiagnosticTelemetry != null) { + targetDataSource.enableDiagnosticTelemetry = this.enableDiagnosticTelemetry; } if (this.enableGraphMetadata != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_GRAPH_METADATA_PROPERTY_NAME, - String.valueOf(this.enableGraphMetadata)); + targetDataSource.enableGraphMetadata = this.enableGraphMetadata; } - connectionProperties.setProperty( + } + + /** + * Returns a sanitized, masked view of all explicitly configured properties for {@code + * Level.CONFIG} diagnostic logging, applying {@link BigQueryConnection#maskPropertyValue(String, + * Object)} to every entry without flattening maps into URL syntax. + */ + Map toMaskedLogMap() { + Map maskedProperties = new LinkedHashMap<>(); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.PROJECT_ID_PROPERTY_NAME, this.projectId); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.DEFAULT_DATASET_PROPERTY_NAME, + this.defaultDataset); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.LOCATION_PROPERTY_NAME, this.location); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.ENABLE_HTAPI_PROPERTY_NAME, + this.enableHighThroughputAPI); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.UNSUPPORTED_HTAPI_FALLBACK_PROPERTY_NAME, + this.unsupportedHTAPIFallback); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.HTAPI_MIN_TABLE_SIZE_PROPERTY_NAME, + this.highThroughputMinTableSize); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.HTAPI_ACTIVATION_RATIO_PROPERTY_NAME, + this.highThroughputActivationRatio); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.KMS_KEY_NAME_PROPERTY_NAME, this.kmsKeyName); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.QUERY_PROPERTIES_NAME, this.queryProperties); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.ENABLE_SESSION_PROPERTY_NAME, this.enableSession); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.ENABLE_TIMESTAMP_PICOS_PROPERTY_NAME, + this.enableTimestampPicos); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.LOG_LEVEL_PROPERTY_NAME, this.logLevel); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME, this.logPath); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.GCP_TELEMETRY_PROJECT_ID_PROPERTY_NAME, + this.gcpTelemetryProjectId); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.GCP_TELEMETRY_CREDENTIALS_PROPERTY_NAME, + this.gcpTelemetryCredentials); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.OAUTH_TYPE_PROPERTY_NAME, this.oAuthType); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.OAUTH_SA_EMAIL_PROPERTY_NAME, + this.oAuthServiceAcctEmail); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PATH_PROPERTY_NAME, + this.oAuthPvtKeyPath); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PROPERTY_NAME, this.oAuthPvtKey); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.OAUTH_ACCESS_TOKEN_PROPERTY_NAME, + this.oAuthAccessToken); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.OAUTH_ACCESS_TOKEN_READONLY_PROPERTY_NAME, + this.oAuthAccessTokenReadonly); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.OAUTH_REFRESH_TOKEN_PROPERTY_NAME, + this.oAuthRefreshToken); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.USE_QUERY_CACHE_PROPERTY_NAME, this.useQueryCache); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.QUERY_DIALECT_PROPERTY_NAME, this.queryDialect); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.ALLOW_LARGE_RESULTS_PROPERTY_NAME, + this.allowLargeResults); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.LARGE_RESULTS_TABLE_PROPERTY_NAME, + this.destinationTable); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.LARGE_RESULTS_DATASET_PROPERTY_NAME, + this.destinationDataset); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.DESTINATION_DATASET_EXPIRATION_TIME_PROPERTY_NAME, + this.destinationDatasetExpirationTime); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME, + this.universeDomain); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME, this.proxyHost); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME, this.proxyPort); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME, this.proxyUid); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME, this.proxyPwd); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.OAUTH_CLIENT_ID_PROPERTY_NAME, this.oAuthClientId); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.OAUTH_CLIENT_SECRET_PROPERTY_NAME, + this.oAuthClientSecret); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.JOB_CREATION_MODE_PROPERTY_NAME, + this.jobCreationMode); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.MAX_RESULTS_PROPERTY_NAME, this.maxResults); + if (this.partnerToken != null && !this.partnerToken.isEmpty()) { + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.PARTNER_TOKEN_PROPERTY_NAME, this.partnerToken); + } + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.ENABLE_WRITE_API_PROPERTY_NAME, + this.enableWriteAPI); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.ADDITIONAL_PROJECTS_PROPERTY_NAME, + this.additionalProjects); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.FILTER_TABLES_ON_DEFAULT_DATASET_PROPERTY_NAME, + this.filterTablesOnDefaultDataset); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.ENABLE_PROJECT_DISCOVERY_PROPERTY_NAME, + this.enableProjectDiscovery); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.REQUEST_GOOGLE_DRIVE_SCOPE_PROPERTY_NAME, + this.requestGoogleDriveScope); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.METADATA_FETCH_THREAD_COUNT_PROPERTY_NAME, + this.metadataFetchThreadCount); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PROPERTY_NAME, + this.sslTrustStorePath); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PWD_PROPERTY_NAME, + this.sslTrustStorePassword); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.SSL_TRUST_STORE_TYPE_PROPERTY_NAME, + this.sslTrustStoreType); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PROVIDER_PROPERTY_NAME, + this.sslTrustStoreProvider); + putMaskedProperty(maskedProperties, BigQueryJdbcUrlUtility.LABELS_PROPERTY_NAME, this.labels); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.REQUEST_REASON_PROPERTY_NAME, this.requestReason); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.RETRY_TIMEOUT_IN_SECS_PROPERTY_NAME, this.timeout); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.JOB_TIMEOUT_PROPERTY_NAME, this.jobTimeout); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.RETRY_INITIAL_DELAY_PROPERTY_NAME, + this.retryInitialDelay); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.RETRY_MAX_DELAY_PROPERTY_NAME, this.retryMaxDelay); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.HTTP_CONNECT_TIMEOUT_PROPERTY_NAME, + this.httpConnectTimeout); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.HTTP_READ_TIMEOUT_PROPERTY_NAME, + this.httpReadTimeout); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.MAX_BYTES_BILLED_PROPERTY_NAME, + this.maximumBytesBilled); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.SWA_ACTIVATION_ROW_COUNT_PROPERTY_NAME, + this.swaActivationRowCount); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.SWA_APPEND_ROW_COUNT_PROPERTY_NAME, + this.swaAppendRowCount); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.OAUTH_P12_PASSWORD_PROPERTY_NAME, + this.oAuthP12Password); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_EMAIL_PROPERTY_NAME, + this.oAuthSAImpersonationEmail); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_CHAIN_PROPERTY_NAME, + this.oAuthSAImpersonationChain); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_SCOPES_PROPERTY_NAME, + this.oAuthSAImpersonationScopes); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_TOKEN_LIFETIME_PROPERTY_NAME, + this.oAuthSAImpersonationTokenLifetime); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME, + this.oAuth2TokenUri); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.BYOID_AUDIENCE_URI_PROPERTY_NAME, + this.byoidAudienceUri); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME, + this.byoidCredentialSource); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.BYOID_POOL_USER_PROJECT_PROPERTY_NAME, + this.byoidPoolUserProject); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.BYOID_SA_IMPERSONATION_URI_PROPERTY_NAME, + this.byoidSAImpersonationUri); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.BYOID_SUBJECT_TOKEN_TYPE_PROPERTY_NAME, + this.byoidSubjectTokenType); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.BYOID_TOKEN_URI_PROPERTY_NAME, this.byoidTokenUri); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.ENDPOINT_OVERRIDES_PROPERTY_NAME, + this.endpointOverrides); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.PRIVATE_SERVICE_CONNECT_PROPERTY_NAME, + this.privateServiceConnect); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.CONNECTION_POOL_SIZE_PROPERTY_NAME, + this.connectionPoolSize); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.LISTENER_POOL_SIZE_PROPERTY_NAME, + this.listenerPoolSize); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.ENABLE_GCP_TRACE_EXPORTER_PROPERTY_NAME, + this.enableGcpTraceExporter); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME, + this.enableGcpLogExporter); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.USE_GLOBAL_OTEL_PROPERTY_NAME, + this.useGlobalOpenTelemetry); + putMaskedProperty( + maskedProperties, + BigQueryJdbcUrlUtility.ENABLE_GRAPH_METADATA_PROPERTY_NAME, + this.enableGraphMetadata); + putMaskedProperty( + maskedProperties, BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, - String.valueOf(getEnableDiagnosticTelemetry())); - return connectionProperties; + this.enableDiagnosticTelemetry); + return maskedProperties; } - private String serializeMap(Map map) { - if (map == null || map.isEmpty()) { - return ""; + private static void putMaskedProperty( + Map maskedProperties, String propertyName, Object propertyValue) { + if (propertyValue != null) { + maskedProperties.put( + BigQueryConnection.sanitizeForLog(propertyName), + BigQueryConnection.maskPropertyValue(propertyName, propertyValue)); } - return Joiner.on(",").withKeyValueSeparator("=").join(map); } @Override @@ -887,7 +1163,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 +1173,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 +1199,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 +1919,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/BigQueryConnectionTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java index 1fe40c127d60..4e83e77783c4 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 @@ -2087,4 +2087,86 @@ public void testConcurrentGetWarningsAndReset_neverThrowsIndexOutOfBounds() thro } } } + + @Test + public void testDatabaseMetaDataGetUrl_omitsSecretsAcrossAllEntryPoints() throws SQLException { + // 1. Driver.connect with clean URL + out-of-band Properties secrets + String cleanConnectionUrl = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;ProjectId=proj-meta"; + Properties credentialProperties = new Properties(); + credentialProperties.setProperty("OAuthType", "2"); + credentialProperties.setProperty("OAuthAccessToken", "live_oob_access_token"); + credentialProperties.setProperty("ProxyHost", "proxy.internal"); + credentialProperties.setProperty("ProxyPort", "8080"); + credentialProperties.setProperty("ProxyUid", "live_proxy_user"); + credentialProperties.setProperty("ProxyPwd", "live_proxy_pwd"); + try (Connection connection = + BigQueryDriver.getRegisteredDriver().connect(cleanConnectionUrl, credentialProperties)) { + String metadataUrl = connection.getMetaData().getURL(); + assertEquals("jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443", metadataUrl); + assertFalse(metadataUrl.contains("OAuthAccessToken")); + assertFalse(metadataUrl.contains("live_oob_access_token")); + assertFalse(metadataUrl.contains("ProxyPwd")); + assertFalse(metadataUrl.contains("live_proxy_pwd")); + } + + // 2. DataSource.getConnection with inline URL secret + setter secret + DataSource dataSource = new DataSource(); + dataSource.setURL( + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=proj-ds;OAuthType=2;OAuthAccessToken=inline_ds_secret"); + dataSource.setSSLTrustStorePassword("setter_ts_secret"); + try (Connection connection = dataSource.getConnection()) { + String metadataUrl = connection.getMetaData().getURL(); + assertEquals("jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443", metadataUrl); + assertFalse(metadataUrl.contains("inline_ds_secret")); + assertFalse(metadataUrl.contains("setter_ts_secret")); + assertFalse(metadataUrl.contains("OAuthAccessToken")); + assertFalse(metadataUrl.contains("SSLTrustStorePwd")); + } + + // 3. Direct package-private BigQueryConnection(url) constructor also omits inline secrets + String directConnectionUrl = + "bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=proj-direct;OAuthType=2;OAuthAccessToken=direct_inline_secret"; + try (BigQueryConnection connection = new BigQueryConnection(directConnectionUrl)) { + String metadataUrl = connection.getMetaData().getURL(); + assertEquals("jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443", metadataUrl); + assertFalse(metadataUrl.contains("direct_inline_secret")); + assertFalse(metadataUrl.contains("OAuthAccessToken")); + } + } + + @Test + public void testDataSourceToMaskedLogMap_includesSafeSecurityFieldsAndMasksSecrets() { + DataSource dataSource = new DataSource(); + dataSource.setOAuthSAImpersonationEmail("impersonated@proj.iam.gserviceaccount.com"); + dataSource.setPrivateServiceConnect("BIGQUERY=https://psc.internal"); + dataSource.setGcpTelemetryProjectId("telemetry-proj"); + dataSource.setGcpTelemetryCredentials("raw-telemetry-secret"); + dataSource.setOAuthP12Password("raw-p12-secret"); + dataSource.setOAuth2TokenUri("https://oauth2.internal/token"); + dataSource.setByoidCredentialSource("{\"headers\":{\"Authorization\":\"Bearer secret\"}}"); + + Map maskedProperties = dataSource.toMaskedLogMap(); + assertEquals( + "impersonated@proj.iam.gserviceaccount.com", + maskedProperties.get(BigQueryJdbcUrlUtility.OAUTH_SA_IMPERSONATION_EMAIL_PROPERTY_NAME)); + assertEquals( + "BIGQUERY=https://psc.internal", + maskedProperties.get(BigQueryJdbcUrlUtility.PRIVATE_SERVICE_CONNECT_PROPERTY_NAME)); + assertEquals( + "telemetry-proj", + maskedProperties.get(BigQueryJdbcUrlUtility.GCP_TELEMETRY_PROJECT_ID_PROPERTY_NAME)); + assertEquals( + "*****", + maskedProperties.get(BigQueryJdbcUrlUtility.GCP_TELEMETRY_CREDENTIALS_PROPERTY_NAME)); + assertEquals( + "*****", maskedProperties.get(BigQueryJdbcUrlUtility.OAUTH_P12_PASSWORD_PROPERTY_NAME)); + assertEquals( + "*****", maskedProperties.get(BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME)); + assertEquals( + "*****", + maskedProperties.get(BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME)); + } } 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..ccfbbd070888 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 @@ -96,7 +96,7 @@ public void testValidURLInAcceptsURLReturnsTrue() throws SQLException { } @Test - public void testGetPropertyInfoReturnsValidProperties() { + public void testGetPropertyInfoReturnsValidProperties() throws SQLException { DriverPropertyInfo[] res = bigQueryDriver.getPropertyInfo( "jdbc:bigquery:https://google.com:8080;projectId=123456;OAuthType=3", new Properties()); @@ -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,262 @@ 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)); + } + + @Test + public void testGetPropertyInfo_returnsNullForSecretsAndHandlesInvalidUrls() throws SQLException { + String connectionUrl = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=visible-proj;OAuthType=2;Location=US"; + Properties credentialProperties = new Properties(); + credentialProperties.setProperty("OAuthAccessToken", "live_access_secret"); + credentialProperties.setProperty("SSLTrustStorePwd", "live_ts_secret"); + credentialProperties.setProperty("gcpTelemetryCredentials", "live_otel_secret"); + credentialProperties.setProperty( + "BYOID_CredentialSource", "{\"headers\":{\"Authorization\":\"Bearer live\"}}"); + + DriverPropertyInfo[] propertyInfos = + bigQueryDriver.getPropertyInfo(connectionUrl, credentialProperties); + String projectIdValue = null; + for (DriverPropertyInfo propertyInfo : propertyInfos) { + if ("ProjectId".equals(propertyInfo.name)) { + projectIdValue = propertyInfo.value; + } + if (!BigQueryConnection.isSafeToLogProperty(propertyInfo.name)) { + assertThat(propertyInfo.value).isNull(); + } + if (propertyInfo.value != null) { + assertThat(propertyInfo.value).doesNotContain("live_"); + assertThat(propertyInfo.value).doesNotContain("Bearer live"); + } + } + assertThat(projectIdValue).isEqualTo("visible-proj"); + + // Service Account (OAuthType=0) and Refresh Token (OAuthType=2) secrets also return null. + Properties serviceAccountProperties = new Properties(); + serviceAccountProperties.setProperty("OAuthType", "0"); + serviceAccountProperties.setProperty( + "OAuthServiceAcctEmail", "sa@proj.iam.gserviceaccount.com"); + serviceAccountProperties.setProperty("OAuthPvtKey", "live_private_key_pem"); + serviceAccountProperties.setProperty("OAuthP12Password", "live_p12_secret"); + for (DriverPropertyInfo propertyInfo : + bigQueryDriver.getPropertyInfo( + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;ProjectId=p", + serviceAccountProperties)) { + if (!BigQueryConnection.isSafeToLogProperty(propertyInfo.name)) { + assertThat(propertyInfo.value).isNull(); + } + } + + // Null, short, or non-jdbc:bigquery URLs must not throw NPE/SIOOBE. + assertThat(bigQueryDriver.getPropertyInfo(null, credentialProperties)).isEmpty(); + assertThat(bigQueryDriver.getPropertyInfo("bad", credentialProperties)).isEmpty(); + assertThat(bigQueryDriver.getPropertyInfo("jdbc:other://host", credentialProperties)).isEmpty(); + + // Key injection in getPropertyInfo Properties is ignored rather than applied. + Properties injectedKeyProperties = new Properties(); + injectedKeyProperties.setProperty( + "custom=1;EndpointOverrides", "BIGQUERY=https://127.0.0.1:8443"); + for (DriverPropertyInfo propertyInfo : + bigQueryDriver.getPropertyInfo(connectionUrl, injectedKeyProperties)) { + if (BigQueryJdbcUrlUtility.ENDPOINT_OVERRIDES_PROPERTY_NAME.equals(propertyInfo.name)) { + assertThat(propertyInfo.value).isNull(); + } + } + } + + @Test + public void testGetPropertyInfo_reportsTelemetryOptOutFromAnySource() throws SQLException { + String urlWithTelemetryOptOut = VALID_TOKEN_URL + "EnableDiagnosticTelemetry=0;"; + Properties telemetryOptInProperties = new Properties(); + telemetryOptInProperties.setProperty("EnableDiagnosticTelemetry", "1"); + boolean telemetryPropertyReported = false; + for (DriverPropertyInfo propertyInfo : + bigQueryDriver.getPropertyInfo(urlWithTelemetryOptOut, telemetryOptInProperties)) { + if (BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME.equals( + propertyInfo.name)) { + telemetryPropertyReported = true; + assertThat(propertyInfo.value).isEqualTo("false"); + } + } + assertThat(telemetryPropertyReported).isTrue(); + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java index 1ccbe13bbe4d..2d4da3436859 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtilityTest.java @@ -27,9 +27,12 @@ import com.google.cloud.bigquery.DatasetId; import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException; import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryPropertyUtility; +import com.google.common.collect.ImmutableSet; +import java.lang.reflect.Field; import java.util.Collections; import java.util.Map; import java.util.Properties; +import java.util.Set; import java.util.logging.LogRecord; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -104,16 +107,14 @@ public void testParsePropertyWithValueCaseInsensitive() { } @Test - public void testAppendPropertiesToURL() { - String url = - "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" - + "ProjectId=MyBigQueryProject;" - + "OAuthAccessToken=RedactedToken"; - Properties properties = new Properties(); - properties.setProperty("OAuthType", "3"); - - String updatedUrl = BigQueryJdbcUrlUtility.appendPropertiesToURL(url, null, properties); - assertThat(updatedUrl.contains("OAuthType=3")); + public void + testValidateAndCanonicalizeProperties_preservesDiscretePropertiesWithoutUrlMutation() { + Properties callerProperties = new Properties(); + callerProperties.setProperty("OAuthType", "3"); + + BigQueryDriver.ValidatedConnectionProperties validatedProperties = + BigQueryDriver.validateAndCanonicalizeProperties(callerProperties); + assertThat(validatedProperties.canonicalProperties.get("OAuthType")).isEqualTo("3"); } @Test @@ -202,18 +203,18 @@ public void testParsePartnerTokenProperty() { } @Test - public void testAppendPropertiesToURL_propertyWithSemicolon_isEscaped() throws Exception { - String url = "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;"; - Properties properties = new Properties(); - String complexValue = "value;ExtraProperty=injection"; - properties.setProperty("ProjectId", complexValue); - - String updatedUrl = BigQueryJdbcUrlUtility.appendPropertiesToURL(url, null, properties); - - Map parsedProperties = BigQueryJdbcUrlUtility.parseUrl(updatedUrl); - - assertThat(parsedProperties.get("ProjectId")).isEqualTo(complexValue); - assertFalse(parsedProperties.containsKey("ExtraProperty")); + public void + testValidateAndCanonicalizeProperties_propertyWithSemicolon_doesNotInjectSiblingProperty() { + Properties callerProperties = new Properties(); + String valueWithSemicolon = "value;ExtraProperty=injection"; + callerProperties.setProperty("ProjectId", valueWithSemicolon); + + BigQueryDriver.ValidatedConnectionProperties validatedProperties = + BigQueryDriver.validateAndCanonicalizeProperties(callerProperties); + + assertThat(validatedProperties.canonicalProperties.get("ProjectId")) + .isEqualTo(valueWithSemicolon); + assertFalse(validatedProperties.canonicalProperties.containsKey("ExtraProperty")); } @Test @@ -386,9 +387,7 @@ public void testParseDiagnosticTelemetryProperties() { DataSource ds = DataSource.fromUrl(url); assertThat(ds.getEnableDiagnosticTelemetry()).isFalse(); - - Properties props = ds.createProperties(); - assertThat(props.getProperty("EnableDiagnosticTelemetry")).isEqualTo("false"); + assertThat(ds.toMaskedLogMap().get("EnableDiagnosticTelemetry")).isEqualTo("false"); String urlWithoutTelemetry = "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;ProjectId=MyBigQueryProject"; @@ -408,9 +407,7 @@ public void testEnableGraphMetadataProperties() { DataSource ds = DataSource.fromUrl(url); assertThat(ds.getEnableGraphMetadata()).isTrue(); - - Properties props = ds.createProperties(); - assertThat(props.getProperty("EnableGraphMetadata")).isEqualTo("true"); + assertThat(ds.toMaskedLogMap().get("EnableGraphMetadata")).isEqualTo("true"); String urlWithoutGraph = "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;ProjectId=MyBigQueryProject"; @@ -434,42 +431,29 @@ public void testEnableGraphMetadataProperties() { "BYOID_CredentialSource", "CustomSecretProperty" }) - public void testAppendPropertiesToURL_masksSensitivePropertiesAtFinest(String secretKey) { - capturedLogs.clear(); - String baseUrl = "bigquery://https://www.googleapis.com/bigquery/v2:443"; - Properties props = new Properties(); + public void testMaskPropertyValue_masksSensitiveProperties(String secretKey) { String rawSecret = "super-secret-value-98765"; - props.setProperty(secretKey, rawSecret); - props.setProperty("ProjectId", "visible-project"); - - String updated = BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "TestCaller", props); - - assertThat(updated).contains(secretKey + "=" + rawSecret); - assertThat(assertLogContains("Appending " + secretKey + " with value ***** to URL")).isTrue(); - assertThat(assertLogContains("Appending ProjectId with value visible-project to URL")).isTrue(); - assertThat(assertLogContains(rawSecret)).isFalse(); + assertThat(BigQueryConnection.maskPropertyValue(secretKey, rawSecret)).isEqualTo("*****"); + assertThat(BigQueryConnection.maskPropertyValue("ProjectId", "visible-project")) + .isEqualTo("visible-project"); } @Test - public void testAppendPropertiesToURL_handlesNullAndNonStringProperties() { - String baseUrl = "bigquery://https://www.googleapis.com/bigquery/v2:443"; - assertThat(BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", null)) - .isEqualTo(baseUrl); - assertThat(BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", new Properties())) - .isEqualTo(baseUrl); - - Properties nonStringProps = new Properties(); - nonStringProps.put("MaxResults", 500); - nonStringProps.put("OAuthAccessToken", 123456); - capturedLogs.clear(); - - String updated = - BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", nonStringProps); - assertThat(updated).contains("MaxResults=500"); - assertThat(updated).contains("OAuthAccessToken=123456"); - assertThat(assertLogContains("Appending MaxResults with value 500 to URL")).isTrue(); - assertThat(assertLogContains("Appending OAuthAccessToken with value ***** to URL")).isTrue(); - assertThat(assertLogContains("123456")).isFalse(); + public void testValidateAndCanonicalizeProperties_handlesNullAndNonStringProperties() { + assertThat(BigQueryDriver.validateAndCanonicalizeProperties(null).canonicalProperties) + .isEmpty(); + assertThat( + BigQueryDriver.validateAndCanonicalizeProperties(new Properties()).canonicalProperties) + .isEmpty(); + + Properties nonStringProperties = new Properties(); + nonStringProperties.put("MaxResults", 500); + nonStringProperties.put("OAuthAccessToken", 123456); + + BigQueryDriver.ValidatedConnectionProperties validatedProperties = + BigQueryDriver.validateAndCanonicalizeProperties(nonStringProperties); + assertThat(validatedProperties.canonicalProperties.get("MaxResults")).isEqualTo("500"); + assertThat(validatedProperties.canonicalProperties.get("OAuthAccessToken")).isEqualTo("123456"); assertThat(BigQueryConnection.maskPropertyValue(null, "secret")).isEqualTo("*****"); assertThat(BigQueryConnection.maskPropertyValue("ProjectId", null)).isNull(); } @@ -477,8 +461,8 @@ public void testAppendPropertiesToURL_handlesNullAndNonStringProperties() { @Test public void testSanitizeControlCharactersAndCaseInsensitiveSafeProperties() { assertThat(BigQueryConnection.sanitizeForLog(null)).isNull(); - String clean = "my-clean-project-123"; - assertThat(BigQueryConnection.sanitizeForLog(clean)).isSameInstanceAs(clean); + String cleanValue = "my-clean-project-123"; + assertThat(BigQueryConnection.sanitizeForLog(cleanValue)).isSameInstanceAs(cleanValue); assertThat(BigQueryConnection.sanitizeForLog("proj\r\nFORGED\t\u007f")) .isEqualTo("proj??FORGED??"); @@ -488,21 +472,247 @@ public void testSanitizeControlCharactersAndCaseInsensitiveSafeProperties() { assertThat(BigQueryConnection.maskPropertyValue("oauthaccesstoken", "tok\nen")) .isEqualTo("*****"); + DataSource dataSource = new DataSource(); + dataSource.setProjectId("proj\r\nFAKE_LOG_ENTRY"); + dataSource.setOAuthAccessToken("secret-val"); + Map maskedProperties = dataSource.toMaskedLogMap(); + assertThat(maskedProperties.get("ProjectId")).isEqualTo("proj??FAKE_LOG_ENTRY"); + assertThat(maskedProperties.get("OAuthAccessToken")).isEqualTo("*****"); + for (String maskedValue : maskedProperties.values()) { + assertThat(maskedValue).doesNotContain("\n"); + assertThat(maskedValue).doesNotContain("\r"); + } + + // Control characters inside property keys are ignored (and warned about once logging is + // active). + Properties controlKeyProperties = new Properties(); + controlKeyProperties.setProperty("Custom\nKey", "secret-val"); + BigQueryDriver.ValidatedConnectionProperties validatedControlKeyProperties = + BigQueryDriver.validateAndCanonicalizeProperties(controlKeyProperties); + assertThat(validatedControlKeyProperties.canonicalProperties).isEmpty(); + assertThat(validatedControlKeyProperties.unknownPropertyKeys).isEmpty(); + assertThat(validatedControlKeyProperties.hasIgnoredInvalidPropertyKeys).isTrue(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "custom_tag=1;EndpointOverrides", + "EndpointOverrides=BIGQUERY=https://127.0.0.1:8443,DUMMY", + "ProjectId;OAuthType", + "Key\r\nInject", + "Key\tTab", + " LeadingSpace", + "TrailingSpace ", + "" + }) + public void testExtractValidPropertyKey_ignoresInvalidPropertyKeys(String invalidKey) { + assertNull(BigQueryJdbcUrlUtility.extractValidPropertyKey(invalidKey)); + Properties invalidProperties = new Properties(); + invalidProperties.setProperty(invalidKey, "val"); + BigQueryDriver.ValidatedConnectionProperties validatedProperties = + BigQueryDriver.validateAndCanonicalizeProperties(invalidProperties); + assertThat(validatedProperties.canonicalProperties).isEmpty(); + assertThat(validatedProperties.hasIgnoredInvalidPropertyKeys).isTrue(); + } + + @Test + public void testExtractValidPropertyKey_rejectsNonStringKeys() { + assertThat(BigQueryJdbcUrlUtility.extractValidPropertyKey("ProjectId")).isEqualTo("ProjectId"); + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> BigQueryJdbcUrlUtility.extractValidPropertyKey(null)); + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> BigQueryJdbcUrlUtility.extractValidPropertyKey(42)); + + Properties nonStringKeyProperties = new Properties(); + nonStringKeyProperties.put(42, "val"); + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> BigQueryDriver.validateAndCanonicalizeProperties(nonStringKeyProperties)); + } + + @Test + public void testParseUrl_noStaticParseCacheRetainingSecrets() { + for (Field field : BigQueryJdbcUrlUtility.class.getDeclaredFields()) { + assertFalse( + "PARSE_CACHE".equals(field.getName()), + "Static PARSE_CACHE must not exist because it retains secret-bearing URLs in heap."); + } + } + + @Test + public void testParseUrl_malformedSegmentDoesNotEchoRawSecretText() { + String secretFragment = "SECRET_PRIVATE_KEY_FRAGMENT_999"; + String connectionUrl = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=p;OAuthAccessToken=top_secret;" + + secretFragment; + + BigQueryJdbcRuntimeException malformedSegmentException = + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> BigQueryJdbcUrlUtility.parseUrl(connectionUrl)); + assertThat(malformedSegmentException.getMessage()).doesNotContain(secretFragment); + assertThat(malformedSegmentException.getMessage()).doesNotContain("top_secret"); + } + + @Test + public void testParsePropertiesMapFromValue_rejectsEmptyKeyAndExactDuplicateAndSanitizesLogs() { + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcUrlUtility.parsePropertiesMapFromValue( + "=orphanValue", "QueryProperties", "Test")); + + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcUrlUtility.parsePropertiesMapFromValue( + "dataset_project_id=tenant_a,dataset_project_id=tenant_b", + "QueryProperties", + "Test")); + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcUrlUtility.parsePropertiesMapFromValue( + "dataset_project_id=tenant_a, dataset_project_id=tenant_b", + "QueryProperties", + "Test")); + + // Case-variant duplicates must still pass through so BigQueryConnection can raise its + // specific case-insensitive session_id duplicate SQLException. + Map caseVariantProperties = + BigQueryJdbcUrlUtility.parsePropertiesMapFromValue( + "session_id=a,Session_Id=b", "QueryProperties", "Test"); + assertThat(caseVariantProperties).containsExactly("session_id", "a", "Session_Id", "b"); + + // Malformed pairs without '=' must sanitize CR/LF before logging a warning. capturedLogs.clear(); - String baseUrl = "bigquery://https://www.googleapis.com/bigquery/v2:443"; - Properties props = new Properties(); - props.setProperty("ProjectId", "proj\r\nFAKE_LOG_ENTRY"); - props.setProperty("Custom\nKey", "secret-val"); - - String updated = BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", props); - - assertThat(updated).contains("ProjectId=proj%0D%0AFAKE_LOG_ENTRY"); - assertThat(assertLogContains("Appending ProjectId with value proj??FAKE_LOG_ENTRY to URL")) - .isTrue(); - assertThat(assertLogContains("Appending Custom?Key with value ***** to URL")).isTrue(); - for (LogRecord rec : capturedLogs) { - assertThat(rec.getMessage()).doesNotContain("\n"); - assertThat(rec.getMessage()).doesNotContain("\r"); + Map parsedWithMalformedPair = + BigQueryJdbcUrlUtility.parsePropertiesMapFromValue( + "time_zone=UTC,bad\r\nFORGED_LOG", "QueryProperties", "Test"); + assertThat(parsedWithMalformedPair).containsExactly("time_zone", "UTC"); + assertThat(assertLogContains("bad??FORGED_LOG")).isTrue(); + for (LogRecord logRecord : capturedLogs) { + assertThat(logRecord.getMessage()).doesNotContain("\r"); + assertThat(logRecord.getMessage()).doesNotContain("\n"); + } + } + + @Test + public void testParseConnectionUrl_twoPhaseLastWinsAndInvalidPercentEncodingWithoutSecretEcho() { + String connectionUrl = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "LogLevel=7;LogPath=/tmp/first;PartnerToken=(GPN:first;a);" + + "PartnerToken=(GPN:second;b);LogLevel=3;LogPath=/tmp/second;MalformedNoEquals"; + + // Phase 1 must not throw even with a malformed segment and must apply last-wins semantics. + BigQueryJdbcUrlUtility.ParsedConnectionUrl parsedUrl = + BigQueryJdbcUrlUtility.parseConnectionUrl(connectionUrl); + assertThat(parsedUrl.getPreConnectProperty("LogLevel")).isEqualTo("3"); + assertThat(parsedUrl.getPreConnectProperty("LogPath")).isEqualTo("/tmp/second"); + assertThat(parsedUrl.getPreConnectProperty("PartnerToken")).isEqualTo(" (GPN:second;b)"); + + // Phase 2 must throw without echoing the malformed segment. + BigQueryJdbcRuntimeException malformedSegmentException = + assertThrows(BigQueryJdbcRuntimeException.class, parsedUrl::validateAndGetProperties); + assertThat(malformedSegmentException.getMessage()).doesNotContain("MalformedNoEquals"); + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcUrlUtility.parseUrl( + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443; =value")); + + // Invalid percent-escape inside a secret must not throw in Phase 1 or echo the secret in + // Phase 2. + String invalidPercentEncodingUrl = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=p;OAuthAccessToken=secret%ZZtoken"; + BigQueryJdbcUrlUtility.ParsedConnectionUrl parsedInvalidEncodingUrl = + BigQueryJdbcUrlUtility.parseConnectionUrl(invalidPercentEncodingUrl); + assertThat(parsedInvalidEncodingUrl.toSanitizedDisplayUrl()) + .isEqualTo("jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443"); + BigQueryJdbcRuntimeException invalidEncodingException = + assertThrows( + BigQueryJdbcRuntimeException.class, parsedInvalidEncodingUrl::validateAndGetProperties); + assertThat(invalidEncodingException.getMessage()).doesNotContain("secret"); + assertThat(invalidEncodingException.getMessage()).doesNotContain("%ZZ"); + } + + @Test + public void testSanitizeUrlForDisplay_returnsEndpointOnlyAndNormalizesPrefix() { + assertNull(BigQueryJdbcUrlUtility.sanitizeUrlForDisplay(null)); + assertThat(BigQueryJdbcUrlUtility.sanitizeUrlForDisplay("")).isEqualTo(""); + assertThat( + BigQueryJdbcUrlUtility.sanitizeUrlForDisplay( + "bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=p1;OAuthType=2;OAuthAccessToken=live_secret;" + + "ProxyPwd=proxy_secret;SSLTrustStorePwd=ts_secret;" + + "BYOID_CredentialSource={\"headers\":{\"Authorization\":\"Bearer x\"}};" + + "PartnerToken=(GPN:acme; prod);ProjectId=p2;UnknownCustom=hidden")) + .isEqualTo("jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443"); + assertThat( + BigQueryJdbcUrlUtility.sanitizeUrlForDisplay( + "jdbc:bigquery://h?OAuthAccessToken=x;ProjectId=p")) + .isEqualTo("jdbc:bigquery:"); + } + + @Test + public void testFormatPartnerTokenHeaderValue_doesNotDoubleDecodeAndPreservesLiteralPercent() { + assertNull(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue(null)); + assertNull(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue("(env)")); + assertNull(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue("(GPN:a\r\nX-Evil: 1)")); + assertThat(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue("(GPN:partner; prod)")) + .isEqualTo(" (GPN:partner; prod)"); + // Discrete Properties/DataSource inputs are already unencoded and must preserve literal '%xx'. + assertThat(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue("(GPN:partner%20name)")) + .isEqualTo(" (GPN:partner%20name)"); + + // URL parsing decodes percent-escapes once; re-formatting the result is idempotent. + String encodedPartnerTokenUrl = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "PartnerToken=%28GPN%3Apartner%2520name%3Bprod%29"; + String parsedPartnerToken = + BigQueryJdbcUrlUtility.parseConnectionUrl(encodedPartnerTokenUrl) + .validateAndGetProperties() + .get(BigQueryJdbcUrlUtility.PARTNER_TOKEN_PROPERTY_NAME); + assertThat(parsedPartnerToken).isEqualTo(" (GPN:partner%20name;prod)"); + assertThat(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue(parsedPartnerToken)) + .isEqualTo(" (GPN:partner%20name;prod)"); + } + + @Test + public void testSafeToLogProperties_exhaustivelyClassifiesEveryKnownProperty() { + // Explicit test-only inventory of known PROPERTY_NAME_MAP keys that must NOT be in + // SAFE_TO_LOG_PROPERTIES (sensitive credentials + internal endpoint-override sub-keys). + Set expectedNonAllowlistedProperties = + ImmutableSet.of( + BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PROPERTY_NAME, + BigQueryJdbcUrlUtility.OAUTH_ACCESS_TOKEN_PROPERTY_NAME, + BigQueryJdbcUrlUtility.OAUTH_REFRESH_TOKEN_PROPERTY_NAME, + BigQueryJdbcUrlUtility.OAUTH_CLIENT_SECRET_PROPERTY_NAME, + BigQueryJdbcUrlUtility.OAUTH_P12_PASSWORD_PROPERTY_NAME, + BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME, + BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME, + BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PWD_PROPERTY_NAME, + BigQueryJdbcUrlUtility.GCP_TELEMETRY_CREDENTIALS_PROPERTY_NAME, + BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME, + BigQueryJdbcUrlUtility.BIGQUERY_ENDPOINT_OVERRIDE_PROPERTY_NAME, + BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME, + BigQueryJdbcUrlUtility.HTAPI_ENDPOINT_OVERRIDE_PROPERTY_NAME, + BigQueryJdbcUrlUtility.STS_ENDPOINT_OVERRIDE_PROPERTY_NAME); + + for (String canonicalPropertyName : BigQueryJdbcUrlUtility.PROPERTY_NAME_MAP.values()) { + boolean isAllowlisted = BigQueryConnection.isSafeToLogProperty(canonicalPropertyName); + boolean isExpectedNonAllowlisted = + expectedNonAllowlistedProperties.contains(canonicalPropertyName); + assertFalse( + isAllowlisted == isExpectedNonAllowlisted, + "Unclassified property: " + canonicalPropertyName); } + assertFalse(BigQueryConnection.isSafeToLogProperty(null)); + assertFalse(BigQueryConnection.isSafeToLogProperty("UnknownCustomSecret")); } } 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 6cccb0e19b7f..2fc5411ea95f 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(); @@ -136,4 +155,246 @@ 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()); + } + // userAgent and customOpenTelemetry have no connection-property name, so they are not logged. + assertEquals(populatedFieldCount - 2, populatedDataSource.toMaskedLogMap().size()); + } + + @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(); + } + } }