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();
+ }
+ }
}