From a68a6b3962ca331929a8b3c915a2bb79e6a5c05d Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 30 Nov 2026 12:24:41 -0500 Subject: [PATCH 01/15] fix(bigquery-jdbc): add single-pass URL parser, remove PARSE_CACHE, and validate property keys --- .../bigquery/jdbc/BigQueryConnection.java | 16 +- .../bigquery/jdbc/BigQueryJdbcUrlUtility.java | 379 +++++++++++++++--- .../jdbc/BigQueryJdbcUrlUtilityTest.java | 203 +++++++++- 3 files changed, 533 insertions(+), 65 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java index 8699c261a60a..b5ae8b24bafb 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java @@ -154,6 +154,8 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { BigQueryJdbcUrlUtility.ENABLE_PROJECT_DISCOVERY_PROPERTY_NAME, BigQueryJdbcUrlUtility.REQUEST_GOOGLE_DRIVE_SCOPE_PROPERTY_NAME, BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PROPERTY_NAME, + BigQueryJdbcUrlUtility.SSL_TRUST_STORE_TYPE_PROPERTY_NAME, + BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PROVIDER_PROPERTY_NAME, BigQueryJdbcUrlUtility.MAX_BYTES_BILLED_PROPERTY_NAME, BigQueryJdbcUrlUtility.LABELS_PROPERTY_NAME, BigQueryJdbcUrlUtility.REQUEST_REASON_PROPERTY_NAME, @@ -171,6 +173,10 @@ public class BigQueryConnection extends BigQueryNoOpsConnection { BigQueryJdbcUrlUtility.OAUTH_SA_EMAIL_PROPERTY_NAME, BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PATH_PROPERTY_NAME, BigQueryJdbcUrlUtility.OAUTH_CLIENT_ID_PROPERTY_NAME, + BigQueryJdbcUrlUtility.GCP_TELEMETRY_PROJECT_ID_PROPERTY_NAME, + BigQueryJdbcUrlUtility.ENABLE_GCP_TRACE_EXPORTER_PROPERTY_NAME, + BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME, + BigQueryJdbcUrlUtility.USE_GLOBAL_OTEL_PROPERTY_NAME, BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, BigQueryJdbcUrlUtility.ENABLE_GRAPH_METADATA_PROPERTY_NAME) .build(); @@ -297,11 +303,19 @@ static String sanitizeForLog(String value) { return sb == null ? value : sb.toString(); } + /** + * Returns whether {@code propertyName} is in the fail-closed {@link #SAFE_TO_LOG_PROPERTIES} + * allowlist. Any unknown or sensitive property returns {@code false}. + */ + static boolean isSafeToLogProperty(String propertyName) { + return propertyName != null && SAFE_TO_LOG_PROPERTIES.contains(propertyName); + } + static String maskPropertyValue(String key, Object value) { if (value == null) { return null; } - if (key == null || !SAFE_TO_LOG_PROPERTIES.contains(key)) { + if (!isSafeToLogProperty(key)) { return "*****"; } return sanitizeForLog(String.valueOf(value)); diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java index 41a1df22f939..d7eae3c65219 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java @@ -25,12 +25,14 @@ import com.google.common.collect.ImmutableList; import com.google.common.net.UrlEscapers; import java.security.KeyStore; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; @@ -45,14 +47,6 @@ */ final class BigQueryJdbcUrlUtility { - private static final Map> PARSE_CACHE = - Collections.synchronizedMap( - new LinkedHashMap>(50, 0.75f, true) { - protected boolean removeEldestEntry(Map.Entry> eldest) { - return size() > 50; // bound cache size - } - }); - // TODO: Add all Connection options static final String ALLOW_LARGE_RESULTS_PROPERTY_NAME = "AllowLargeResults"; static final String LARGE_RESULTS_TABLE_PROPERTY_NAME = "LargeResultTable"; @@ -710,7 +704,7 @@ protected boolean removeEldestEntry(Map.Entry> eldes ENDPOINT_OVERRIDES_PROPERTY_NAME, PRIVATE_SERVICE_CONNECT_PROPERTY_NAME); - private static final Map PROPERTY_NAME_MAP; + static final Map PROPERTY_NAME_MAP; static { Map map = new HashMap<>(); @@ -784,70 +778,320 @@ static String parseUriPropertyWithoutValidation(String uri, String property) { } /** - * Parses the URL into a map of key-value pairs, validating that all keys are known properties. + * Immutable result of a single-pass, non-throwing parse of a BigQuery JDBC connection URL. * - * @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. + *

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

    + *
  • Phase 1 (pre-connect / bootstrap lookup): "Bootstrap" here refers strictly to the + * pre-connect logging and telemetry settings ({@code EnableDiagnosticTelemetry}, {@code + * LogLevel}, {@code LogPath}, {@code enableGcpLogExporter}) that must be read using + * last-wins semantics before opening the pre-connect log scope and before full URL + * validation throws. + *
  • Phase 2 (validation): Once logging is active, callers invoke {@link + * #validateAndGetProperties()} to reject malformed segments or invalid percent-encoding (by + * 1-based segment position only, never echoing raw secret slices) and warn on unknown keys. + *
*/ - static Map parseUrl(String url) { - return PARSE_CACHE.computeIfAbsent(url, BigQueryJdbcUrlUtility::parseUrlInternal); + static final class ParsedConnectionUrl { + private final String urlPrefix; + private final Map canonicalProperties; + private final Map allowlistedDisplayProperties; + private final List malformedSegmentPositions; + private final List invalidPercentEncodingPositions; + private final List unknownPropertyKeys; + + ParsedConnectionUrl( + String urlPrefix, + Map canonicalProperties, + Map allowlistedDisplayProperties, + List malformedSegmentPositions, + List invalidPercentEncodingPositions, + List unknownPropertyKeys) { + this.urlPrefix = urlPrefix; + this.canonicalProperties = Collections.unmodifiableMap(canonicalProperties); + this.allowlistedDisplayProperties = Collections.unmodifiableMap(allowlistedDisplayProperties); + this.malformedSegmentPositions = Collections.unmodifiableList(malformedSegmentPositions); + this.invalidPercentEncodingPositions = + Collections.unmodifiableList(invalidPercentEncodingPositions); + this.unknownPropertyKeys = Collections.unmodifiableList(unknownPropertyKeys); + } + + /** + * Phase 1 non-throwing last-wins lookup for a pre-connect (bootstrap) property such as {@code + * LogLevel}, {@code LogPath}, {@code enableGcpLogExporter}, or {@code + * EnableDiagnosticTelemetry}, matched case-insensitively. + */ + String getPreConnectProperty(String propertyName) { + if (propertyName == null) { + return null; + } + String canonicalPropertyName = PROPERTY_NAME_MAP.get(propertyName.toUpperCase(Locale.ROOT)); + return canonicalPropertyName != null + ? canonicalProperties.get(canonicalPropertyName) + : canonicalProperties.get(propertyName); + } + + /** + * Phase 2 validation step: rejects malformed segments or invalid percent-encoding without + * echoing raw parameter text, logs warnings for unknown property keys, and returns the + * canonicalized URL property map. + */ + Map validateAndGetProperties() { + if (!malformedSegmentPositions.isEmpty()) { + throw new BigQueryJdbcRuntimeException( + String.format( + "Malformed connection property segment at index %d. Expected key=value format.", + malformedSegmentPositions.get(0))); + } + if (!invalidPercentEncodingPositions.isEmpty()) { + throw new BigQueryJdbcRuntimeException( + String.format( + "Invalid URL-encoded value at connection property segment %d.", + invalidPercentEncodingPositions.get(0))); + } + for (String unknownPropertyKey : unknownPropertyKeys) { + LOG.warning("Wrong value or unknown setting: %s", unknownPropertyKey); + } + return canonicalProperties; + } + + /** + * Builds a sanitized display URL suitable for {@code DatabaseMetaData.getURL()} and logs. + * + *

Non-allowlisted URL parameters are omitted (rather than masked as {@code key=*****}) so + * the returned URL stays syntactically valid for JDBC callers, avoids leaking secret parameter + * names to secret scanners, and prevents callers or BI tools from feeding {@code *****} back as + * a literal credential. Out-of-band {@code Properties}/{@code DataSource} credentials are never + * appended to the URL. + */ + String toSanitizedDisplayUrl() { + if (urlPrefix == null) { + return null; + } + if (urlPrefix.isEmpty()) { + return ""; + } + String sanitizedUrlPrefix = BigQueryConnection.sanitizeForLog(urlPrefix); + String normalizedUrlPrefix = + sanitizedUrlPrefix.startsWith("bigquery:") + ? "jdbc:" + sanitizedUrlPrefix + : sanitizedUrlPrefix; + if (allowlistedDisplayProperties.isEmpty()) { + return normalizedUrlPrefix; + } + StringBuilder displayUrlBuilder = new StringBuilder(normalizedUrlPrefix); + for (Entry displayEntry : allowlistedDisplayProperties.entrySet()) { + displayUrlBuilder + .append(';') + .append(displayEntry.getKey()) + .append('=') + .append(displayEntry.getValue()); + } + return displayUrlBuilder.toString(); + } } - private static Map parseUrlInternal(String url) { - Map map = new HashMap<>(); - if (url == null) { - return map; + /** + * 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. + * + *

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 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.toUpperCase(Locale.ROOT).startsWith("GPN:")) { + return " (" + unwrappedToken + ")"; } + return null; + } - String[] urlParts = url.split(";", 2); - if (urlParts.length < 2) { - 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.emptyMap(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList()); } - String urlToParse = urlParts[1]; + int firstSemicolonIndex = connectionUrl.indexOf(';'); + if (firstSemicolonIndex == -1) { + return new ParsedConnectionUrl( + connectionUrl, + Collections.emptyMap(), + Collections.emptyMap(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList()); + } - // 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; + String urlPrefix = connectionUrl.substring(0, firstSemicolonIndex); + String parameterSection = connectionUrl.substring(firstSemicolonIndex + 1); + Map canonicalProperties = new LinkedHashMap<>(); + Map allowlistedDisplayProperties = new LinkedHashMap<>(); + List malformedSegmentPositions = new ArrayList<>(); + List invalidPercentEncodingPositions = new ArrayList<>(); + List unknownPropertyKeys = new ArrayList<>(); - 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); + if (BigQueryConnection.isSafeToLogProperty(PARTNER_TOKEN_PROPERTY_NAME)) { + allowlistedDisplayProperties.put( + PARTNER_TOKEN_PROPERTY_NAME, + BigQueryConnection.sanitizeForLog(formattedPartnerToken.trim())); + } + } else { + canonicalProperties.remove(PARTNER_TOKEN_PROPERTY_NAME); + allowlistedDisplayProperties.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) { + 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, while keeping unknown keys out of the sanitized display URL. + 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; + } + canonicalProperties.put(canonicalPropertyName, decodedPropertyValue); + // Omit non-allowlisted URL parameters from the display URL (DatabaseMetaData.getURL() + // contract) so credentials embedded in a URL never leak into metadata, traces, or logs. + if (BigQueryConnection.isSafeToLogProperty(canonicalPropertyName)) { + allowlistedDisplayProperties.put( + canonicalPropertyName, BigQueryConnection.sanitizeForLog(encodedPropertyValue)); + } + } + + return new ParsedConnectionUrl( + urlPrefix, + canonicalProperties, + allowlistedDisplayProperties, + malformedSegmentPositions, + invalidPercentEncodingPositions, + unknownPropertyKeys); + } + + /** + * Returns a sanitized display URL with the {@code jdbc:bigquery:} prefix preserved and all + * non-allowlisted ({@code !SAFE_TO_LOG_PROPERTIES}) URL parameters omitted. + */ + static String sanitizeUrlForDisplay(String connectionUrl) { + return parseConnectionUrl(connectionUrl).toSanitizedDisplayUrl(); + } + + /** + * Validates a caller-supplied connection property key from {@code Properties}, rejecting + * delimiters ({@code ';'}, {@code '='}), ASCII control characters, blank keys, and + * leading/trailing whitespace so caller keys cannot inject or forge sibling connection + * properties. + */ + static String validatePropertyKey(Object propertyKeyObject) { + if (propertyKeyObject == null) { + throw new BigQueryJdbcRuntimeException("Connection property key must not be null."); + } + String propertyKey = String.valueOf(propertyKeyObject); + if (propertyKey.isEmpty() || !propertyKey.equals(propertyKey.trim())) { + throw new BigQueryJdbcRuntimeException( + "Invalid connection property key: key must not be empty or contain leading/trailing" + + " whitespace."); + } + for (int index = 0; index < propertyKey.length(); index++) { + char character = propertyKey.charAt(index); + if (character == ';' || character == '=' || character < 0x20 || character == 0x7F) { + throw new BigQueryJdbcRuntimeException( + "Invalid connection property key: key must not contain ';', '=', or control" + + " characters."); } - String propertyName = PROPERTY_NAME_MAP.get(key); - String value = CharEscapers.decodeUriPath(kv[1].replace("+", "%2B")); - map.put(propertyName, value); } - return Collections.unmodifiableMap(map); + 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() { @@ -894,7 +1138,7 @@ static String appendPropertiesToURL(String url, String callerClassName, Properti Object rawKey = entry.getKey(); Object rawValue = entry.getValue(); if (rawKey != null && rawValue != null) { - String key = String.valueOf(rawKey); + String key = validatePropertyKey(rawKey); String valueStr = String.valueOf(rawValue); if (!valueStr.isEmpty()) { LOG.finest( @@ -983,15 +1227,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); + if (entryKey.trim().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/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..8f7fe6ef7783 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; @@ -492,17 +495,213 @@ public void testSanitizeControlCharactersAndCaseInsensitiveSafeProperties() { 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"); + props.setProperty("CustomUnknownKey", "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(); + assertThat(assertLogContains("Appending CustomUnknownKey with value ***** to URL")).isTrue(); for (LogRecord rec : capturedLogs) { assertThat(rec.getMessage()).doesNotContain("\n"); assertThat(rec.getMessage()).doesNotContain("\r"); } + + // Control characters inside property keys are rejected outright. + Properties controlKeyProperties = new Properties(); + controlKeyProperties.setProperty("Custom\nKey", "secret-val"); + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", controlKeyProperties)); + } + + @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 testAppendPropertiesToURL_rejectsInvalidPropertyKeys(String invalidKey) { + String baseUrl = "bigquery://https://www.googleapis.com/bigquery/v2:443;ProjectId=locked"; + Properties invalidProperties = new Properties(); + invalidProperties.setProperty(invalidKey, "val"); + + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", invalidProperties)); + } + + @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")); + + // 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(); + 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"); + + // 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;ProjectId=p"); + BigQueryJdbcRuntimeException invalidEncodingException = + assertThrows( + BigQueryJdbcRuntimeException.class, parsedInvalidEncodingUrl::validateAndGetProperties); + assertThat(invalidEncodingException.getMessage()).doesNotContain("secret"); + assertThat(invalidEncodingException.getMessage()).doesNotContain("%ZZ"); + } + + @Test + public void testSanitizeUrlForDisplay_omitsNonAllowlistedParamsAndNormalizesPrefix() { + 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;" + + "PartnerToken=(GPN:acme; prod);ProjectId=p2;OAuthType=2"); + } + + @Test + public void testFormatPartnerTokenHeaderValue_doesNotDoubleDecodeAndPreservesLiteralPercent() { + assertNull(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue(null)); + assertNull(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue("(env)")); + 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); + assertThat(isAllowlisted ^ isExpectedNonAllowlisted).isTrue(); + } + assertFalse(BigQueryConnection.isSafeToLogProperty(null)); + assertFalse(BigQueryConnection.isSafeToLogProperty("UnknownCustomSecret")); } } From a84ef0aa655b40f5c99a66100eeff6db3e66eb50 Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 30 Nov 2026 12:31:09 -0500 Subject: [PATCH 02/15] fix(bigquery-jdbc): pass typed DataSource overrides and unify last-wins connect pipeline Stack: PR 2 of 3 (base: fix/g01-url-parsing-and-sanitization) Bug: b/584841439, b/584840529, b/584840728, b/584839495 - Replace DataSource.getConnection() createProperties/DriverManager URL round-trip with a defensive typed DataSource snapshot passed directly to BigQueryDriver.connectWithDataSource(). - Preserve all 15 previously dropped security bean fields, explicit false on boxed telemetry/OTel flags, unset enableDiagnosticTelemetry, and raw ImmutableMap queryProperties/labels. - Unify BigQueryDriver.connect() onto two-phase single-pass tokenization with last-wins precedence (Properties/DataSource > URL) for LogLevel, LogPath, enableGcpLogExporter, and EnableDiagnosticTelemetry. - Redact invalid-URL exceptions in DataSource.getConnection() and fix single-read URL TOCTOU. --- .../cloud/bigquery/jdbc/BigQueryDriver.java | 396 +++++++++++++----- .../cloud/bigquery/jdbc/DataSource.java | 354 ++++++++++++++-- .../bigquery/jdbc/BigQueryDriverTest.java | 88 +++- .../cloud/bigquery/jdbc/DataSourceTest.java | 207 +++++++++ .../jdbc/PooledConnectionDataSourceTest.java | 34 ++ 5 files changed, 953 insertions(+), 126 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java index de14bdbfc1da..d832289127dc 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java @@ -33,7 +33,10 @@ import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.logging.Level; @@ -108,6 +111,138 @@ public static BigQueryDriver getRegisteredDriver() throws IllegalStateException throw ex; } + /** + * Result of validating and normalizing caller-supplied {@link Properties} passed to {@link + * Driver} methods without flattening them onto the JDBC URL. + * + *

"Normalized" here means: + * + *

    + *
  • Every key has been validated by {@link BigQueryJdbcUrlUtility#validatePropertyKey} + * against delimiters ({@code ';'}, {@code '='}), control characters, and outer whitespace. + *
  • Case-insensitive known property names are mapped to their canonical names from {@link + * BigQueryJdbcUrlUtility#PROPERTY_NAME_MAP}. + *
  • Direct entries in the caller's {@link Properties} deterministically override any + * inherited parent defaults. + *
  • Unknown keys are truncated and log-sanitized separately so Phase 2 can log warnings once + * logging is active, and any {@link OpenTelemetry} instance under {@code + * customOpenTelemetry} is extracted out of band. + *
+ */ + static final class ValidatedConnectionProperties { + final Map canonicalProperties; + final List unknownPropertyKeys; + final OpenTelemetry customOpenTelemetry; + + ValidatedConnectionProperties( + Map canonicalProperties, + List unknownPropertyKeys, + OpenTelemetry customOpenTelemetry) { + this.canonicalProperties = Collections.unmodifiableMap(canonicalProperties); + this.unknownPropertyKeys = Collections.unmodifiableList(unknownPropertyKeys); + this.customOpenTelemetry = customOpenTelemetry; + } + } + + /** + * Validates and normalizes (canonicalizes) caller-supplied {@link Properties} without serializing + * them onto the JDBC URL. Preserves inherited {@link Properties} defaults, non-String values via + * {@link String#valueOf(Object)}, and out-of-band {@code customOpenTelemetry} instances. + */ + static ValidatedConnectionProperties validateAndCanonicalizeProperties( + Properties callerProperties) { + if (callerProperties == null) { + return new ValidatedConnectionProperties( + Collections.emptyMap(), Collections.emptyList(), null); + } + OpenTelemetry customOpenTelemetry = null; + Object customOpenTelemetryValue = callerProperties.get("customOpenTelemetry"); + if (customOpenTelemetryValue instanceof OpenTelemetry) { + customOpenTelemetry = (OpenTelemetry) customOpenTelemetryValue; + } + + Map canonicalProperties = new LinkedHashMap<>(); + List unknownPropertyKeys = new ArrayList<>(); + + // Pass 1: record inherited String defaults that are not directly shadowed in callerProperties. + for (String defaultPropertyKey : callerProperties.stringPropertyNames()) { + if ("customOpenTelemetry".equals(defaultPropertyKey) + || callerProperties.containsKey(defaultPropertyKey)) { + continue; + } + String validatedPropertyKey = BigQueryJdbcUrlUtility.validatePropertyKey(defaultPropertyKey); + String defaultPropertyValue = callerProperties.getProperty(defaultPropertyKey); + recordValidatedProperty( + validatedPropertyKey, defaultPropertyValue, canonicalProperties, unknownPropertyKeys); + } + + // Pass 2: overlay direct entries from callerProperties (both String and non-String values) so + // direct entries always win deterministically over inherited defaults, including case-variant + // keys. + for (Map.Entry directPropertyEntry : callerProperties.entrySet()) { + Object directKeyObject = directPropertyEntry.getKey(); + Object directValueObject = directPropertyEntry.getValue(); + if ("customOpenTelemetry".equals(directKeyObject)) { + continue; + } + if (directKeyObject != null && directValueObject != null) { + String validatedPropertyKey = BigQueryJdbcUrlUtility.validatePropertyKey(directKeyObject); + recordValidatedProperty( + validatedPropertyKey, + String.valueOf(directValueObject), + canonicalProperties, + unknownPropertyKeys); + } + } + + return new ValidatedConnectionProperties( + canonicalProperties, unknownPropertyKeys, customOpenTelemetry); + } + + private static void recordValidatedProperty( + String propertyKey, + String propertyValue, + Map canonicalProperties, + List unknownPropertyKeys) { + if (propertyValue == null || propertyValue.isEmpty()) { + return; + } + String uppercasePropertyKey = propertyKey.toUpperCase(Locale.ROOT); + String canonicalPropertyName = + BigQueryJdbcUrlUtility.PROPERTY_NAME_MAP.get(uppercasePropertyKey); + if (canonicalPropertyName != null) { + canonicalProperties.put(canonicalPropertyName, propertyValue); + } else { + String truncatedPropertyKey = + uppercasePropertyKey.length() > 32 + ? uppercasePropertyKey.substring(0, 32) + "..." + : uppercasePropertyKey; + unknownPropertyKeys.add(BigQueryConnection.sanitizeForLog(truncatedPropertyKey)); + } + } + + /** + * Resolves a pre-connect ("bootstrap") setting—one of the four logging/telemetry properties + * ({@code EnableDiagnosticTelemetry}, {@code LogLevel}, {@code LogPath}, {@code + * enableGcpLogExporter}) that must be read before the pre-connect logger opens and before Phase 2 + * URL validation throws—applying strict precedence: {@code DataSource} setter > caller {@link + * Properties} > URL parameter (last-wins). + */ + private static String resolvePreConnectProperty( + String canonicalPropertyName, + String dataSourceOverrideValue, + ValidatedConnectionProperties propertiesOverrides, + BigQueryJdbcUrlUtility.ParsedConnectionUrl parsedUrl) { + if (dataSourceOverrideValue != null) { + return dataSourceOverrideValue; + } + if (propertiesOverrides != null + && propertiesOverrides.canonicalProperties.containsKey(canonicalPropertyName)) { + return propertiesOverrides.canonicalProperties.get(canonicalPropertyName); + } + return parsedUrl.getPreConnectProperty(canonicalPropertyName); + } + /** * Attempts to establish a BigQuery connection to the given URL, using the provided connection * Properties. @@ -128,116 +263,183 @@ public static BigQueryDriver getRegisteredDriver() throws IllegalStateException @Override public Connection connect(String url, Properties info) throws SQLException { LOG.finest("++enter++"); - AuthenticationType authType = AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED; + if (!acceptsURL(url)) { + return null; + } + ValidatedConnectionProperties propertiesOverrides; try { - if (acceptsURL(url)) { - Properties connectInfo = info == null ? new Properties() : (Properties) info.clone(); - Object customOpenTelemetryObj = connectInfo.remove("customOpenTelemetry"); + propertiesOverrides = validateAndCanonicalizeProperties(info); + } catch (RuntimeException e) { + LOG.log(Level.SEVERE, "Failed to parse connection URL properties", e); + BigQueryJdbcException jdbcException = + new BigQueryJdbcException("Failed to parse connection URL properties", e); + TelemetryManager.recordConnectionAttempt( + Status.STATUS_ERROR, + TelemetryManager.extractErrorCode(jdbcException), + AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED); + throw jdbcException; + } + return connectInternal(url, propertiesOverrides, null); + } - String connectionUri = - BigQueryJdbcUrlUtility.appendPropertiesToURL( - url.substring(5), this.toString(), connectInfo); + /** + * Package-private entry point used by {@link DataSource#getConnection()} to pass a defensive + * typed snapshot directly into the driver without flattening fields into a URL string. + */ + Connection connectWithDataSource(String url, DataSource configuredDataSourceSnapshot) + throws SQLException { + LOG.finest("++enter++"); + if (!acceptsURL(url)) { + return null; + } + return connectInternal(url, null, configuredDataSourceSnapshot); + } - String telemetryOptOut = - BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation( - connectionUri, BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME); + private Connection connectInternal( + String url, ValidatedConnectionProperties propertiesOverrides, DataSource dataSourceOverrides) + throws SQLException { + AuthenticationType authType = AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED; + try { + BigQueryJdbcUrlUtility.ParsedConnectionUrl parsedUrl = + BigQueryJdbcUrlUtility.parseConnectionUrl(url); - if (telemetryOptOut != null) { - connectInfo.setProperty( - BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, telemetryOptOut); - } - TelemetryManager.getInstance(connectInfo); + String dataSourceTelemetryFlag = + dataSourceOverrides != null + && dataSourceOverrides.getConfiguredEnableDiagnosticTelemetry() != null + ? String.valueOf(dataSourceOverrides.getConfiguredEnableDiagnosticTelemetry()) + : null; + String diagnosticTelemetrySetting = + resolvePreConnectProperty( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, + dataSourceTelemetryFlag, + propertiesOverrides, + parsedUrl); + Properties telemetryProperties = new Properties(); + if (diagnosticTelemetrySetting != null) { + telemetryProperties.setProperty( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, + diagnosticTelemetrySetting); + } + TelemetryManager.getInstance(telemetryProperties); - Level logLevel; - String logPath; - boolean ignoredUrlLogPath; - try { - // LogLevel - String logLevelStr = - BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation( - connectionUri, BigQueryJdbcUrlUtility.LOG_LEVEL_PROPERTY_NAME); - if (logLevelStr == null) { - logLevelStr = System.getenv(BigQueryJdbcUrlUtility.LOG_LEVEL_ENV_VAR); - } - logLevel = BigQueryJdbcUrlUtility.parseLogLevel(logLevelStr); - - // LogPath - String urlLogPath = - BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation( - connectionUri, BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME); - String envLogPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR); - - String enableGcpLogExporterStr = - BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation( - connectionUri, BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME); - boolean enableGcpLogExporter = false; - if (enableGcpLogExporterStr != null) { - enableGcpLogExporter = - BigQueryJdbcUrlUtility.convertToBoolean( - enableGcpLogExporterStr, - BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME); - } - ignoredUrlLogPath = !BigQueryJdbcUrlUtility.isUrlLogPathAllowed() && urlLogPath != null; - logPath = - BigQueryJdbcUrlUtility.resolveEffectiveLogPath( - urlLogPath, envLogPath, !enableGcpLogExporter); - - BigQueryJdbcRootLogger.setLevel(logLevel, logPath); - } catch (RuntimeException e) { - LOG.log(Level.SEVERE, "Failed to parse connection URL properties", e); - throw new BigQueryJdbcException("Failed to parse connection URL properties", e); + Level logLevel; + String logPath; + boolean isConfiguredLogPathIgnored; + try { + String configuredLogLevel = + resolvePreConnectProperty( + BigQueryJdbcUrlUtility.LOG_LEVEL_PROPERTY_NAME, + dataSourceOverrides != null ? dataSourceOverrides.getLogLevel() : null, + propertiesOverrides, + parsedUrl); + if (configuredLogLevel == null) { + configuredLogLevel = System.getenv(BigQueryJdbcUrlUtility.LOG_LEVEL_ENV_VAR); } + logLevel = BigQueryJdbcUrlUtility.parseLogLevel(configuredLogLevel); - // Logging starts from here. - BigQueryConnection connection; - try (BigQueryJdbcMdc.MdcCloseable preConnect = - BigQueryJdbcRootLogger.openPreConnectScope(logLevel, logPath)) { - if (ignoredUrlLogPath) { - LOG.warning( - "Ignoring URL/Properties %s because system property %s is false.", + String configuredLogPath = + resolvePreConnectProperty( BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME, - BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY); - } - DataSource ds; - try { - ds = DataSource.fromUrl(connectionUri); - } catch (BigQueryJdbcRuntimeException e) { - LOG.log(Level.SEVERE, "Failed to parse connection URL", e); - throw new BigQueryJdbcException("Failed to parse connection URL", e); + dataSourceOverrides != null ? dataSourceOverrides.getLogPath() : null, + propertiesOverrides, + parsedUrl); + String environmentLogPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR); + + boolean enableGcpLogExporter; + if (dataSourceOverrides != null + && dataSourceOverrides.getConfiguredEnableGcpLogExporter() != null) { + enableGcpLogExporter = dataSourceOverrides.getConfiguredEnableGcpLogExporter(); + } else { + String configuredGcpLogExporter = + resolvePreConnectProperty( + BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME, + null, + propertiesOverrides, + parsedUrl); + enableGcpLogExporter = + configuredGcpLogExporter != null + && BigQueryJdbcUrlUtility.convertToBoolean( + configuredGcpLogExporter, + BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME); + } + isConfiguredLogPathIgnored = + !BigQueryJdbcUrlUtility.isUrlLogPathAllowed() && configuredLogPath != null; + logPath = + BigQueryJdbcUrlUtility.resolveEffectiveLogPath( + configuredLogPath, environmentLogPath, !enableGcpLogExporter); + + BigQueryJdbcRootLogger.setLevel(logLevel, logPath); + } catch (RuntimeException e) { + LOG.log(Level.SEVERE, "Failed to parse connection URL properties", e); + throw new BigQueryJdbcException("Failed to parse connection URL properties", e); + } + + // Logging starts from here. + BigQueryConnection connection; + try (BigQueryJdbcMdc.MdcCloseable preConnect = + BigQueryJdbcRootLogger.openPreConnectScope(logLevel, logPath)) { + if (isConfiguredLogPathIgnored) { + LOG.warning( + "Ignoring URL/Properties %s because system property %s is false.", + BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME, + BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY); + } + String sanitizedDisplayUrl = parsedUrl.toSanitizedDisplayUrl(); + DataSource resolvedDataSource; + try { + Map validatedUrlProperties = parsedUrl.validateAndGetProperties(); + if (propertiesOverrides != null) { + for (String unknownPropertyKey : propertiesOverrides.unknownPropertyKeys) { + LOG.warning("Wrong value or unknown setting: %s", unknownPropertyKey); + } } - authType = TelemetryManager.toAuthenticationType(ds.getOAuthType()); - if (customOpenTelemetryObj instanceof OpenTelemetry) { - ds.setCustomOpenTelemetry((OpenTelemetry) customOpenTelemetryObj); + if (dataSourceOverrides != null) { + resolvedDataSource = + DataSource.fromCanonicalProperties(sanitizedDisplayUrl, validatedUrlProperties); + dataSourceOverrides.applyConfiguredFieldsTo(resolvedDataSource); + } else { + Map mergedConnectionProperties = + new LinkedHashMap<>(validatedUrlProperties); + if (propertiesOverrides != null) { + mergedConnectionProperties.putAll(propertiesOverrides.canonicalProperties); + } + resolvedDataSource = + DataSource.fromCanonicalProperties(sanitizedDisplayUrl, mergedConnectionProperties); + if (propertiesOverrides != null && propertiesOverrides.customOpenTelemetry != null) { + resolvedDataSource.setCustomOpenTelemetry(propertiesOverrides.customOpenTelemetry); + } } - connection = new BigQueryConnection(connectionUri, ds); - } - try (BigQueryJdbcMdc.MdcCloseable mdc = - BigQueryJdbcMdc.registerInstance(connection.getConnectionId())) { - DatabaseMetaData metaData = connection.getMetaDataInternal(); - LOG.info( - "Driver info : { {Database Product Name : %s}, " - + "{Database Product Version : %s}, " - + "{Driver Name : %s}, " - + "{Driver Version : %s}, " - + "{LogLevel : %s}, " - + "{LogPath : %s}, " - + "{Driver Instance : %s} }", - metaData.getDatabaseProductName(), - metaData.getDatabaseProductVersion(), - metaData.getDriverName(), - metaData.getDriverVersion(), - logLevel, - logPath, - this.toString()); + } catch (BigQueryJdbcRuntimeException | IllegalArgumentException e) { + LOG.log(Level.SEVERE, "Failed to parse connection URL", e); + throw new BigQueryJdbcException("Failed to parse connection URL", e); } + authType = TelemetryManager.toAuthenticationType(resolvedDataSource.getOAuthType()); + connection = new BigQueryConnection(sanitizedDisplayUrl, resolvedDataSource); + } + try (BigQueryJdbcMdc.MdcCloseable mdc = + BigQueryJdbcMdc.registerInstance(connection.getConnectionId())) { + DatabaseMetaData metaData = connection.getMetaDataInternal(); + LOG.info( + "Driver info : { {Database Product Name : %s}, " + + "{Database Product Version : %s}, " + + "{Driver Name : %s}, " + + "{Driver Version : %s}, " + + "{LogLevel : %s}, " + + "{LogPath : %s}, " + + "{Driver Instance : %s} }", + metaData.getDatabaseProductName(), + metaData.getDatabaseProductVersion(), + metaData.getDriverName(), + metaData.getDriverVersion(), + logLevel, + logPath, + this.toString()); + } - Connection wrapped = BigQueryJdbcContextProxy.wrap(connection, Connection.class); + Connection proxiedConnection = BigQueryJdbcContextProxy.wrap(connection, Connection.class); - TelemetryManager.recordConnectionAttempt(Status.STATUS_SUCCESS, 0, authType); - return wrapped; - } else { - return null; - } + TelemetryManager.recordConnectionAttempt(Status.STATUS_SUCCESS, 0, authType); + return proxiedConnection; } catch (IOException e) { TelemetryManager.recordConnectionAttempt( Status.STATUS_ERROR, TelemetryManager.extractErrorCode(e), authType); diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java index 61f5ac9f581a..1ae9d6cda6f1 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java @@ -25,7 +25,6 @@ import io.opentelemetry.api.OpenTelemetry; import java.io.PrintWriter; import java.sql.Connection; -import java.sql.DriverManager; import java.sql.SQLException; import java.util.Map; import java.util.Properties; @@ -124,12 +123,10 @@ public class DataSource implements javax.sql.DataSource { private String privateServiceConnect; private Long connectionPoolSize; private Long listenerPoolSize; - private boolean enableGcpTraceExporter = - BigQueryJdbcUrlUtility.DEFAULT_ENABLE_GCP_TRACE_EXPORTER_VALUE; - private boolean enableGcpLogExporter = - BigQueryJdbcUrlUtility.DEFAULT_ENABLE_GCP_LOG_EXPORTER_VALUE; + private Boolean enableGcpTraceExporter; + private Boolean enableGcpLogExporter; private OpenTelemetry customOpenTelemetry; - private boolean useGlobalOpenTelemetry = BigQueryJdbcUrlUtility.DEFAULT_USE_GLOBAL_OTEL_VALUE; + private Boolean useGlobalOpenTelemetry; private Boolean enableDiagnosticTelemetry; private Boolean enableGraphMetadata; @@ -254,7 +251,10 @@ public class DataSource implements javax.sql.DataSource { .put( BigQueryJdbcUrlUtility.MAX_RESULTS_PROPERTY_NAME, (ds, val) -> ds.setMaxResults(Long.parseLong(val))) - .put(BigQueryJdbcUrlUtility.PARTNER_TOKEN_PROPERTY_NAME, DataSource::setPartnerToken) + .put( + BigQueryJdbcUrlUtility.PARTNER_TOKEN_PROPERTY_NAME, + (ds, val) -> + ds.setPartnerToken(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue(val))) .put( BigQueryJdbcUrlUtility.ENABLE_WRITE_API_PROPERTY_NAME, (ds, val) -> @@ -406,17 +406,26 @@ public class DataSource implements javax.sql.DataSource { .build(); public static DataSource fromUrl(String url) { + return fromCanonicalProperties(url, BigQueryJdbcUrlUtility.parseUrl(url)); + } + + /** + * Builds a {@link DataSource} from already-validated canonical property names (keys from {@link + * BigQueryJdbcUrlUtility#PROPERTY_NAME_MAP}) and decoded string values. + */ + static DataSource fromCanonicalProperties( + String connectionUrl, Map canonicalProperties) { DataSource dataSource = new DataSource(); - dataSource.setURL(url); - Map properties = BigQueryJdbcUrlUtility.parseUrl(url); - for (Map.Entry entry : properties.entrySet()) { - BiConsumer setter = PROPERTY_SETTERS.get(entry.getKey()); - if (setter != null) { + dataSource.setURL(connectionUrl); + for (Map.Entry propertyEntry : canonicalProperties.entrySet()) { + BiConsumer propertySetter = PROPERTY_SETTERS.get(propertyEntry.getKey()); + if (propertySetter != null) { try { - setter.accept(dataSource, entry.getValue()); + propertySetter.accept(dataSource, propertyEntry.getValue()); } catch (NumberFormatException e) { throw new BigQueryJdbcRuntimeException( - String.format("Invalid value for %s. It must be a valid integer.", entry.getKey()), + String.format( + "Invalid value for %s. It must be a valid integer.", propertyEntry.getKey()), e); } } @@ -452,19 +461,284 @@ public DataSource() {} @Override public Connection getConnection() throws SQLException { - if (getURL() == null) { + String connectionUrl = getURL(); + if (connectionUrl == null) { throw new BigQueryJdbcException( "Connection URL is null. Please specify a valid Connection URL to get Connection."); } - if (!BigQueryDriver.getRegisteredDriver().acceptsURL(getURL())) { + if (!BigQueryDriver.getRegisteredDriver().acceptsURL(connectionUrl)) { throw new BigQueryJdbcException( - "The URL " + getURL() + " is invalid. Please specify a valid Connection URL. "); + "The connection URL is invalid. Please specify a valid Connection URL starting with" + + " 'jdbc:bigquery:'."); + } + return BigQueryDriver.getRegisteredDriver() + .connectWithDataSource(connectionUrl, snapshotConfiguredFields()); + } + + /** Returns an unshared snapshot of all explicitly configured JavaBean fields on this instance. */ + DataSource snapshotConfiguredFields() { + DataSource configuredSnapshot = new DataSource(); + applyConfiguredFieldsTo(configuredSnapshot); + // Preserve the unformatted partnerToken on the snapshot so an explicit non-GPN token (e.g. + // "(env)") still clears any URL-supplied PartnerToken when applied onto the URL-parsed + // DataSource. + configuredSnapshot.partnerToken = this.partnerToken; + return configuredSnapshot; + } + + /** + * Copies every non-null field configured 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 (this.projectId != null) { + targetDataSource.projectId = this.projectId; + } + if (this.defaultDataset != null) { + targetDataSource.defaultDataset = this.defaultDataset; + } + if (this.location != null) { + targetDataSource.location = this.location; + } + if (this.userAgent != null) { + targetDataSource.userAgent = this.userAgent; + } + if (this.enableHighThroughputAPI != null) { + targetDataSource.enableHighThroughputAPI = this.enableHighThroughputAPI; + } + if (this.highThroughputMinTableSize != null) { + targetDataSource.highThroughputMinTableSize = this.highThroughputMinTableSize; + } + if (this.highThroughputActivationRatio != null) { + targetDataSource.highThroughputActivationRatio = this.highThroughputActivationRatio; + } + if (this.unsupportedHTAPIFallback != null) { + targetDataSource.unsupportedHTAPIFallback = this.unsupportedHTAPIFallback; + } + if (this.kmsKeyName != null) { + targetDataSource.kmsKeyName = this.kmsKeyName; + } + if (this.queryProperties != null) { + targetDataSource.queryProperties = this.queryProperties; + } + if (this.logLevel != null) { + targetDataSource.logLevel = this.logLevel; + } + if (this.enableSession != null) { + targetDataSource.enableSession = this.enableSession; + } + if (this.enableTimestampPicos != null) { + targetDataSource.enableTimestampPicos = this.enableTimestampPicos; + } + if (this.logPath != null) { + targetDataSource.logPath = this.logPath; + } + if (this.gcpTelemetryProjectId != null) { + targetDataSource.gcpTelemetryProjectId = this.gcpTelemetryProjectId; + } + if (this.gcpTelemetryCredentials != null) { + targetDataSource.gcpTelemetryCredentials = this.gcpTelemetryCredentials; + } + if (this.oAuthType != null) { + targetDataSource.oAuthType = this.oAuthType; + } + if (this.oAuthServiceAcctEmail != null) { + targetDataSource.oAuthServiceAcctEmail = this.oAuthServiceAcctEmail; + } + if (this.oAuthPvtKeyPath != null) { + targetDataSource.oAuthPvtKeyPath = this.oAuthPvtKeyPath; + } + if (this.oAuthPvtKey != null) { + targetDataSource.oAuthPvtKey = this.oAuthPvtKey; + } + if (this.oAuthAccessToken != null) { + targetDataSource.oAuthAccessToken = this.oAuthAccessToken; + } + if (this.oAuthAccessTokenReadonly != null) { + targetDataSource.oAuthAccessTokenReadonly = this.oAuthAccessTokenReadonly; + } + if (this.oAuthRefreshToken != null) { + targetDataSource.oAuthRefreshToken = this.oAuthRefreshToken; + } + if (this.useQueryCache != null) { + targetDataSource.useQueryCache = this.useQueryCache; + } + if (this.queryDialect != null) { + targetDataSource.queryDialect = this.queryDialect; + } + if (this.allowLargeResults != null) { + targetDataSource.allowLargeResults = this.allowLargeResults; + } + if (this.destinationTable != null) { + targetDataSource.destinationTable = this.destinationTable; + } + if (this.destinationDataset != null) { + targetDataSource.destinationDataset = this.destinationDataset; + } + if (this.destinationDatasetExpirationTime != null) { + targetDataSource.destinationDatasetExpirationTime = this.destinationDatasetExpirationTime; + } + if (this.universeDomain != null) { + targetDataSource.universeDomain = this.universeDomain; + } + if (this.proxyHost != null) { + targetDataSource.proxyHost = this.proxyHost; + } + if (this.proxyPort != null) { + targetDataSource.proxyPort = this.proxyPort; + } + if (this.proxyUid != null) { + targetDataSource.proxyUid = this.proxyUid; + } + if (this.proxyPwd != null) { + targetDataSource.proxyPwd = this.proxyPwd; + } + if (this.oAuthClientId != null) { + targetDataSource.oAuthClientId = this.oAuthClientId; + } + if (this.oAuthClientSecret != null) { + targetDataSource.oAuthClientSecret = this.oAuthClientSecret; + } + if (this.jobCreationMode != null) { + targetDataSource.jobCreationMode = this.jobCreationMode; + } + if (this.maxResults != null) { + targetDataSource.maxResults = this.maxResults; + } + if (this.partnerToken != null && !this.partnerToken.isEmpty()) { + targetDataSource.partnerToken = + BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue(this.partnerToken); + } + if (this.enableWriteAPI != null) { + targetDataSource.enableWriteAPI = this.enableWriteAPI; + } + if (this.additionalProjects != null) { + targetDataSource.additionalProjects = this.additionalProjects; + } + if (this.filterTablesOnDefaultDataset != null) { + targetDataSource.filterTablesOnDefaultDataset = this.filterTablesOnDefaultDataset; + } + if (this.enableProjectDiscovery != null) { + targetDataSource.enableProjectDiscovery = this.enableProjectDiscovery; + } + if (this.requestGoogleDriveScope != null) { + targetDataSource.requestGoogleDriveScope = this.requestGoogleDriveScope; + } + if (this.metadataFetchThreadCount != null) { + targetDataSource.metadataFetchThreadCount = this.metadataFetchThreadCount; + } + if (this.sslTrustStorePath != null) { + targetDataSource.sslTrustStorePath = this.sslTrustStorePath; + } + if (this.sslTrustStorePassword != null) { + targetDataSource.sslTrustStorePassword = this.sslTrustStorePassword; + } + if (this.sslTrustStoreType != null) { + targetDataSource.sslTrustStoreType = this.sslTrustStoreType; + } + if (this.sslTrustStoreProvider != null) { + targetDataSource.sslTrustStoreProvider = this.sslTrustStoreProvider; + } + if (this.labels != null) { + targetDataSource.labels = this.labels; + } + if (this.requestReason != null) { + targetDataSource.requestReason = this.requestReason; + } + if (this.timeout != null) { + targetDataSource.timeout = this.timeout; + } + if (this.jobTimeout != null) { + targetDataSource.jobTimeout = this.jobTimeout; + } + if (this.retryInitialDelay != null) { + targetDataSource.retryInitialDelay = this.retryInitialDelay; + } + if (this.retryMaxDelay != null) { + targetDataSource.retryMaxDelay = this.retryMaxDelay; + } + if (this.httpConnectTimeout != null) { + targetDataSource.httpConnectTimeout = this.httpConnectTimeout; + } + if (this.httpReadTimeout != null) { + targetDataSource.httpReadTimeout = this.httpReadTimeout; + } + if (this.maximumBytesBilled != null) { + targetDataSource.maximumBytesBilled = this.maximumBytesBilled; + } + if (this.swaActivationRowCount != null) { + targetDataSource.swaActivationRowCount = this.swaActivationRowCount; + } + if (this.swaAppendRowCount != null) { + targetDataSource.swaAppendRowCount = this.swaAppendRowCount; + } + if (this.oAuthP12Password != null) { + targetDataSource.oAuthP12Password = this.oAuthP12Password; + } + if (this.oAuthSAImpersonationEmail != null) { + targetDataSource.oAuthSAImpersonationEmail = this.oAuthSAImpersonationEmail; + } + if (this.oAuthSAImpersonationChain != null) { + targetDataSource.oAuthSAImpersonationChain = this.oAuthSAImpersonationChain; + } + if (this.oAuthSAImpersonationScopes != null) { + targetDataSource.oAuthSAImpersonationScopes = this.oAuthSAImpersonationScopes; + } + if (this.oAuthSAImpersonationTokenLifetime != null) { + targetDataSource.oAuthSAImpersonationTokenLifetime = this.oAuthSAImpersonationTokenLifetime; + } + if (this.oAuth2TokenUri != null) { + targetDataSource.oAuth2TokenUri = this.oAuth2TokenUri; + } + if (this.byoidAudienceUri != null) { + targetDataSource.byoidAudienceUri = this.byoidAudienceUri; + } + if (this.byoidCredentialSource != null) { + targetDataSource.byoidCredentialSource = this.byoidCredentialSource; + } + if (this.byoidPoolUserProject != null) { + targetDataSource.byoidPoolUserProject = this.byoidPoolUserProject; + } + if (this.byoidSAImpersonationUri != null) { + targetDataSource.byoidSAImpersonationUri = this.byoidSAImpersonationUri; + } + if (this.byoidSubjectTokenType != null) { + targetDataSource.byoidSubjectTokenType = this.byoidSubjectTokenType; + } + if (this.byoidTokenUri != null) { + targetDataSource.byoidTokenUri = this.byoidTokenUri; + } + if (this.endpointOverrides != null) { + targetDataSource.endpointOverrides = this.endpointOverrides; + } + if (this.privateServiceConnect != null) { + targetDataSource.privateServiceConnect = this.privateServiceConnect; + } + if (this.connectionPoolSize != null) { + targetDataSource.connectionPoolSize = this.connectionPoolSize; + } + if (this.listenerPoolSize != null) { + targetDataSource.listenerPoolSize = this.listenerPoolSize; + } + if (this.enableGcpTraceExporter != null) { + targetDataSource.enableGcpTraceExporter = this.enableGcpTraceExporter; + } + if (this.enableGcpLogExporter != null) { + targetDataSource.enableGcpLogExporter = this.enableGcpLogExporter; } - Properties props = createProperties(); if (this.customOpenTelemetry != null) { - props.put("customOpenTelemetry", this.customOpenTelemetry); + targetDataSource.customOpenTelemetry = this.customOpenTelemetry; + } + if (this.useGlobalOpenTelemetry != null) { + targetDataSource.useGlobalOpenTelemetry = this.useGlobalOpenTelemetry; + } + if (this.enableDiagnosticTelemetry != null) { + targetDataSource.enableDiagnosticTelemetry = this.enableDiagnosticTelemetry; + } + if (this.enableGraphMetadata != null) { + targetDataSource.enableGraphMetadata = this.enableGraphMetadata; } - return DriverManager.getConnection(getURL(), props); } Properties createProperties() { @@ -730,17 +1004,17 @@ Properties createProperties() { BigQueryJdbcUrlUtility.LISTENER_POOL_SIZE_PROPERTY_NAME, String.valueOf(this.listenerPoolSize)); } - if (this.enableGcpTraceExporter) { + if (this.enableGcpTraceExporter != null) { connectionProperties.setProperty( BigQueryJdbcUrlUtility.ENABLE_GCP_TRACE_EXPORTER_PROPERTY_NAME, String.valueOf(this.enableGcpTraceExporter)); } - if (this.enableGcpLogExporter) { + if (this.enableGcpLogExporter != null) { connectionProperties.setProperty( BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME, String.valueOf(this.enableGcpLogExporter)); } - if (this.useGlobalOpenTelemetry) { + if (this.useGlobalOpenTelemetry != null) { connectionProperties.setProperty( BigQueryJdbcUrlUtility.USE_GLOBAL_OTEL_PROPERTY_NAME, String.valueOf(this.useGlobalOpenTelemetry)); @@ -750,9 +1024,11 @@ Properties createProperties() { BigQueryJdbcUrlUtility.ENABLE_GRAPH_METADATA_PROPERTY_NAME, String.valueOf(this.enableGraphMetadata)); } - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, - String.valueOf(getEnableDiagnosticTelemetry())); + if (this.enableDiagnosticTelemetry != null) { + connectionProperties.setProperty( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, + String.valueOf(this.enableDiagnosticTelemetry)); + } return connectionProperties; } @@ -887,7 +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/BigQueryDriverTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java index dde6b644e1e6..7fd63e0f8b58 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 @@ -338,7 +338,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 +413,91 @@ 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", "0"); + 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(urlLogDir)).isFalse(); + assertThat(TelemetryManager.isInitialized()).isTrue(); + } + + @Test + public void testConnect_rejectsPropertiesKeyInjectionAndFormatsPartnerToken() + 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"); + Assertions.assertThrows( + BigQueryJdbcException.class, + () -> bigQueryDriver.connect(baseConnectionUrl, semicolonInjectedProperties)); + + Properties equalsInjectedProperties = new Properties(); + equalsInjectedProperties.setProperty( + "EndpointOverrides=BIGQUERY=https://127.0.0.1:8443,DUMMY", "1"); + Assertions.assertThrows( + BigQueryJdbcException.class, + () -> bigQueryDriver.connect(baseConnectionUrl, equalsInjectedProperties)); + + Properties partnerTokenProperties = new Properties(); + partnerTokenProperties.setProperty("PartnerToken", "(GPN:acme_partner; prod)"); + try (Connection connection = + bigQueryDriver.connect(baseConnectionUrl, partnerTokenProperties)) { + BigQueryConnection bigQueryConnection = connection.unwrap(BigQueryConnection.class); + assertThat(bigQueryConnection.getPartnerToken()).isEqualTo(" (GPN:acme_partner; prod)"); + } + + // Properties with parent defaults: direct child entries (both non-String and case-variant + // keys) must deterministically override inherited defaults while preserving unoverridden ones. + Properties defaultProperties = new Properties(); + defaultProperties.setProperty("location", "US"); + defaultProperties.setProperty("MaxResults", "100"); + defaultProperties.setProperty("RequestReason", "default-reason"); + Properties childProperties = new Properties(defaultProperties); + childProperties.setProperty("Location", "EU"); + childProperties.put("MaxResults", 250); + childProperties.setProperty("PartnerToken", "(GPN:partner%20name)"); + try (Connection connection = bigQueryDriver.connect(baseConnectionUrl, childProperties)) { + BigQueryConnection bigQueryConnection = connection.unwrap(BigQueryConnection.class); + assertThat(bigQueryConnection.getLocation()).isEqualTo("EU"); + assertThat(bigQueryConnection.getMaxResults()).isEqualTo(250L); + assertThat(bigQueryConnection.requestReason).isEqualTo("default-reason"); + assertThat(bigQueryConnection.getPartnerToken()).isEqualTo(" (GPN:partner%20name)"); + } + + // Invalid boolean and enum-style integer properties must surface as BigQueryJdbcException + // (SQLException) rather than escaping connect() as an unchecked IllegalArgumentException. + Properties invalidBooleanProperties = new Properties(); + invalidBooleanProperties.setProperty("EnableHighThroughputAPI", "maybe"); + Assertions.assertThrows( + BigQueryJdbcException.class, + () -> bigQueryDriver.connect(baseConnectionUrl, invalidBooleanProperties)); + + Properties invalidJobCreationModeProperties = new Properties(); + invalidJobCreationModeProperties.setProperty("JobCreationMode", "99"); + Assertions.assertThrows( + BigQueryJdbcException.class, + () -> bigQueryDriver.connect(baseConnectionUrl, invalidJobCreationModeProperties)); + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/DataSourceTest.java index 6cccb0e19b7f..8e15287937c6 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,192 @@ 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_invalidUrlExceptionRedactsSecrets() { + DataSource dataSource = new DataSource(); + dataSource.setURL( + "bigquery://https://localhost:443;ProjectId=p;OAuthType=2;" + + "OAuthAccessToken=SUPER_SECRET_INVALID_URL_TOKEN"); + + BigQueryJdbcException invalidUrlException = + assertThrows(BigQueryJdbcException.class, dataSource::getConnection); + assertFalse(invalidUrlException.getMessage().contains("SUPER_SECRET_INVALID_URL_TOKEN")); + } + + @Test + public void testSnapshotConfiguredFields_coversEveryNonUrlDataSourceField() throws Exception { + DataSource populatedDataSource = new DataSource(); + int populatedFieldCount = 0; + for (Field field : DataSource.class.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || "URL".equals(field.getName())) { + continue; + } + field.setAccessible(true); + Class fieldType = field.getType(); + Object sampleValue; + if (fieldType == String.class) { + sampleValue = + "partnerToken".equals(field.getName()) + ? "(GPN:test_partner)" + : "val_" + field.getName(); + } else if (fieldType == Boolean.class) { + sampleValue = Boolean.FALSE; + } else if (fieldType == Integer.class) { + sampleValue = 42; + } else if (fieldType == Long.class) { + sampleValue = 99L; + } else if (fieldType == Map.class) { + sampleValue = ImmutableMap.of("k", "v"); + } else if (fieldType == OpenTelemetry.class) { + sampleValue = OpenTelemetry.noop(); + } else { + throw new AssertionError( + "Unhandled DataSource field type for " + field.getName() + ": " + fieldType); + } + field.set(populatedDataSource, sampleValue); + populatedFieldCount++; + } + + DataSource copiedSnapshot = populatedDataSource.snapshotConfiguredFields(); + assertTrue(populatedFieldCount >= 80); + for (Field field : DataSource.class.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || "URL".equals(field.getName())) { + continue; + } + field.setAccessible(true); + Object copiedFieldValue = field.get(copiedSnapshot); + assertEquals( + field.get(populatedDataSource), + copiedFieldValue, + "DataSource.applyConfiguredFieldsTo missed field: " + field.getName()); + } + } + + @Test + public void testGetConnection_partnerTokenOverlayParityAndNoDoubleDecode() throws SQLException { + String urlWithPartnerToken = + BigQueryJdbcBaseTest.getUriOAuthToken() + .append("ProjectId", "partner-proj") + .append("PartnerToken", "(GPN:url_partner)") + .toString(); + + DataSource invalidPartnerTokenDataSource = new DataSource(); + invalidPartnerTokenDataSource.setURL(urlWithPartnerToken); + invalidPartnerTokenDataSource.setPartnerToken("(env)"); + try (Connection connection = invalidPartnerTokenDataSource.getConnection()) { + BigQueryConnection bigQueryConnection = connection.unwrap(BigQueryConnection.class); + assertNull(bigQueryConnection.getPartnerToken()); + } + + DataSource literalPercentDataSource = new DataSource(); + literalPercentDataSource.setURL(urlWithPartnerToken); + literalPercentDataSource.setPartnerToken("(GPN:partner%20name)"); + try (Connection connection = literalPercentDataSource.getConnection()) { + BigQueryConnection bigQueryConnection = connection.unwrap(BigQueryConnection.class); + assertEquals(" (GPN:partner%20name)", bigQueryConnection.getPartnerToken()); + } + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSourceTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSourceTest.java index a486d28ecd7b..8d6333ad5064 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSourceTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PooledConnectionDataSourceTest.java @@ -27,12 +27,15 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import com.google.cloud.bigquery.ConnectionProperty; import com.google.cloud.bigquery.exception.BigQueryJdbcException; import com.google.cloud.bigquery.jdbc.utils.TestUtilities.TestConnectionListener; +import com.google.common.collect.ImmutableMap; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; @@ -417,4 +420,35 @@ public void testStandalonePooledConnectionListenerOnDataSourceConnection_closesO pc2.close(); } } + + @Test + public void testGetPooledConnection_preservesSecurityPropertiesAndTypedMaps() + throws SQLException { + PooledConnectionDataSource pooledDataSource = new PooledConnectionDataSource(); + pooledDataSource.setURL(buildTestUrl(4L, 10L)); + pooledDataSource.setEndpointOverrides("BIGQUERY=https://psc.internal.example.com"); + pooledDataSource.setGcpTelemetryProjectId("audit-telemetry-proj"); + pooledDataSource.setQueryProperties( + ImmutableMap.of( + "dataset_project_id", "tenant_a", "time_zone", "UTC,session_id=VICTIM_SID")); + pooledDataSource.setLabels(ImmutableMap.of("tenant", "tenant_a", "note", "ok,tenant=tenant_b")); + + PooledConnection pooledConnection = pooledDataSource.getPooledConnection(); + try (Connection connection = pooledConnection.getConnection()) { + BigQueryConnection physicalConnection = connection.unwrap(BigQueryConnection.class); + assertEquals( + "https://psc.internal.example.com", + physicalConnection.overrideProperties.get( + BigQueryJdbcUrlUtility.BIGQUERY_ENDPOINT_OVERRIDE_PROPERTY_NAME)); + assertEquals("audit-telemetry-proj", physicalConnection.gcpTelemetryProjectId); + List queryProperties = physicalConnection.getQueryProperties(); + assertEquals(2, queryProperties.size()); + assertNull(physicalConnection.getSessionInfoConnectionProperty()); + Map labels = physicalConnection.getLabels(); + assertEquals("tenant_a", labels.get("tenant")); + assertEquals("ok,tenant=tenant_b", labels.get("note")); + } finally { + pooledConnection.close(); + } + } } From 2033143ba1d22b5fb69ed91569a85fcdeb1a5d5b Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 30 Nov 2026 12:36:50 -0500 Subject: [PATCH 03/15] fix(bigquery-jdbc): redact DatabaseMetaData.getURL and getPropertyInfo and remove legacy URL round-trip helpers Stack: PR 3 of 3 (base: fix/g01-structured-connect-and-datasource-overrides) Bug: b/584839495 - Sanitize BigQueryConnection.connectionUrl via sanitizeUrlForDisplay() on all entry points so DatabaseMetaData.getURL() omits non-allowlisted URL params and never exposes out-of-band secrets. - Rewire BigQueryDriver.getPropertyInfo() onto structured URL + validated Properties merge, guard null/short/non-BigQuery URLs, and return null for non-allowlisted secret properties. - Replace DataSource.createProperties() in Level.CONFIG logging with DataSource.toMaskedLogMap() covering all configured fields. - Remove unused legacy helpers appendPropertiesToURL(), parseUriPropertyWithoutValidation(), DataSource.createProperties(), and DataSource.serializeMap(). - Document explicit G01 decisions inline on DatabaseMetaData.getURL(), BigQueryDriver.getPropertyInfo(), and BigQueryConnection.getAuthProperties(). --- .../bigquery/jdbc/BigQueryConnection.java | 16 +- .../jdbc/BigQueryDatabaseMetaData.java | 2 + .../cloud/bigquery/jdbc/BigQueryDriver.java | 49 +- .../bigquery/jdbc/BigQueryJdbcUrlUtility.java | 68 -- .../cloud/bigquery/jdbc/DataSource.java | 585 +++++++++--------- .../bigquery/jdbc/BigQueryConnectionTest.java | 85 +++ .../bigquery/jdbc/BigQueryDriverTest.java | 59 ++ .../jdbc/BigQueryJdbcUrlUtilityTest.java | 131 ++-- 8 files changed, 533 insertions(+), 462 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java index b5ae8b24bafb..8d77f140ed9e 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java @@ -346,15 +346,12 @@ static String maskPropertyValue(String key, Object value) { ExecutorService createdQueryExecutor = null; ExecutorService createdMetadataExecutor = null; try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(this.connectionId)) { - this.connectionUrl = url; + // Omit non-allowlisted URL parameters so DatabaseMetaData.getURL() never exposes plaintext + // secrets regardless of whether the connection was created via Driver, DataSource, or direct + // constructor. + this.connectionUrl = BigQueryJdbcUrlUtility.sanitizeUrlForDisplay(url); if (LOG.isLoggable(Level.CONFIG)) { - Properties connectionProps = ds.createProperties(); - Properties maskedProps = new Properties(); - for (String name : connectionProps.stringPropertyNames()) { - maskedProps.setProperty( - sanitizeForLog(name), maskPropertyValue(name, connectionProps.getProperty(name))); - } - LOG.config("Connection properties: %s", maskedProps.toString()); + LOG.config("Connection properties: %s", ds.toMaskedLogMap().toString()); } this.openStatements = ConcurrentHashMap.newKeySet(); this.autoCommit = true; @@ -765,6 +762,9 @@ public String getLocation() throws BigQueryJdbcException { return this.location; } + // Public signature intentionally kept unchanged for G01 to preserve API/binary compatibility + // (api-lifecycle) and existing integration test callers (ITPSCBigQueryTest, + // ITUniverseDomainBigQueryTest). public Map getAuthProperties() throws BigQueryJdbcException { checkClosed(); return this.authProperties; diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java index fcd6c4c5296f..defc1dca1f1a 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java @@ -192,6 +192,8 @@ public boolean allTablesAreSelectable() { @Override public String getURL() { + // Returns a sanitized jdbc:bigquery: URL with all non-allowlisted (!SAFE_TO_LOG_PROPERTIES) + // URL parameters omitted and out-of-band Properties/DataSource credentials excluded. return this.URL; } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java index d832289127dc..ac589458eac8 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java @@ -476,28 +476,53 @@ public boolean acceptsURL(String url) throws SQLException { @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) { LOG.finest("++enter++"); - String connectionUri = - BigQueryJdbcUrlUtility.appendPropertiesToURL(url.substring(5), this.toString(), info); - List propertyInfoList = new ArrayList<>(); + if (url == null || !url.startsWith("jdbc:bigquery:")) { + return new DriverPropertyInfo[0]; + } + BigQueryJdbcUrlUtility.ParsedConnectionUrl parsedUrl = + BigQueryJdbcUrlUtility.parseConnectionUrl(url); + Map mergedConnectionProperties = + new LinkedHashMap<>(parsedUrl.validateAndGetProperties()); + ValidatedConnectionProperties propertiesOverrides = validateAndCanonicalizeProperties(info); + mergedConnectionProperties.putAll(propertiesOverrides.canonicalProperties); - for (BigQueryConnectionProperty prop : BigQueryJdbcUrlUtility.VALID_PROPERTIES) { + List propertyInfoList = new ArrayList<>(); + for (BigQueryConnectionProperty connectionProperty : BigQueryJdbcUrlUtility.VALID_PROPERTIES) { + String propertyName = connectionProperty.getName(); DriverPropertyInfo driverProperty = new DriverPropertyInfo( - prop.getName(), - BigQueryJdbcUrlUtility.parseUriProperty(connectionUri, prop.getName())); - driverProperty.description = prop.getDescription(); + propertyName, + redactPropertyInfoValue(propertyName, mergedConnectionProperties.get(propertyName))); + driverProperty.description = connectionProperty.getDescription(); propertyInfoList.add(driverProperty); } - DataSource ds = DataSource.fromUrl(connectionUri); - Map oAuthProperties = - BigQueryJdbcOAuthUtility.parseOAuthProperties(ds, this.toString()); - for (Map.Entry authProperty : oAuthProperties.entrySet()) { - propertyInfoList.add(new DriverPropertyInfo(authProperty.getKey(), authProperty.getValue())); + if (mergedConnectionProperties.containsKey(BigQueryJdbcUrlUtility.OAUTH_TYPE_PROPERTY_NAME)) { + DataSource parsedDataSource = + DataSource.fromCanonicalProperties( + parsedUrl.toSanitizedDisplayUrl(), mergedConnectionProperties); + Map oAuthProperties = + BigQueryJdbcOAuthUtility.parseOAuthProperties(parsedDataSource, this.toString()); + for (Map.Entry authProperty : oAuthProperties.entrySet()) { + propertyInfoList.add( + new DriverPropertyInfo( + authProperty.getKey(), + redactPropertyInfoValue(authProperty.getKey(), authProperty.getValue()))); + } } return propertyInfoList.toArray(new DriverPropertyInfo[0]); } + private static String redactPropertyInfoValue(String propertyName, String propertyValue) { + // Return null (per JDBC Driver.getPropertyInfo contract) for non-allowlisted secret properties + // rather than plaintext or "*****", preventing credential disclosure and ensuring GUI/BI tools + // never resubmit a masked placeholder as a live credential. + if (!BigQueryConnection.isSafeToLogProperty(propertyName)) { + return null; + } + return propertyValue; + } + @Override public int getMajorVersion() { LOG.finest("++enter++"); diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java index d7eae3c65219..5fdc7cdcab80 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java @@ -23,7 +23,6 @@ import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryPropertyUtility; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; -import com.google.common.net.UrlEscapers; import java.security.KeyStore; import java.util.ArrayList; import java.util.Arrays; @@ -35,7 +34,6 @@ import java.util.Locale; import java.util.Map; import java.util.Map.Entry; -import java.util.Properties; import java.util.Set; import java.util.logging.Level; import java.util.regex.Matcher; @@ -746,37 +744,6 @@ static String parseUriProperty(String uri, String property) { return map.get(property); } - /** - * Parses a URI property from the given URI without validating any other properties. - * - * @param uri The URI to parse. - * @param property The name of the property to parse. - * @return The String value of the property, or null if the property is not found. - */ - static String parseUriPropertyWithoutValidation(String uri, String property) { - if (uri == null) { - return null; - } - int start = 0; - int len = uri.length(); - while (start < len) { - int nextSemi = uri.indexOf(';', start); - int end = (nextSemi == -1) ? len : nextSemi; - - int eqIndex = uri.indexOf('=', start); - if (eqIndex > start && eqIndex < end) { - String key = uri.substring(start, eqIndex).trim(); - if (key.equalsIgnoreCase(property)) { - String value = uri.substring(eqIndex + 1, end); - return CharEscapers.decodeUriPath(value.replace("+", "%2B")); - } - } - - start = end + 1; - } - return null; - } - /** * Immutable result of a single-pass, non-throwing parse of a BigQuery JDBC connection URL. * @@ -1121,41 +1088,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 = validatePropertyKey(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; 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 1ae9d6cda6f1..d1c79071769d 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,15 +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.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; @@ -741,302 +740,296 @@ void applyConfiguredFieldsTo(DataSource targetDataSource) { } } - Properties createProperties() { - Properties connectionProperties = new Properties(); - if (this.projectId != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.PROJECT_ID_PROPERTY_NAME, this.projectId); - } - if (this.defaultDataset != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.DEFAULT_DATASET_PROPERTY_NAME, this.defaultDataset); - } - if (this.location != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.LOCATION_PROPERTY_NAME, this.location); - } - if (this.enableHighThroughputAPI != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_HTAPI_PROPERTY_NAME, - String.valueOf(this.enableHighThroughputAPI)); - } - if (this.unsupportedHTAPIFallback != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.UNSUPPORTED_HTAPI_FALLBACK_PROPERTY_NAME, - String.valueOf(this.unsupportedHTAPIFallback)); - } - if (this.highThroughputMinTableSize != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.HTAPI_MIN_TABLE_SIZE_PROPERTY_NAME, - String.valueOf(this.highThroughputMinTableSize)); - } - if (this.highThroughputActivationRatio != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.HTAPI_ACTIVATION_RATIO_PROPERTY_NAME, - String.valueOf(this.highThroughputActivationRatio)); - } - if (this.kmsKeyName != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.KMS_KEY_NAME_PROPERTY_NAME, this.kmsKeyName); - } - if (this.queryProperties != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.QUERY_PROPERTIES_NAME, serializeMap(this.queryProperties)); - } - if (this.enableSession != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_SESSION_PROPERTY_NAME, String.valueOf(this.enableSession)); - } - if (this.enableTimestampPicos != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_TIMESTAMP_PICOS_PROPERTY_NAME, - String.valueOf(this.enableTimestampPicos)); - } - if (this.logLevel != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.LOG_LEVEL_PROPERTY_NAME, this.logLevel); - } - if (this.logPath != null) { - connectionProperties.setProperty(BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME, this.logPath); - } - if (this.oAuthType != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_TYPE_PROPERTY_NAME, String.valueOf(this.oAuthType)); - } - if (this.oAuthServiceAcctEmail != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_SA_EMAIL_PROPERTY_NAME, this.oAuthServiceAcctEmail); - } - if (this.oAuthPvtKeyPath != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PATH_PROPERTY_NAME, this.oAuthPvtKeyPath); - } - if (this.oAuthPvtKey != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PROPERTY_NAME, this.oAuthPvtKey); - } - if (this.oAuthAccessToken != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_ACCESS_TOKEN_PROPERTY_NAME, this.oAuthAccessToken); - } - if (this.oAuthAccessTokenReadonly != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_ACCESS_TOKEN_READONLY_PROPERTY_NAME, - String.valueOf(this.oAuthAccessTokenReadonly)); - } - if (this.oAuthRefreshToken != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_REFRESH_TOKEN_PROPERTY_NAME, this.oAuthRefreshToken); - } - if (this.useQueryCache != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.USE_QUERY_CACHE_PROPERTY_NAME, String.valueOf(this.useQueryCache)); - } - if (this.queryDialect != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.QUERY_DIALECT_PROPERTY_NAME, this.queryDialect); - } - if (this.allowLargeResults != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ALLOW_LARGE_RESULTS_PROPERTY_NAME, - String.valueOf(this.allowLargeResults)); - } - if (this.destinationTable != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.LARGE_RESULTS_TABLE_PROPERTY_NAME, this.destinationTable); - } - if (this.destinationDataset != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.LARGE_RESULTS_DATASET_PROPERTY_NAME, this.destinationDataset); - } - if (this.destinationDatasetExpirationTime != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.DESTINATION_DATASET_EXPIRATION_TIME_PROPERTY_NAME, - String.valueOf(this.destinationDatasetExpirationTime)); - } - if (this.universeDomain != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME, this.universeDomain); - } - if (this.proxyHost != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME, this.proxyHost); - } - if (this.proxyPort != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME, this.proxyPort); - } - if (this.proxyUid != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME, this.proxyUid); - } - if (this.proxyPwd != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME, this.proxyPwd); - } - if (this.oAuthClientId != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_CLIENT_ID_PROPERTY_NAME, this.oAuthClientId); - } - if (this.oAuthClientSecret != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.OAUTH_CLIENT_SECRET_PROPERTY_NAME, this.oAuthClientSecret); - } - if (this.jobCreationMode != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.JOB_CREATION_MODE_PROPERTY_NAME, - String.valueOf(this.jobCreationMode)); - } - if (this.maxResults != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.MAX_RESULTS_PROPERTY_NAME, String.valueOf(this.maxResults)); - } + /** + * 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()) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.PARTNER_TOKEN_PROPERTY_NAME, this.partnerToken); - } - if (this.enableWriteAPI != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_WRITE_API_PROPERTY_NAME, - String.valueOf(this.enableWriteAPI)); - } - if (this.additionalProjects != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ADDITIONAL_PROJECTS_PROPERTY_NAME, this.additionalProjects); - } - if (this.filterTablesOnDefaultDataset != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.FILTER_TABLES_ON_DEFAULT_DATASET_PROPERTY_NAME, - String.valueOf(this.filterTablesOnDefaultDataset)); - } - if (this.enableProjectDiscovery != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_PROJECT_DISCOVERY_PROPERTY_NAME, - String.valueOf(this.enableProjectDiscovery)); - } - if (this.requestGoogleDriveScope != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.REQUEST_GOOGLE_DRIVE_SCOPE_PROPERTY_NAME, - String.valueOf(this.requestGoogleDriveScope)); - } - if (this.metadataFetchThreadCount != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.METADATA_FETCH_THREAD_COUNT_PROPERTY_NAME, - String.valueOf(this.metadataFetchThreadCount)); - } - - if (this.sslTrustStorePath != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PROPERTY_NAME, - String.valueOf(this.sslTrustStorePath)); - } - if (this.sslTrustStorePassword != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PWD_PROPERTY_NAME, - String.valueOf(this.sslTrustStorePassword)); - } - if (this.sslTrustStoreType != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.SSL_TRUST_STORE_TYPE_PROPERTY_NAME, this.sslTrustStoreType); - } - if (this.sslTrustStoreProvider != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PROVIDER_PROPERTY_NAME, - this.sslTrustStoreProvider); - } - if (this.labels != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.LABELS_PROPERTY_NAME, serializeMap(this.labels)); - } - if (this.requestReason != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.REQUEST_REASON_PROPERTY_NAME, this.requestReason); - } - if (this.timeout != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.RETRY_TIMEOUT_IN_SECS_PROPERTY_NAME, String.valueOf(this.timeout)); - } - if (this.jobTimeout != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.JOB_TIMEOUT_PROPERTY_NAME, String.valueOf(this.jobTimeout)); - } - if (this.retryInitialDelay != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.RETRY_INITIAL_DELAY_PROPERTY_NAME, - String.valueOf(this.retryInitialDelay)); - } - if (this.retryMaxDelay != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.RETRY_MAX_DELAY_PROPERTY_NAME, String.valueOf(this.retryMaxDelay)); - } - if (this.httpConnectTimeout != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.HTTP_CONNECT_TIMEOUT_PROPERTY_NAME, - String.valueOf(this.httpConnectTimeout)); - } - if (this.httpReadTimeout != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.HTTP_READ_TIMEOUT_PROPERTY_NAME, - String.valueOf(this.httpReadTimeout)); - } - if (this.maximumBytesBilled != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.MAX_BYTES_BILLED_PROPERTY_NAME, - String.valueOf(this.maximumBytesBilled)); - } - if (this.swaActivationRowCount != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.SWA_ACTIVATION_ROW_COUNT_PROPERTY_NAME, - String.valueOf(this.swaActivationRowCount)); - } - if (this.swaAppendRowCount != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.SWA_APPEND_ROW_COUNT_PROPERTY_NAME, - String.valueOf(this.swaAppendRowCount)); - } - if (this.connectionPoolSize != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.CONNECTION_POOL_SIZE_PROPERTY_NAME, - String.valueOf(this.connectionPoolSize)); - } - if (this.listenerPoolSize != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.LISTENER_POOL_SIZE_PROPERTY_NAME, - String.valueOf(this.listenerPoolSize)); - } - if (this.enableGcpTraceExporter != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_GCP_TRACE_EXPORTER_PROPERTY_NAME, - String.valueOf(this.enableGcpTraceExporter)); - } - if (this.enableGcpLogExporter != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME, - String.valueOf(this.enableGcpLogExporter)); - } - if (this.useGlobalOpenTelemetry != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.USE_GLOBAL_OTEL_PROPERTY_NAME, - String.valueOf(this.useGlobalOpenTelemetry)); - } - if (this.enableGraphMetadata != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_GRAPH_METADATA_PROPERTY_NAME, - String.valueOf(this.enableGraphMetadata)); - } - if (this.enableDiagnosticTelemetry != null) { - connectionProperties.setProperty( - BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, - String.valueOf(this.enableDiagnosticTelemetry)); - } - return connectionProperties; - } - - private String serializeMap(Map map) { - if (map == null || map.isEmpty()) { - return ""; + 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, + this.enableDiagnosticTelemetry); + return maskedProperties; + } + + 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 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..41ed89b5190d 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,89 @@ 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(); + assertTrue(metadataUrl.startsWith("jdbc:bigquery://")); + assertTrue(metadataUrl.contains("ProjectId=proj-meta")); + 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(); + assertTrue(metadataUrl.startsWith("jdbc:bigquery://")); + assertTrue(metadataUrl.contains("ProjectId=proj-ds")); + 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(); + assertTrue(metadataUrl.startsWith("jdbc:bigquery://")); + assertTrue(metadataUrl.contains("ProjectId=proj-direct")); + 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 7fd63e0f8b58..937a702af077 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 @@ -500,4 +500,63 @@ public void testConnect_rejectsPropertiesKeyInjectionAndFormatsPartnerToken() BigQueryJdbcException.class, () -> bigQueryDriver.connect(baseConnectionUrl, invalidJobCreationModeProperties)); } + + @Test + public void testGetPropertyInfo_returnsNullForSecretsAndHandlesInvalidUrls() { + 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 must also be rejected. + Properties injectedKeyProperties = new Properties(); + injectedKeyProperties.setProperty( + "custom=1;EndpointOverrides", "BIGQUERY=https://127.0.0.1:8443"); + Assertions.assertThrows( + BigQueryJdbcRuntimeException.class, + () -> bigQueryDriver.getPropertyInfo(connectionUrl, injectedKeyProperties)); + } } 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 8f7fe6ef7783..d265364968f5 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 @@ -107,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"); + public void + testValidateAndCanonicalizeProperties_preservesDiscretePropertiesWithoutUrlMutation() { + Properties callerProperties = new Properties(); + callerProperties.setProperty("OAuthType", "3"); - String updatedUrl = BigQueryJdbcUrlUtility.appendPropertiesToURL(url, null, properties); - assertThat(updatedUrl.contains("OAuthType=3")); + BigQueryDriver.ValidatedConnectionProperties validatedProperties = + BigQueryDriver.validateAndCanonicalizeProperties(callerProperties); + assertThat(validatedProperties.canonicalProperties.get("OAuthType")).isEqualTo("3"); } @Test @@ -205,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); + public void + testValidateAndCanonicalizeProperties_propertyWithSemicolon_doesNotInjectSiblingProperty() { + Properties callerProperties = new Properties(); + String valueWithSemicolon = "value;ExtraProperty=injection"; + callerProperties.setProperty("ProjectId", valueWithSemicolon); - Map parsedProperties = BigQueryJdbcUrlUtility.parseUrl(updatedUrl); + BigQueryDriver.ValidatedConnectionProperties validatedProperties = + BigQueryDriver.validateAndCanonicalizeProperties(callerProperties); - assertThat(parsedProperties.get("ProjectId")).isEqualTo(complexValue); - assertFalse(parsedProperties.containsKey("ExtraProperty")); + assertThat(validatedProperties.canonicalProperties.get("ProjectId")) + .isEqualTo(valueWithSemicolon); + assertFalse(validatedProperties.canonicalProperties.containsKey("ExtraProperty")); } @Test @@ -389,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"; @@ -411,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"; @@ -437,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); + public void testValidateAndCanonicalizeProperties_handlesNullAndNonStringProperties() { + assertThat(BigQueryDriver.validateAndCanonicalizeProperties(null).canonicalProperties) + .isEmpty(); + assertThat( + BigQueryDriver.validateAndCanonicalizeProperties(new Properties()).canonicalProperties) + .isEmpty(); - Properties nonStringProps = new Properties(); - nonStringProps.put("MaxResults", 500); - nonStringProps.put("OAuthAccessToken", 123456); - capturedLogs.clear(); + Properties nonStringProperties = new Properties(); + nonStringProperties.put("MaxResults", 500); + nonStringProperties.put("OAuthAccessToken", 123456); - 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(); + 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(); } @@ -480,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??"); @@ -491,21 +472,15 @@ public void testSanitizeControlCharactersAndCaseInsensitiveSafeProperties() { assertThat(BigQueryConnection.maskPropertyValue("oauthaccesstoken", "tok\nen")) .isEqualTo("*****"); - 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("CustomUnknownKey", "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 CustomUnknownKey with value ***** to URL")).isTrue(); - for (LogRecord rec : capturedLogs) { - assertThat(rec.getMessage()).doesNotContain("\n"); - assertThat(rec.getMessage()).doesNotContain("\r"); + 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 rejected outright. @@ -513,8 +488,7 @@ public void testSanitizeControlCharactersAndCaseInsensitiveSafeProperties() { controlKeyProperties.setProperty("Custom\nKey", "secret-val"); assertThrows( BigQueryJdbcRuntimeException.class, - () -> - BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", controlKeyProperties)); + () -> BigQueryDriver.validateAndCanonicalizeProperties(controlKeyProperties)); } @ParameterizedTest @@ -529,14 +503,15 @@ public void testSanitizeControlCharactersAndCaseInsensitiveSafeProperties() { "TrailingSpace ", "" }) - public void testAppendPropertiesToURL_rejectsInvalidPropertyKeys(String invalidKey) { - String baseUrl = "bigquery://https://www.googleapis.com/bigquery/v2:443;ProjectId=locked"; + public void testValidatePropertyKey_rejectsInvalidPropertyKeys(String invalidKey) { + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> BigQueryJdbcUrlUtility.validatePropertyKey(invalidKey)); Properties invalidProperties = new Properties(); invalidProperties.setProperty(invalidKey, "val"); - assertThrows( BigQueryJdbcRuntimeException.class, - () -> BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", invalidProperties)); + () -> BigQueryDriver.validateAndCanonicalizeProperties(invalidProperties)); } @Test From 6aa7c4f74d0152f8b9c54bc435aea999729f7f31 Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 30 Nov 2026 16:00:41 -0500 Subject: [PATCH 04/15] fix(bigquery-jdbc): use Locale.ROOT for property lookup and harden URL/PartnerToken/map parsing --- .../bigquery/jdbc/BigQueryJdbcUrlUtility.java | 33 ++++++++++++------- .../jdbc/BigQueryJdbcUrlUtilityTest.java | 27 ++++++++++++++- 2 files changed, 47 insertions(+), 13 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java index d7eae3c65219..a9ef6c42303c 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java @@ -709,22 +709,22 @@ final class BigQueryJdbcUrlUtility { static { Map map = new HashMap<>(); for (BigQueryConnectionProperty p : VALID_PROPERTIES) { - map.put(p.getName().toUpperCase(), p.getName()); + map.put(p.getName().toUpperCase(Locale.ROOT), p.getName()); } for (BigQueryConnectionProperty p : AUTH_PROPERTIES) { - map.put(p.getName().toUpperCase(), p.getName()); + map.put(p.getName().toUpperCase(Locale.ROOT), p.getName()); } for (BigQueryConnectionProperty p : PROXY_PROPERTIES) { - map.put(p.getName().toUpperCase(), p.getName()); + map.put(p.getName().toUpperCase(Locale.ROOT), p.getName()); } for (String p : OVERRIDE_PROPERTIES) { - map.put(p.toUpperCase(), p); + map.put(p.toUpperCase(Locale.ROOT), p); } for (String p : BYOID_PROPERTIES) { - map.put(p.toUpperCase(), p); + map.put(p.toUpperCase(Locale.ROOT), p); } for (String p : NETWORK_PROPERTIES) { - map.put(p.toUpperCase(), p); + map.put(p.toUpperCase(Locale.ROOT), p); } PROPERTY_NAME_MAP = Collections.unmodifiableMap(map); } @@ -740,8 +740,8 @@ private BigQueryJdbcUrlUtility() {} */ static String parseUriProperty(String uri, String property) { Map map = parseUrl(uri); - if (PROPERTY_NAME_MAP.containsKey(property.toUpperCase())) { - return map.get(PROPERTY_NAME_MAP.get(property.toUpperCase())); + if (PROPERTY_NAME_MAP.containsKey(property.toUpperCase(Locale.ROOT))) { + return map.get(PROPERTY_NAME_MAP.get(property.toUpperCase(Locale.ROOT))); } return map.get(property); } @@ -877,6 +877,12 @@ String toSanitizedDisplayUrl() { 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:"; + } if (allowlistedDisplayProperties.isEmpty()) { return normalizedUrlPrefix; } @@ -911,6 +917,9 @@ static String formatPartnerTokenHeaderValue(String partnerTokenValue) { (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 + ")"; } @@ -975,7 +984,7 @@ static ParsedConnectionUrl parseConnectionUrl(String connectionUrl) { if (BigQueryConnection.isSafeToLogProperty(PARTNER_TOKEN_PROPERTY_NAME)) { allowlistedDisplayProperties.put( PARTNER_TOKEN_PROPERTY_NAME, - BigQueryConnection.sanitizeForLog(formattedPartnerToken.trim())); + BigQueryConnection.sanitizeForLog(encodedPartnerToken.trim())); } } else { canonicalProperties.remove(PARTNER_TOKEN_PROPERTY_NAME); @@ -1004,7 +1013,7 @@ static ParsedConnectionUrl parseConnectionUrl(String connectionUrl) { segmentPosition++; int equalsIndex = segment.indexOf('='); - if (equalsIndex <= 0) { + if (equalsIndex <= 0 || segment.substring(0, equalsIndex).trim().isEmpty()) { malformedSegmentPositions.add(segmentPosition); continue; } @@ -1231,8 +1240,8 @@ static Map parsePropertiesMapFromValue( for (String keyValuePair : Splitter.on(",").split(propertiesString)) { List keyValueParts = Splitter.on("=").limit(2).splitToList(keyValuePair); if (keyValueParts.size() == 2) { - String entryKey = keyValueParts.get(0); - if (entryKey.trim().isEmpty()) { + String entryKey = keyValueParts.get(0).trim(); + if (entryKey.isEmpty()) { throw new BigQueryJdbcRuntimeException( String.format("Invalid empty key in %s.", propertyName)); } 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 8f7fe6ef7783..4ba4d73fdf75 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 @@ -579,6 +579,13 @@ public void testParsePropertiesMapFromValue_rejectsEmptyKeyAndExactDuplicateAndS "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. @@ -618,6 +625,11 @@ public void testParseConnectionUrl_twoPhaseLastWinsAndInvalidPercentEncodingWith 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. @@ -649,12 +661,17 @@ public void testSanitizeUrlForDisplay_omitsNonAllowlistedParamsAndNormalizesPref .isEqualTo( "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + "PartnerToken=(GPN:acme; prod);ProjectId=p2;OAuthType=2"); + assertThat( + BigQueryJdbcUrlUtility.sanitizeUrlForDisplay( + "jdbc:bigquery://h?OAuthAccessToken=x;ProjectId=p")) + .isEqualTo("jdbc:bigquery:;ProjectId=p"); } @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'. @@ -672,6 +689,12 @@ public void testFormatPartnerTokenHeaderValue_doesNotDoubleDecodeAndPreservesLit assertThat(parsedPartnerToken).isEqualTo(" (GPN:partner%20name;prod)"); assertThat(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue(parsedPartnerToken)) .isEqualTo(" (GPN:partner%20name;prod)"); + assertThat( + BigQueryJdbcUrlUtility.parseConnectionUrl( + BigQueryJdbcUrlUtility.sanitizeUrlForDisplay(encodedPartnerTokenUrl)) + .validateAndGetProperties() + .get(BigQueryJdbcUrlUtility.PARTNER_TOKEN_PROPERTY_NAME)) + .isEqualTo(" (GPN:partner%20name;prod)"); } @Test @@ -699,7 +722,9 @@ public void testSafeToLogProperties_exhaustivelyClassifiesEveryKnownProperty() { boolean isAllowlisted = BigQueryConnection.isSafeToLogProperty(canonicalPropertyName); boolean isExpectedNonAllowlisted = expectedNonAllowlistedProperties.contains(canonicalPropertyName); - assertThat(isAllowlisted ^ isExpectedNonAllowlisted).isTrue(); + assertFalse( + isAllowlisted == isExpectedNonAllowlisted, + "Unclassified property: " + canonicalPropertyName); } assertFalse(BigQueryConnection.isSafeToLogProperty(null)); assertFalse(BigQueryConnection.isSafeToLogProperty("UnknownCustomSecret")); From 8b4f6334761d8120d2736772b0af7897b1494de4 Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 30 Nov 2026 16:06:02 -0500 Subject: [PATCH 05/15] fix(bigquery-jdbc): snapshot caller Properties and ensure telemetry opt-out always wins --- .../cloud/bigquery/jdbc/BigQueryDriver.java | 60 +++++++++++++++---- .../bigquery/jdbc/BigQueryDriverTest.java | 58 +++++++++++++++++- 2 files changed, 103 insertions(+), 15 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java index d832289127dc..c2d9d19190e6 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java @@ -155,8 +155,9 @@ static ValidatedConnectionProperties validateAndCanonicalizeProperties( return new ValidatedConnectionProperties( Collections.emptyMap(), Collections.emptyList(), null); } + Properties propertiesSnapshot = (Properties) callerProperties.clone(); OpenTelemetry customOpenTelemetry = null; - Object customOpenTelemetryValue = callerProperties.get("customOpenTelemetry"); + Object customOpenTelemetryValue = propertiesSnapshot.get("customOpenTelemetry"); if (customOpenTelemetryValue instanceof OpenTelemetry) { customOpenTelemetry = (OpenTelemetry) customOpenTelemetryValue; } @@ -164,22 +165,23 @@ static ValidatedConnectionProperties validateAndCanonicalizeProperties( Map canonicalProperties = new LinkedHashMap<>(); List unknownPropertyKeys = new ArrayList<>(); - // Pass 1: record inherited String defaults that are not directly shadowed in callerProperties. - for (String defaultPropertyKey : callerProperties.stringPropertyNames()) { + // Pass 1: record inherited String defaults that are not directly shadowed in + // propertiesSnapshot. + for (String defaultPropertyKey : propertiesSnapshot.stringPropertyNames()) { if ("customOpenTelemetry".equals(defaultPropertyKey) - || callerProperties.containsKey(defaultPropertyKey)) { + || propertiesSnapshot.containsKey(defaultPropertyKey)) { continue; } String validatedPropertyKey = BigQueryJdbcUrlUtility.validatePropertyKey(defaultPropertyKey); - String defaultPropertyValue = callerProperties.getProperty(defaultPropertyKey); + String defaultPropertyValue = propertiesSnapshot.getProperty(defaultPropertyKey); recordValidatedProperty( validatedPropertyKey, defaultPropertyValue, canonicalProperties, unknownPropertyKeys); } - // Pass 2: overlay direct entries from callerProperties (both String and non-String values) so + // Pass 2: overlay direct entries from propertiesSnapshot (both String and non-String values) so // direct entries always win deterministically over inherited defaults, including case-variant // keys. - for (Map.Entry directPropertyEntry : callerProperties.entrySet()) { + for (Map.Entry directPropertyEntry : propertiesSnapshot.entrySet()) { Object directKeyObject = directPropertyEntry.getKey(); Object directValueObject = directPropertyEntry.getValue(); if ("customOpenTelemetry".equals(directKeyObject)) { @@ -221,12 +223,27 @@ private static void recordValidatedProperty( } } + private static boolean isTelemetryOptOut(String value) { + if (value == null) { + return false; + } + if ("false".equalsIgnoreCase(value)) { + return true; + } + try { + return Integer.parseInt(value) == 0; + } catch (NumberFormatException ignored) { + return false; + } + } + /** * Resolves a pre-connect ("bootstrap") setting—one of the four logging/telemetry properties * ({@code EnableDiagnosticTelemetry}, {@code LogLevel}, {@code LogPath}, {@code * enableGcpLogExporter}) that must be read before the pre-connect logger opens and before Phase 2 * URL validation throws—applying strict precedence: {@code DataSource} setter > caller {@link - * Properties} > URL parameter (last-wins). + * Properties} > URL parameter (last-wins). For {@code EnableDiagnosticTelemetry}, callers + * check {@link #isTelemetryOptOut(String)} across all sources first so an opt-out always wins. */ private static String resolvePreConnectProperty( String canonicalPropertyName, @@ -308,12 +325,26 @@ private Connection connectInternal( && dataSourceOverrides.getConfiguredEnableDiagnosticTelemetry() != null ? String.valueOf(dataSourceOverrides.getConfiguredEnableDiagnosticTelemetry()) : null; + String propertiesTelemetryFlag = + propertiesOverrides != null + ? propertiesOverrides.canonicalProperties.get( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME) + : null; + String urlTelemetryFlag = + parsedUrl.getPreConnectProperty( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME); + boolean telemetryOptOut = + isTelemetryOptOut(dataSourceTelemetryFlag) + || isTelemetryOptOut(propertiesTelemetryFlag) + || isTelemetryOptOut(urlTelemetryFlag); String diagnosticTelemetrySetting = - resolvePreConnectProperty( - BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, - dataSourceTelemetryFlag, - propertiesOverrides, - parsedUrl); + telemetryOptOut + ? "false" + : resolvePreConnectProperty( + BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, + dataSourceTelemetryFlag, + propertiesOverrides, + parsedUrl); Properties telemetryProperties = new Properties(); if (diagnosticTelemetrySetting != null) { telemetryProperties.setProperty( @@ -409,6 +440,9 @@ private Connection connectInternal( resolvedDataSource.setCustomOpenTelemetry(propertiesOverrides.customOpenTelemetry); } } + if (telemetryOptOut) { + resolvedDataSource.setEnableDiagnosticTelemetry(false); + } } catch (BigQueryJdbcRuntimeException | IllegalArgumentException e) { LOG.log(Level.SEVERE, "Failed to parse connection URL", e); throw new BigQueryJdbcException("Failed to parse connection URL", e); 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 7fd63e0f8b58..6aa79af241fb 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 @@ -429,7 +429,7 @@ public void testConnect_propertiesOverrideUrlPreConnectLogAndTelemetry(@TempDir .toString(); Properties overrideProperties = new Properties(); - overrideProperties.setProperty("LogLevel", "0"); + overrideProperties.setProperty("LogLevel", "3"); overrideProperties.setProperty("LogPath", overrideLogDir.toString()); overrideProperties.setProperty("EnableDiagnosticTelemetry", "1"); @@ -437,8 +437,62 @@ public void testConnect_propertiesOverrideUrlPreConnectLogAndTelemetry(@TempDir assertThat(connection).isNotNull(); assertThat(connection.isClosed()).isFalse(); } + assertThat(Files.exists(overrideLogDir)).isTrue(); assertThat(Files.exists(urlLogDir)).isFalse(); - assertThat(TelemetryManager.isInitialized()).isTrue(); + // 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 From 6abbc34fd2fbec2649562e82ef2111c860b4f358 Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 30 Nov 2026 16:09:54 -0500 Subject: [PATCH 06/15] fix(bigquery-jdbc): wrap getPropertyInfo parse errors in SQLException, guard toMaskedLogMap, and update USER_GUIDE --- java-bigquery-jdbc/docs/USER_GUIDE.md | 12 ++++++++++++ .../google/cloud/bigquery/jdbc/BigQueryDriver.java | 11 ++++++++++- .../cloud/bigquery/jdbc/BigQueryDriverTest.java | 6 +++--- .../google/cloud/bigquery/jdbc/DataSourceTest.java | 2 ++ 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index cb2f7cc28e92..8b30136077db 100644 --- a/java-bigquery-jdbc/docs/USER_GUIDE.md +++ b/java-bigquery-jdbc/docs/USER_GUIDE.md @@ -286,6 +286,18 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443" | `gcpTelemetryCredentials` | `null` | File path or raw JSON credentials string for OpenTelemetry GCP exporters. | | `useGlobalOpenTelemetry` | `false` | Instructs the driver to register with the global OpenTelemetry instance (`GlobalOpenTelemetry`) in the JVM environment. | +### Configuration precedence and credential handling + +- When a property is set in more than one place, `DataSource` setters win over + `Properties`, which win over the JDBC URL. An explicit + `EnableDiagnosticTelemetry` opt-out (`0` or `false`) in any source always wins. +- `DatabaseMetaData.getURL()` omits credentials and unknown properties, so it + cannot be used to open a second connection. +- `Driver.getPropertyInfo()` returns `null` as the value of credential properties. +- `Labels` and `QueryProperties` reject duplicate or empty keys. +- `Properties` keys must not contain `;`, `=`, control characters, or leading or + trailing spaces. + --- ## 5. Data Type Mapping Reference diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java index 78faf941e71c..bc782cba55ab 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java @@ -505,10 +505,19 @@ public boolean acceptsURL(String url) throws SQLException { * @param url the BigQuery connection URL * @param info a proposed list BigQuery connection properties * @return an array of {@code DriverPropertyInfo} objects describing possible properties. + * @throws SQLException if the connection URL or properties cannot be parsed * @see Driver#getPropertyInfo(String, Properties) */ @Override - public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) { + public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { + try { + return describeProperties(url, info); + } catch (BigQueryJdbcRuntimeException | IllegalArgumentException e) { + throw new BigQueryJdbcException("Failed to parse connection URL properties", e); + } + } + + private DriverPropertyInfo[] describeProperties(String url, Properties info) { LOG.finest("++enter++"); if (url == null || !url.startsWith("jdbc:bigquery:")) { return new DriverPropertyInfo[0]; 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 7368b9385011..48a3b071dcf8 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()); @@ -556,7 +556,7 @@ public void testConnect_rejectsPropertiesKeyInjectionAndFormatsPartnerToken() } @Test - public void testGetPropertyInfo_returnsNullForSecretsAndHandlesInvalidUrls() { + public void testGetPropertyInfo_returnsNullForSecretsAndHandlesInvalidUrls() throws SQLException { String connectionUrl = "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + "ProjectId=visible-proj;OAuthType=2;Location=US"; @@ -610,7 +610,7 @@ public void testGetPropertyInfo_returnsNullForSecretsAndHandlesInvalidUrls() { injectedKeyProperties.setProperty( "custom=1;EndpointOverrides", "BIGQUERY=https://127.0.0.1:8443"); Assertions.assertThrows( - BigQueryJdbcRuntimeException.class, + BigQueryJdbcException.class, () -> bigQueryDriver.getPropertyInfo(connectionUrl, injectedKeyProperties)); } } 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 8e15287937c6..37bcf64d25e7 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 @@ -317,6 +317,8 @@ public void testSnapshotConfiguredFields_coversEveryNonUrlDataSourceField() thro 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 From fce23c85ba921610544f68ede761469d90e2cf7c Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 30 Nov 2026 16:28:48 -0500 Subject: [PATCH 07/15] fix(bigquery-jdbc): warn when customOpenTelemetry property is non-empty and not an OpenTelemetry instance --- .../google/cloud/bigquery/jdbc/BigQueryDriver.java | 7 ++++--- .../cloud/bigquery/jdbc/BigQueryDriverTest.java | 13 +++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java index c2d9d19190e6..0c37e11c8fae 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java @@ -156,15 +156,16 @@ static ValidatedConnectionProperties validateAndCanonicalizeProperties( Collections.emptyMap(), Collections.emptyList(), null); } Properties propertiesSnapshot = (Properties) callerProperties.clone(); + Map canonicalProperties = new LinkedHashMap<>(); + List unknownPropertyKeys = new ArrayList<>(); OpenTelemetry customOpenTelemetry = null; Object customOpenTelemetryValue = propertiesSnapshot.get("customOpenTelemetry"); if (customOpenTelemetryValue instanceof OpenTelemetry) { customOpenTelemetry = (OpenTelemetry) customOpenTelemetryValue; + } else if (customOpenTelemetryValue != null && !"".equals(customOpenTelemetryValue)) { + unknownPropertyKeys.add("customOpenTelemetry"); } - Map canonicalProperties = new LinkedHashMap<>(); - List unknownPropertyKeys = new ArrayList<>(); - // Pass 1: record inherited String defaults that are not directly shadowed in // propertiesSnapshot. for (String defaultPropertyKey : propertiesSnapshot.stringPropertyNames()) { 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 6aa79af241fb..161187e380d6 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java @@ -155,6 +155,19 @@ public void testConnect_withCustomOpenTelemetry_injectsIntoDataSource() throws S assertThat(connection).isNotNull(); assertThat(connection.isClosed()).isFalse(); + + // Non-OpenTelemetry value records a warning key; empty string is ignored like other properties. + Properties wrongTypeProps = new Properties(); + wrongTypeProps.setProperty("customOpenTelemetry", "not-an-otel-instance"); + BigQueryDriver.ValidatedConnectionProperties wrongTypeValidated = + BigQueryDriver.validateAndCanonicalizeProperties(wrongTypeProps); + assertThat(wrongTypeValidated.customOpenTelemetry).isNull(); + assertThat(wrongTypeValidated.unknownPropertyKeys).containsExactly("customOpenTelemetry"); + + Properties emptyOtelProps = new Properties(); + emptyOtelProps.setProperty("customOpenTelemetry", ""); + assertThat(BigQueryDriver.validateAndCanonicalizeProperties(emptyOtelProps).unknownPropertyKeys) + .isEmpty(); } @Test From 069d0dcee64b4dcd87b22bb23014607d79f26b70 Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Wed, 2 Dec 2026 12:20:08 -0500 Subject: [PATCH 08/15] fix(bigquery-jdbc): return endpoint-only display URL and ignore invalid Properties keys Address review feedback on #15289: DatabaseMetaData display URL now returns only the caller's connection endpoint, validatePropertyKey is renamed to extractValidPropertyKey and rejects non-String keys, and keys that are blank, padded, or contain ';', '=', or control characters are ignored with a warning instead of failing the connection. --- .../bigquery/jdbc/BigQueryJdbcUrlUtility.java | 89 +++++++------------ .../jdbc/BigQueryJdbcUrlUtilityTest.java | 55 ++++++++---- 2 files changed, 69 insertions(+), 75 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java index a9ef6c42303c..b35d554f9a97 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java @@ -796,7 +796,6 @@ static String parseUriPropertyWithoutValidation(String uri, String property) { static final class ParsedConnectionUrl { private final String urlPrefix; private final Map canonicalProperties; - private final Map allowlistedDisplayProperties; private final List malformedSegmentPositions; private final List invalidPercentEncodingPositions; private final List unknownPropertyKeys; @@ -804,13 +803,11 @@ static final class ParsedConnectionUrl { ParsedConnectionUrl( String urlPrefix, Map canonicalProperties, - Map allowlistedDisplayProperties, List malformedSegmentPositions, List invalidPercentEncodingPositions, List unknownPropertyKeys) { this.urlPrefix = urlPrefix; this.canonicalProperties = Collections.unmodifiableMap(canonicalProperties); - this.allowlistedDisplayProperties = Collections.unmodifiableMap(allowlistedDisplayProperties); this.malformedSegmentPositions = Collections.unmodifiableList(malformedSegmentPositions); this.invalidPercentEncodingPositions = Collections.unmodifiableList(invalidPercentEncodingPositions); @@ -857,13 +854,9 @@ Map validateAndGetProperties() { } /** - * Builds a sanitized display URL suitable for {@code DatabaseMetaData.getURL()} and logs. - * - *

Non-allowlisted URL parameters are omitted (rather than masked as {@code key=*****}) so - * the returned URL stays syntactically valid for JDBC callers, avoids leaking secret parameter - * names to secret scanners, and prevents callers or BI tools from feeding {@code *****} back as - * a literal credential. Out-of-band {@code Properties}/{@code DataSource} credentials are never - * appended to the URL. + * 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) { @@ -883,18 +876,11 @@ String toSanitizedDisplayUrl() { // A well-formed prefix is scheme://host[:port]; anything else may carry a credential. normalizedUrlPrefix = "jdbc:bigquery:"; } - if (allowlistedDisplayProperties.isEmpty()) { - return normalizedUrlPrefix; - } - StringBuilder displayUrlBuilder = new StringBuilder(normalizedUrlPrefix); - for (Entry displayEntry : allowlistedDisplayProperties.entrySet()) { - displayUrlBuilder - .append(';') - .append(displayEntry.getKey()) - .append('=') - .append(displayEntry.getValue()); - } - return displayUrlBuilder.toString(); + // 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; } } @@ -937,7 +923,6 @@ static ParsedConnectionUrl parseConnectionUrl(String connectionUrl) { return new ParsedConnectionUrl( null, Collections.emptyMap(), - Collections.emptyMap(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); @@ -948,7 +933,6 @@ static ParsedConnectionUrl parseConnectionUrl(String connectionUrl) { return new ParsedConnectionUrl( connectionUrl, Collections.emptyMap(), - Collections.emptyMap(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); @@ -957,7 +941,6 @@ static ParsedConnectionUrl parseConnectionUrl(String connectionUrl) { String urlPrefix = connectionUrl.substring(0, firstSemicolonIndex); String parameterSection = connectionUrl.substring(firstSemicolonIndex + 1); Map canonicalProperties = new LinkedHashMap<>(); - Map allowlistedDisplayProperties = new LinkedHashMap<>(); List malformedSegmentPositions = new ArrayList<>(); List invalidPercentEncodingPositions = new ArrayList<>(); List unknownPropertyKeys = new ArrayList<>(); @@ -981,14 +964,8 @@ static ParsedConnectionUrl parseConnectionUrl(String connectionUrl) { String formattedPartnerToken = formatPartnerTokenHeaderValue(decodedPartnerToken); if (formattedPartnerToken != null) { canonicalProperties.put(PARTNER_TOKEN_PROPERTY_NAME, formattedPartnerToken); - if (BigQueryConnection.isSafeToLogProperty(PARTNER_TOKEN_PROPERTY_NAME)) { - allowlistedDisplayProperties.put( - PARTNER_TOKEN_PROPERTY_NAME, - BigQueryConnection.sanitizeForLog(encodedPartnerToken.trim())); - } } else { canonicalProperties.remove(PARTNER_TOKEN_PROPERTY_NAME); - allowlistedDisplayProperties.remove(PARTNER_TOKEN_PROPERTY_NAME); } partnerTokenMatcher.appendReplacement(remainingParameterSection, ""); } @@ -1022,7 +999,7 @@ static ParsedConnectionUrl parseConnectionUrl(String connectionUrl) { 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, while keeping unknown keys out of the sanitized display URL. + // failing the connection. String truncatedPropertyKey = uppercasePropertyKey.length() > 32 ? uppercasePropertyKey.substring(0, 32) + "..." @@ -1040,53 +1017,49 @@ static ParsedConnectionUrl parseConnectionUrl(String connectionUrl) { continue; } canonicalProperties.put(canonicalPropertyName, decodedPropertyValue); - // Omit non-allowlisted URL parameters from the display URL (DatabaseMetaData.getURL() - // contract) so credentials embedded in a URL never leak into metadata, traces, or logs. - if (BigQueryConnection.isSafeToLogProperty(canonicalPropertyName)) { - allowlistedDisplayProperties.put( - canonicalPropertyName, BigQueryConnection.sanitizeForLog(encodedPropertyValue)); - } } return new ParsedConnectionUrl( urlPrefix, canonicalProperties, - allowlistedDisplayProperties, malformedSegmentPositions, invalidPercentEncodingPositions, unknownPropertyKeys); } /** - * Returns a sanitized display URL with the {@code jdbc:bigquery:} prefix preserved and all - * non-allowlisted ({@code !SAFE_TO_LOG_PROPERTIES}) URL parameters omitted. + * 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."; + /** - * Validates a caller-supplied connection property key from {@code Properties}, rejecting - * delimiters ({@code ';'}, {@code '='}), ASCII control characters, blank keys, and - * leading/trailing whitespace so caller keys cannot inject or forge sibling connection - * properties. + * 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 validatePropertyKey(Object propertyKeyObject) { - if (propertyKeyObject == null) { - throw new BigQueryJdbcRuntimeException("Connection property key must not be null."); + static String extractValidPropertyKey(Object propertyKeyObject) { + if (!(propertyKeyObject instanceof String)) { + throw new BigQueryJdbcRuntimeException("Connection property keys must be non-null strings."); } - String propertyKey = String.valueOf(propertyKeyObject); + String propertyKey = (String) propertyKeyObject; if (propertyKey.isEmpty() || !propertyKey.equals(propertyKey.trim())) { - throw new BigQueryJdbcRuntimeException( - "Invalid connection property key: key must not be empty or contain leading/trailing" - + " whitespace."); + return null; } for (int index = 0; index < propertyKey.length(); index++) { char character = propertyKey.charAt(index); if (character == ';' || character == '=' || character < 0x20 || character == 0x7F) { - throw new BigQueryJdbcRuntimeException( - "Invalid connection property key: key must not contain ';', '=', or control" - + " characters."); + return null; } } return propertyKey; @@ -1147,7 +1120,11 @@ static String appendPropertiesToURL(String url, String callerClassName, Properti Object rawKey = entry.getKey(); Object rawValue = entry.getValue(); if (rawKey != null && rawValue != null) { - String key = validatePropertyKey(rawKey); + String key = extractValidPropertyKey(rawKey); + if (key == null) { + LOG.warning(IGNORED_PROPERTY_KEY_WARNING); + continue; + } String valueStr = String.valueOf(rawValue); if (!valueStr.isEmpty()) { LOG.finest( 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 4ba4d73fdf75..806a4cb06ce4 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 @@ -508,13 +508,15 @@ public void testSanitizeControlCharactersAndCaseInsensitiveSafeProperties() { assertThat(rec.getMessage()).doesNotContain("\r"); } - // Control characters inside property keys are rejected outright. + // Control characters inside property keys are ignored with a warning that does not echo the + // key. + capturedLogs.clear(); Properties controlKeyProperties = new Properties(); controlKeyProperties.setProperty("Custom\nKey", "secret-val"); - assertThrows( - BigQueryJdbcRuntimeException.class, - () -> - BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", controlKeyProperties)); + assertThat( + BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", controlKeyProperties)) + .isEqualTo(baseUrl); + assertThat(assertLogContains(BigQueryJdbcUrlUtility.IGNORED_PROPERTY_KEY_WARNING)).isTrue(); } @ParameterizedTest @@ -529,14 +531,37 @@ public void testSanitizeControlCharactersAndCaseInsensitiveSafeProperties() { "TrailingSpace ", "" }) - public void testAppendPropertiesToURL_rejectsInvalidPropertyKeys(String invalidKey) { + public void testAppendPropertiesToURL_ignoresInvalidPropertyKeys(String invalidKey) { String baseUrl = "bigquery://https://www.googleapis.com/bigquery/v2:443;ProjectId=locked"; Properties invalidProperties = new Properties(); invalidProperties.setProperty(invalidKey, "val"); + capturedLogs.clear(); + assertNull(BigQueryJdbcUrlUtility.extractValidPropertyKey(invalidKey)); + assertThat(BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", invalidProperties)) + .isEqualTo(baseUrl); + assertThat(assertLogContains(BigQueryJdbcUrlUtility.IGNORED_PROPERTY_KEY_WARNING)).isTrue(); + } + + @Test + public void testExtractValidPropertyKey_rejectsNonStringKeys() { + assertThat(BigQueryJdbcUrlUtility.extractValidPropertyKey("ProjectId")).isEqualTo("ProjectId"); + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> BigQueryJdbcUrlUtility.extractValidPropertyKey(null)); assertThrows( BigQueryJdbcRuntimeException.class, - () -> BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", invalidProperties)); + () -> BigQueryJdbcUrlUtility.extractValidPropertyKey(42)); + + Properties nonStringKeyProperties = new Properties(); + nonStringKeyProperties.put(42, "val"); + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcUrlUtility.appendPropertiesToURL( + "bigquery://https://www.googleapis.com/bigquery/v2:443", + "Caller", + nonStringKeyProperties)); } @Test @@ -639,7 +664,7 @@ public void testParseConnectionUrl_twoPhaseLastWinsAndInvalidPercentEncodingWith BigQueryJdbcUrlUtility.ParsedConnectionUrl parsedInvalidEncodingUrl = BigQueryJdbcUrlUtility.parseConnectionUrl(invalidPercentEncodingUrl); assertThat(parsedInvalidEncodingUrl.toSanitizedDisplayUrl()) - .isEqualTo("jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;ProjectId=p"); + .isEqualTo("jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443"); BigQueryJdbcRuntimeException invalidEncodingException = assertThrows( BigQueryJdbcRuntimeException.class, parsedInvalidEncodingUrl::validateAndGetProperties); @@ -648,7 +673,7 @@ public void testParseConnectionUrl_twoPhaseLastWinsAndInvalidPercentEncodingWith } @Test - public void testSanitizeUrlForDisplay_omitsNonAllowlistedParamsAndNormalizesPrefix() { + public void testSanitizeUrlForDisplay_returnsEndpointOnlyAndNormalizesPrefix() { assertNull(BigQueryJdbcUrlUtility.sanitizeUrlForDisplay(null)); assertThat(BigQueryJdbcUrlUtility.sanitizeUrlForDisplay("")).isEqualTo(""); assertThat( @@ -658,13 +683,11 @@ public void testSanitizeUrlForDisplay_omitsNonAllowlistedParamsAndNormalizesPref + "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;" - + "PartnerToken=(GPN:acme; prod);ProjectId=p2;OAuthType=2"); + .isEqualTo("jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443"); assertThat( BigQueryJdbcUrlUtility.sanitizeUrlForDisplay( "jdbc:bigquery://h?OAuthAccessToken=x;ProjectId=p")) - .isEqualTo("jdbc:bigquery:;ProjectId=p"); + .isEqualTo("jdbc:bigquery:"); } @Test @@ -689,12 +712,6 @@ public void testFormatPartnerTokenHeaderValue_doesNotDoubleDecodeAndPreservesLit assertThat(parsedPartnerToken).isEqualTo(" (GPN:partner%20name;prod)"); assertThat(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue(parsedPartnerToken)) .isEqualTo(" (GPN:partner%20name;prod)"); - assertThat( - BigQueryJdbcUrlUtility.parseConnectionUrl( - BigQueryJdbcUrlUtility.sanitizeUrlForDisplay(encodedPartnerTokenUrl)) - .validateAndGetProperties() - .get(BigQueryJdbcUrlUtility.PARTNER_TOKEN_PROPERTY_NAME)) - .isEqualTo(" (GPN:partner%20name;prod)"); } @Test From 0618a55b2b4b469c8238b396be2ecf6d60b1a9aa Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Wed, 2 Dec 2026 12:28:03 -0500 Subject: [PATCH 09/15] fix(bigquery-jdbc): treat endpoint override aliases as one property and empty DataSource strings as unset Address review feedback on #15290: an EndpointOverrides or PrivateServiceConnectUris value from a DataSource setter or Properties now replaces both aliases from the URL, empty-string DataSource setters are treated as unset like empty Properties values, and invalid Properties keys are ignored with a warning via extractValidPropertyKey. --- .../cloud/bigquery/jdbc/BigQueryDriver.java | 49 +++++++-- .../cloud/bigquery/jdbc/DataSource.java | 101 +++++++++--------- .../bigquery/jdbc/BigQueryDriverTest.java | 52 +++++++-- .../cloud/bigquery/jdbc/DataSourceTest.java | 36 +++++++ 4 files changed, 177 insertions(+), 61 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java index 0c37e11c8fae..2013b660d5fe 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java @@ -118,8 +118,9 @@ public static BigQueryDriver getRegisteredDriver() throws IllegalStateException *

"Normalized" here means: * *

    - *
  • Every key has been validated by {@link BigQueryJdbcUrlUtility#validatePropertyKey} - * against delimiters ({@code ';'}, {@code '='}), control characters, and outer whitespace. + *
  • Every key has been checked by {@link BigQueryJdbcUrlUtility#extractValidPropertyKey}; + * keys containing delimiters ({@code ';'}, {@code '='}), control characters, or outer + * whitespace are ignored with a warning. *
  • Case-insensitive known property names are mapped to their canonical names from {@link * BigQueryJdbcUrlUtility#PROPERTY_NAME_MAP}. *
  • Direct entries in the caller's {@link Properties} deterministically override any @@ -132,14 +133,17 @@ public static BigQueryDriver getRegisteredDriver() throws IllegalStateException static final class ValidatedConnectionProperties { final Map canonicalProperties; final List unknownPropertyKeys; + final boolean hasIgnoredInvalidPropertyKeys; final OpenTelemetry customOpenTelemetry; ValidatedConnectionProperties( Map canonicalProperties, List unknownPropertyKeys, + boolean hasIgnoredInvalidPropertyKeys, OpenTelemetry customOpenTelemetry) { this.canonicalProperties = Collections.unmodifiableMap(canonicalProperties); this.unknownPropertyKeys = Collections.unmodifiableList(unknownPropertyKeys); + this.hasIgnoredInvalidPropertyKeys = hasIgnoredInvalidPropertyKeys; this.customOpenTelemetry = customOpenTelemetry; } } @@ -153,11 +157,12 @@ static ValidatedConnectionProperties validateAndCanonicalizeProperties( Properties callerProperties) { if (callerProperties == null) { return new ValidatedConnectionProperties( - Collections.emptyMap(), Collections.emptyList(), null); + Collections.emptyMap(), Collections.emptyList(), false, null); } Properties propertiesSnapshot = (Properties) callerProperties.clone(); Map canonicalProperties = new LinkedHashMap<>(); List unknownPropertyKeys = new ArrayList<>(); + boolean hasIgnoredInvalidPropertyKeys = false; OpenTelemetry customOpenTelemetry = null; Object customOpenTelemetryValue = propertiesSnapshot.get("customOpenTelemetry"); if (customOpenTelemetryValue instanceof OpenTelemetry) { @@ -173,7 +178,12 @@ static ValidatedConnectionProperties validateAndCanonicalizeProperties( || propertiesSnapshot.containsKey(defaultPropertyKey)) { continue; } - String validatedPropertyKey = BigQueryJdbcUrlUtility.validatePropertyKey(defaultPropertyKey); + String validatedPropertyKey = + BigQueryJdbcUrlUtility.extractValidPropertyKey(defaultPropertyKey); + if (validatedPropertyKey == null) { + hasIgnoredInvalidPropertyKeys = true; + continue; + } String defaultPropertyValue = propertiesSnapshot.getProperty(defaultPropertyKey); recordValidatedProperty( validatedPropertyKey, defaultPropertyValue, canonicalProperties, unknownPropertyKeys); @@ -189,7 +199,12 @@ static ValidatedConnectionProperties validateAndCanonicalizeProperties( continue; } if (directKeyObject != null && directValueObject != null) { - String validatedPropertyKey = BigQueryJdbcUrlUtility.validatePropertyKey(directKeyObject); + String validatedPropertyKey = + BigQueryJdbcUrlUtility.extractValidPropertyKey(directKeyObject); + if (validatedPropertyKey == null) { + hasIgnoredInvalidPropertyKeys = true; + continue; + } recordValidatedProperty( validatedPropertyKey, String.valueOf(directValueObject), @@ -199,7 +214,10 @@ static ValidatedConnectionProperties validateAndCanonicalizeProperties( } return new ValidatedConnectionProperties( - canonicalProperties, unknownPropertyKeys, customOpenTelemetry); + canonicalProperties, + unknownPropertyKeys, + hasIgnoredInvalidPropertyKeys, + customOpenTelemetry); } private static void recordValidatedProperty( @@ -224,6 +242,20 @@ private static void recordValidatedProperty( } } + /** + * {@code EndpointOverrides} and {@code PrivateServiceConnectUris} are aliases; a caller value for + * either replaces both so a URL-supplied alias can never shadow it. + */ + private static void removeAliasesOverriddenBy( + Map baseProperties, Map overrideProperties) { + if (overrideProperties.containsKey(BigQueryJdbcUrlUtility.ENDPOINT_OVERRIDES_PROPERTY_NAME) + || overrideProperties.containsKey( + BigQueryJdbcUrlUtility.PRIVATE_SERVICE_CONNECT_PROPERTY_NAME)) { + baseProperties.remove(BigQueryJdbcUrlUtility.ENDPOINT_OVERRIDES_PROPERTY_NAME); + baseProperties.remove(BigQueryJdbcUrlUtility.PRIVATE_SERVICE_CONNECT_PROPERTY_NAME); + } + } + private static boolean isTelemetryOptOut(String value) { if (value == null) { return false; @@ -424,6 +456,9 @@ private Connection connectInternal( for (String unknownPropertyKey : propertiesOverrides.unknownPropertyKeys) { LOG.warning("Wrong value or unknown setting: %s", unknownPropertyKey); } + if (propertiesOverrides.hasIgnoredInvalidPropertyKeys) { + LOG.warning(BigQueryJdbcUrlUtility.IGNORED_PROPERTY_KEY_WARNING); + } } if (dataSourceOverrides != null) { resolvedDataSource = @@ -433,6 +468,8 @@ private Connection connectInternal( Map mergedConnectionProperties = new LinkedHashMap<>(validatedUrlProperties); if (propertiesOverrides != null) { + removeAliasesOverriddenBy( + mergedConnectionProperties, propertiesOverrides.canonicalProperties); mergedConnectionProperties.putAll(propertiesOverrides.canonicalProperties); } resolvedDataSource = 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 1ae9d6cda6f1..1d2b470134de 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 @@ -486,22 +486,27 @@ DataSource snapshotConfiguredFields() { return configuredSnapshot; } + /** Empty strings mean "not configured", matching the {@code Properties} path. */ + private static boolean isConfigured(String value) { + return value != null && !value.isEmpty(); + } + /** - * Copies every non-null field configured 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. + * 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 (this.projectId != null) { + if (isConfigured(this.projectId)) { targetDataSource.projectId = this.projectId; } - if (this.defaultDataset != null) { + if (isConfigured(this.defaultDataset)) { targetDataSource.defaultDataset = this.defaultDataset; } - if (this.location != null) { + if (isConfigured(this.location)) { targetDataSource.location = this.location; } - if (this.userAgent != null) { + if (isConfigured(this.userAgent)) { targetDataSource.userAgent = this.userAgent; } if (this.enableHighThroughputAPI != null) { @@ -516,13 +521,13 @@ void applyConfiguredFieldsTo(DataSource targetDataSource) { if (this.unsupportedHTAPIFallback != null) { targetDataSource.unsupportedHTAPIFallback = this.unsupportedHTAPIFallback; } - if (this.kmsKeyName != null) { + if (isConfigured(this.kmsKeyName)) { targetDataSource.kmsKeyName = this.kmsKeyName; } if (this.queryProperties != null) { targetDataSource.queryProperties = this.queryProperties; } - if (this.logLevel != null) { + if (isConfigured(this.logLevel)) { targetDataSource.logLevel = this.logLevel; } if (this.enableSession != null) { @@ -531,73 +536,73 @@ void applyConfiguredFieldsTo(DataSource targetDataSource) { if (this.enableTimestampPicos != null) { targetDataSource.enableTimestampPicos = this.enableTimestampPicos; } - if (this.logPath != null) { + if (isConfigured(this.logPath)) { targetDataSource.logPath = this.logPath; } - if (this.gcpTelemetryProjectId != null) { + if (isConfigured(this.gcpTelemetryProjectId)) { targetDataSource.gcpTelemetryProjectId = this.gcpTelemetryProjectId; } - if (this.gcpTelemetryCredentials != null) { + if (isConfigured(this.gcpTelemetryCredentials)) { targetDataSource.gcpTelemetryCredentials = this.gcpTelemetryCredentials; } if (this.oAuthType != null) { targetDataSource.oAuthType = this.oAuthType; } - if (this.oAuthServiceAcctEmail != null) { + if (isConfigured(this.oAuthServiceAcctEmail)) { targetDataSource.oAuthServiceAcctEmail = this.oAuthServiceAcctEmail; } - if (this.oAuthPvtKeyPath != null) { + if (isConfigured(this.oAuthPvtKeyPath)) { targetDataSource.oAuthPvtKeyPath = this.oAuthPvtKeyPath; } - if (this.oAuthPvtKey != null) { + if (isConfigured(this.oAuthPvtKey)) { targetDataSource.oAuthPvtKey = this.oAuthPvtKey; } - if (this.oAuthAccessToken != null) { + if (isConfigured(this.oAuthAccessToken)) { targetDataSource.oAuthAccessToken = this.oAuthAccessToken; } if (this.oAuthAccessTokenReadonly != null) { targetDataSource.oAuthAccessTokenReadonly = this.oAuthAccessTokenReadonly; } - if (this.oAuthRefreshToken != null) { + if (isConfigured(this.oAuthRefreshToken)) { targetDataSource.oAuthRefreshToken = this.oAuthRefreshToken; } if (this.useQueryCache != null) { targetDataSource.useQueryCache = this.useQueryCache; } - if (this.queryDialect != null) { + if (isConfigured(this.queryDialect)) { targetDataSource.queryDialect = this.queryDialect; } if (this.allowLargeResults != null) { targetDataSource.allowLargeResults = this.allowLargeResults; } - if (this.destinationTable != null) { + if (isConfigured(this.destinationTable)) { targetDataSource.destinationTable = this.destinationTable; } - if (this.destinationDataset != null) { + if (isConfigured(this.destinationDataset)) { targetDataSource.destinationDataset = this.destinationDataset; } if (this.destinationDatasetExpirationTime != null) { targetDataSource.destinationDatasetExpirationTime = this.destinationDatasetExpirationTime; } - if (this.universeDomain != null) { + if (isConfigured(this.universeDomain)) { targetDataSource.universeDomain = this.universeDomain; } - if (this.proxyHost != null) { + if (isConfigured(this.proxyHost)) { targetDataSource.proxyHost = this.proxyHost; } - if (this.proxyPort != null) { + if (isConfigured(this.proxyPort)) { targetDataSource.proxyPort = this.proxyPort; } - if (this.proxyUid != null) { + if (isConfigured(this.proxyUid)) { targetDataSource.proxyUid = this.proxyUid; } - if (this.proxyPwd != null) { + if (isConfigured(this.proxyPwd)) { targetDataSource.proxyPwd = this.proxyPwd; } - if (this.oAuthClientId != null) { + if (isConfigured(this.oAuthClientId)) { targetDataSource.oAuthClientId = this.oAuthClientId; } - if (this.oAuthClientSecret != null) { + if (isConfigured(this.oAuthClientSecret)) { targetDataSource.oAuthClientSecret = this.oAuthClientSecret; } if (this.jobCreationMode != null) { @@ -613,7 +618,7 @@ void applyConfiguredFieldsTo(DataSource targetDataSource) { if (this.enableWriteAPI != null) { targetDataSource.enableWriteAPI = this.enableWriteAPI; } - if (this.additionalProjects != null) { + if (isConfigured(this.additionalProjects)) { targetDataSource.additionalProjects = this.additionalProjects; } if (this.filterTablesOnDefaultDataset != null) { @@ -628,22 +633,22 @@ void applyConfiguredFieldsTo(DataSource targetDataSource) { if (this.metadataFetchThreadCount != null) { targetDataSource.metadataFetchThreadCount = this.metadataFetchThreadCount; } - if (this.sslTrustStorePath != null) { + if (isConfigured(this.sslTrustStorePath)) { targetDataSource.sslTrustStorePath = this.sslTrustStorePath; } - if (this.sslTrustStorePassword != null) { + if (isConfigured(this.sslTrustStorePassword)) { targetDataSource.sslTrustStorePassword = this.sslTrustStorePassword; } - if (this.sslTrustStoreType != null) { + if (isConfigured(this.sslTrustStoreType)) { targetDataSource.sslTrustStoreType = this.sslTrustStoreType; } - if (this.sslTrustStoreProvider != null) { + if (isConfigured(this.sslTrustStoreProvider)) { targetDataSource.sslTrustStoreProvider = this.sslTrustStoreProvider; } if (this.labels != null) { targetDataSource.labels = this.labels; } - if (this.requestReason != null) { + if (isConfigured(this.requestReason)) { targetDataSource.requestReason = this.requestReason; } if (this.timeout != null) { @@ -673,46 +678,46 @@ void applyConfiguredFieldsTo(DataSource targetDataSource) { if (this.swaAppendRowCount != null) { targetDataSource.swaAppendRowCount = this.swaAppendRowCount; } - if (this.oAuthP12Password != null) { + if (isConfigured(this.oAuthP12Password)) { targetDataSource.oAuthP12Password = this.oAuthP12Password; } - if (this.oAuthSAImpersonationEmail != null) { + if (isConfigured(this.oAuthSAImpersonationEmail)) { targetDataSource.oAuthSAImpersonationEmail = this.oAuthSAImpersonationEmail; } - if (this.oAuthSAImpersonationChain != null) { + if (isConfigured(this.oAuthSAImpersonationChain)) { targetDataSource.oAuthSAImpersonationChain = this.oAuthSAImpersonationChain; } - if (this.oAuthSAImpersonationScopes != null) { + if (isConfigured(this.oAuthSAImpersonationScopes)) { targetDataSource.oAuthSAImpersonationScopes = this.oAuthSAImpersonationScopes; } - if (this.oAuthSAImpersonationTokenLifetime != null) { + if (isConfigured(this.oAuthSAImpersonationTokenLifetime)) { targetDataSource.oAuthSAImpersonationTokenLifetime = this.oAuthSAImpersonationTokenLifetime; } - if (this.oAuth2TokenUri != null) { + if (isConfigured(this.oAuth2TokenUri)) { targetDataSource.oAuth2TokenUri = this.oAuth2TokenUri; } - if (this.byoidAudienceUri != null) { + if (isConfigured(this.byoidAudienceUri)) { targetDataSource.byoidAudienceUri = this.byoidAudienceUri; } - if (this.byoidCredentialSource != null) { + if (isConfigured(this.byoidCredentialSource)) { targetDataSource.byoidCredentialSource = this.byoidCredentialSource; } - if (this.byoidPoolUserProject != null) { + if (isConfigured(this.byoidPoolUserProject)) { targetDataSource.byoidPoolUserProject = this.byoidPoolUserProject; } - if (this.byoidSAImpersonationUri != null) { + if (isConfigured(this.byoidSAImpersonationUri)) { targetDataSource.byoidSAImpersonationUri = this.byoidSAImpersonationUri; } - if (this.byoidSubjectTokenType != null) { + if (isConfigured(this.byoidSubjectTokenType)) { targetDataSource.byoidSubjectTokenType = this.byoidSubjectTokenType; } - if (this.byoidTokenUri != null) { + if (isConfigured(this.byoidTokenUri)) { targetDataSource.byoidTokenUri = this.byoidTokenUri; } - if (this.endpointOverrides != null) { + // 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 = this.endpointOverrides; - } - if (this.privateServiceConnect != null) { targetDataSource.privateServiceConnect = this.privateServiceConnect; } if (this.connectionPoolSize != null) { 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 161187e380d6..cf032920d6dd 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryDriverTest.java @@ -509,23 +509,61 @@ public void testDataSourceLogPathOverridesUrl(@TempDir Path tempDir) throws SQLE } @Test - public void testConnect_rejectsPropertiesKeyInjectionAndFormatsPartnerToken() + 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"); - Assertions.assertThrows( - BigQueryJdbcException.class, - () -> bigQueryDriver.connect(baseConnectionUrl, semicolonInjectedProperties)); + 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"); - Assertions.assertThrows( - BigQueryJdbcException.class, - () -> bigQueryDriver.connect(baseConnectionUrl, equalsInjectedProperties)); + 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)"); 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 8e15287937c6..7d5c306d949f 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 @@ -258,6 +258,42 @@ public void testGetConnection_typedMapsWithDelimitersDoNotInjectSiblingKeys() } } + @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 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(); From 83e53789d0f1562aa9ca2be364d292f6b22a9edd Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Wed, 2 Dec 2026 12:35:24 -0500 Subject: [PATCH 10/15] fix(bigquery-jdbc): align getPropertyInfo telemetry opt-out and aliases with connect Address review feedback on #15291: Driver.getPropertyInfo reports EnableDiagnosticTelemetry=false when any source opts out, matching connect(), applies the EndpointOverrides/PrivateServiceConnectUris alias rule, and a stale process comment on getAuthProperties is removed. --- .../cloud/bigquery/jdbc/BigQueryConnection.java | 3 --- .../cloud/bigquery/jdbc/BigQueryDriver.java | 7 +++++++ .../cloud/bigquery/jdbc/BigQueryDriverTest.java | 17 +++++++++++++++++ 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java index eb459a3b72b6..7bf31a64f46a 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java @@ -763,9 +763,6 @@ public String getLocation() throws BigQueryJdbcException { return this.location; } - // Public signature intentionally kept unchanged for G01 to preserve API/binary compatibility - // (api-lifecycle) and existing integration test callers (ITPSCBigQueryTest, - // ITUniverseDomainBigQueryTest). public Map getAuthProperties() throws BigQueryJdbcException { checkClosed(); return this.authProperties; diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java index 9e86fb180233..fcee9317fb70 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java @@ -565,7 +565,14 @@ private DriverPropertyInfo[] describeProperties(String url, Properties info) { Map mergedConnectionProperties = new LinkedHashMap<>(parsedUrl.validateAndGetProperties()); ValidatedConnectionProperties propertiesOverrides = validateAndCanonicalizeProperties(info); + removeAliasesOverriddenBy(mergedConnectionProperties, propertiesOverrides.canonicalProperties); mergedConnectionProperties.putAll(propertiesOverrides.canonicalProperties); + // Mirror connect(): an EnableDiagnosticTelemetry opt-out from any source wins. + String telemetryPropertyName = BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME; + if (isTelemetryOptOut(parsedUrl.getPreConnectProperty(telemetryPropertyName)) + || isTelemetryOptOut(propertiesOverrides.canonicalProperties.get(telemetryPropertyName))) { + mergedConnectionProperties.put(telemetryPropertyName, "false"); + } List propertyInfoList = new ArrayList<>(); for (BigQueryConnectionProperty connectionProperty : BigQueryJdbcUrlUtility.VALID_PROPERTIES) { 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 43433855cbe4..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 @@ -667,4 +667,21 @@ public void testGetPropertyInfo_returnsNullForSecretsAndHandlesInvalidUrls() thr } } } + + @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(); + } } From bbaaf1b1a7e448b1123c6839c443b56d4dd988ba Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Wed, 2 Dec 2026 12:42:18 -0500 Subject: [PATCH 11/15] fix(bigquery-jdbc): copy an empty endpoint override alias as unset When one EndpointOverrides/PrivateServiceConnectUris alias is configured and the other is an empty string, copy the empty alias as null so it is not surfaced in diagnostic logs. --- .../google/cloud/bigquery/jdbc/DataSource.java | 6 ++++-- .../cloud/bigquery/jdbc/DataSourceTest.java | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) 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 1d2b470134de..9760956e9b5d 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/DataSource.java @@ -717,8 +717,10 @@ void applyConfiguredFieldsTo(DataSource targetDataSource) { // 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 = this.endpointOverrides; - targetDataSource.privateServiceConnect = this.privateServiceConnect; + targetDataSource.endpointOverrides = + isConfigured(this.endpointOverrides) ? this.endpointOverrides : null; + targetDataSource.privateServiceConnect = + isConfigured(this.privateServiceConnect) ? this.privateServiceConnect : null; } if (this.connectionPoolSize != null) { targetDataSource.connectionPoolSize = this.connectionPoolSize; 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 7d5c306d949f..a86a4777c786 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 @@ -278,6 +278,22 @@ public void testGetConnection_privateServiceConnectSetterReplacesUrlEndpointOver } } + @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(); From c5ec3d31408088f065957884d16fdc7a3d6b421d Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Wed, 2 Dec 2026 12:44:34 -0500 Subject: [PATCH 12/15] fix(bigquery-jdbc): update getURL comments and drop inert alias call in getPropertyInfo --- .../com/google/cloud/bigquery/jdbc/BigQueryConnection.java | 4 +--- .../google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java | 3 +-- .../java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java | 1 - 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java index 7bf31a64f46a..3e0249bd2636 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java @@ -347,9 +347,7 @@ static String maskPropertyValue(String key, Object value) { ExecutorService createdMetadataExecutor = null; try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(this.connectionId)) { // DatabaseMetaData.getURL() exposes only the connection endpoint, never connection - // properties, - // regardless of whether the connection was created via Driver, DataSource, or direct - // constructor. + // properties, whether the connection came from Driver, DataSource, or the constructor. this.connectionUrl = BigQueryJdbcUrlUtility.sanitizeUrlForDisplay(url); if (LOG.isLoggable(Level.CONFIG)) { LOG.config("Connection properties: %s", ds.toMaskedLogMap().toString()); diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java index defc1dca1f1a..2572a1759d51 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDatabaseMetaData.java @@ -192,8 +192,7 @@ public boolean allTablesAreSelectable() { @Override public String getURL() { - // Returns a sanitized jdbc:bigquery: URL with all non-allowlisted (!SAFE_TO_LOG_PROPERTIES) - // URL parameters omitted and out-of-band Properties/DataSource credentials excluded. + // Returns only the sanitized jdbc:bigquery: connection endpoint (no connection properties). return this.URL; } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java index fcee9317fb70..75b3e9227683 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java @@ -565,7 +565,6 @@ private DriverPropertyInfo[] describeProperties(String url, Properties info) { Map mergedConnectionProperties = new LinkedHashMap<>(parsedUrl.validateAndGetProperties()); ValidatedConnectionProperties propertiesOverrides = validateAndCanonicalizeProperties(info); - removeAliasesOverriddenBy(mergedConnectionProperties, propertiesOverrides.canonicalProperties); mergedConnectionProperties.putAll(propertiesOverrides.canonicalProperties); // Mirror connect(): an EnableDiagnosticTelemetry opt-out from any source wins. String telemetryPropertyName = BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME; From 119d17457ad2711aec45f493e6ce0422096b820c Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Wed, 2 Dec 2026 20:49:36 -0500 Subject: [PATCH 13/15] refactor(bigquery-jdbc): drop redundant empty-prefix branch in toSanitizedDisplayUrl --- .../com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java index b35d554f9a97..3b78f8631da1 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcUrlUtility.java @@ -862,9 +862,6 @@ String toSanitizedDisplayUrl() { if (urlPrefix == null) { return null; } - if (urlPrefix.isEmpty()) { - return ""; - } String sanitizedUrlPrefix = BigQueryConnection.sanitizeForLog(urlPrefix); String normalizedUrlPrefix = sanitizedUrlPrefix.startsWith("bigquery:") From 76b509040851098b78ac2aeeaaa1568352308217 Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Wed, 2 Dec 2026 20:52:35 -0500 Subject: [PATCH 14/15] docs(bigquery-jdbc): describe single-pass URL parsing without PARSE_CACHE --- java-bigquery-jdbc/DEVELOPMENT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java-bigquery-jdbc/DEVELOPMENT.md b/java-bigquery-jdbc/DEVELOPMENT.md index 825da028d7b2..506afbfeb6b7 100644 --- a/java-bigquery-jdbc/DEVELOPMENT.md +++ b/java-bigquery-jdbc/DEVELOPMENT.md @@ -41,7 +41,7 @@ graph TD - **`BigQueryDriver`**: JDBC entry point registered with `java.sql.DriverManager`. Intercepts `jdbc:bigquery://` URLs, initializes early logger state, and instantiates `BigQueryConnection`. - **`BigQueryConnection`**: Represents an active BigQuery session, holding dataset defaults, connection configuration maps, and transaction/session state (`EnableSession=true`, `session_id`). -- **`BigQueryJdbcUrlUtility`**: Parses and validates connection string parameters using a bounded LRU parse cache (`PARSE_CACHE`) to avoid heavy allocations during frequent connection creation. +- **`BigQueryJdbcUrlUtility`**: Parses and validates connection string parameters in a single pass (`parseConnectionUrl`). It keeps no static cache, so URLs that carry credentials are not retained across connections. - **`BigQueryJdbcContextProxy`**: A dynamic proxy layer (`java.lang.reflect.Proxy`) wrapping JDBC statements, connections, and metadata. Intercepts calls to propagate ThreadLocal MDC parameters (`connectionId`) across execution threads and enforce state validation (`checkClosed()`). - **`BigQueryTypeRegistry` & `TypeDescriptor`**: Centralized, bidirectional mapping between JDBC SQL types, Java classes and BigQuery types (`StandardSQLTypeName`), including the coercion of raw values (`Date`, `Timestamp`, `BigDecimal`, etc.) into the expected Java type. - **`BigQueryArrowResultSet`**: Custom result set implementation accelerating large query result retrieval via the BigQuery Storage Read API gRPC stream. From bb8dc43c13b868f8b5311c0a3eb433bc4c7ff484 Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Wed, 2 Dec 2026 20:52:55 -0500 Subject: [PATCH 15/15] docs(bigquery-jdbc): clarify getPropertyInfo redaction and empty values in user guide --- java-bigquery-jdbc/docs/USER_GUIDE.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index 7351b785c300..2a16a5dcfb17 100644 --- a/java-bigquery-jdbc/docs/USER_GUIDE.md +++ b/java-bigquery-jdbc/docs/USER_GUIDE.md @@ -293,10 +293,13 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443" `EnableDiagnosticTelemetry` opt-out (`0` or `false`) in any source always wins. - `DatabaseMetaData.getURL()` returns only the connection endpoint, without any connection properties, so it cannot be used to open a second connection. -- `Driver.getPropertyInfo()` returns `null` as the value of credential properties. +- `Driver.getPropertyInfo()` returns `null` as the value of credentials and of any + other property that is not on the driver's safe-to-log list. - `Labels` and `QueryProperties` reject duplicate or empty keys. - `Properties` keys that contain `;`, `=`, control characters, or leading or trailing spaces are ignored with a warning. +- Empty values (`""`), whether from `Properties` or `DataSource` setters, are + treated as unset. ---