From a68a6b3962ca331929a8b3c915a2bb79e6a5c05d Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 30 Nov 2026 12:24:41 -0500 Subject: [PATCH 1/5] 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 6aa7c4f74d0152f8b9c54bc435aea999729f7f31 Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 30 Nov 2026 16:00:41 -0500 Subject: [PATCH 2/5] 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 069d0dcee64b4dcd87b22bb23014607d79f26b70 Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Wed, 2 Dec 2026 12:20:08 -0500 Subject: [PATCH 3/5] 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 119d17457ad2711aec45f493e6ce0422096b820c Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Wed, 2 Dec 2026 20:49:36 -0500 Subject: [PATCH 4/5] 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 5/5] 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.