diff --git a/java-bigquery-jdbc/DEVELOPMENT.md b/java-bigquery-jdbc/DEVELOPMENT.md index 825da028d7b2..506afbfeb6b7 100644 --- a/java-bigquery-jdbc/DEVELOPMENT.md +++ b/java-bigquery-jdbc/DEVELOPMENT.md @@ -41,7 +41,7 @@ graph TD - **`BigQueryDriver`**: JDBC entry point registered with `java.sql.DriverManager`. Intercepts `jdbc:bigquery://` URLs, initializes early logger state, and instantiates `BigQueryConnection`. - **`BigQueryConnection`**: Represents an active BigQuery session, holding dataset defaults, connection configuration maps, and transaction/session state (`EnableSession=true`, `session_id`). -- **`BigQueryJdbcUrlUtility`**: Parses and validates connection string parameters using a bounded LRU parse cache (`PARSE_CACHE`) to avoid heavy allocations during frequent connection creation. +- **`BigQueryJdbcUrlUtility`**: Parses and validates connection string parameters in a single pass (`parseConnectionUrl`). It keeps no static cache, so URLs that carry credentials are not retained across connections. - **`BigQueryJdbcContextProxy`**: A dynamic proxy layer (`java.lang.reflect.Proxy`) wrapping JDBC statements, connections, and metadata. Intercepts calls to propagate ThreadLocal MDC parameters (`connectionId`) across execution threads and enforce state validation (`checkClosed()`). - **`BigQueryTypeRegistry` & `TypeDescriptor`**: Centralized, bidirectional mapping between JDBC SQL types, Java classes and BigQuery types (`StandardSQLTypeName`), including the coercion of raw values (`Date`, `Timestamp`, `BigDecimal`, etc.) into the expected Java type. - **`BigQueryArrowResultSet`**: Custom result set implementation accelerating large query result retrieval via the BigQuery Storage Read API gRPC stream. diff --git a/java-bigquery-jdbc/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..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 @@ -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,27 +704,27 @@ protected boolean removeEldestEntry(Map.Entry> eldes ENDPOINT_OVERRIDES_PROPERTY_NAME, PRIVATE_SERVICE_CONNECT_PROPERTY_NAME); - private static final Map PROPERTY_NAME_MAP; + static final Map PROPERTY_NAME_MAP; static { Map map = new HashMap<>(); for (BigQueryConnectionProperty p : VALID_PROPERTIES) { - map.put(p.getName().toUpperCase(), p.getName()); + map.put(p.getName().toUpperCase(Locale.ROOT), p.getName()); } for (BigQueryConnectionProperty p : AUTH_PROPERTIES) { - map.put(p.getName().toUpperCase(), p.getName()); + map.put(p.getName().toUpperCase(Locale.ROOT), p.getName()); } for (BigQueryConnectionProperty p : PROXY_PROPERTIES) { - map.put(p.getName().toUpperCase(), p.getName()); + map.put(p.getName().toUpperCase(Locale.ROOT), p.getName()); } for (String p : OVERRIDE_PROPERTIES) { - map.put(p.toUpperCase(), p); + map.put(p.toUpperCase(Locale.ROOT), p); } for (String p : BYOID_PROPERTIES) { - map.put(p.toUpperCase(), p); + map.put(p.toUpperCase(Locale.ROOT), p); } for (String p : NETWORK_PROPERTIES) { - map.put(p.toUpperCase(), p); + map.put(p.toUpperCase(Locale.ROOT), p); } PROPERTY_NAME_MAP = Collections.unmodifiableMap(map); } @@ -746,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); } @@ -784,70 +778,299 @@ 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 List malformedSegmentPositions; + private final List invalidPercentEncodingPositions; + private final List unknownPropertyKeys; + + ParsedConnectionUrl( + String urlPrefix, + Map canonicalProperties, + List malformedSegmentPositions, + List invalidPercentEncodingPositions, + List unknownPropertyKeys) { + this.urlPrefix = urlPrefix; + this.canonicalProperties = Collections.unmodifiableMap(canonicalProperties); + this.malformedSegmentPositions = Collections.unmodifiableList(malformedSegmentPositions); + this.invalidPercentEncodingPositions = + Collections.unmodifiableList(invalidPercentEncodingPositions); + this.unknownPropertyKeys = Collections.unmodifiableList(unknownPropertyKeys); + } + + /** + * 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 the display URL returned by {@code DatabaseMetaData.getURL()}: the caller's connection + * endpoint only, for example {@code + * jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443}. + */ + String toSanitizedDisplayUrl() { + if (urlPrefix == null) { + return null; + } + String sanitizedUrlPrefix = BigQueryConnection.sanitizeForLog(urlPrefix); + String normalizedUrlPrefix = + sanitizedUrlPrefix.startsWith("bigquery:") + ? "jdbc:" + sanitizedUrlPrefix + : sanitizedUrlPrefix; + if (normalizedUrlPrefix.indexOf('=') >= 0 + || normalizedUrlPrefix.indexOf('?') >= 0 + || normalizedUrlPrefix.indexOf('@') >= 0) { + // A well-formed prefix is scheme://host[:port]; anything else may carry a credential. + normalizedUrlPrefix = "jdbc:bigquery:"; + } + // The display URL is informational only, so no connection properties are appended: with + // credentials removed it could not open a new connection anyway, and omitting every property + // guarantees no configuration or secret is exposed through metadata, traces, or logs. The + // caller's endpoint is kept so PSC and custom-universe connections remain identifiable. + return normalizedUrlPrefix; + } } - 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.equals(BigQueryConnection.sanitizeForLog(unwrappedToken))) { + return null; // control characters must never reach the user-agent header + } + if (unwrappedToken.toUpperCase(Locale.ROOT).startsWith("GPN:")) { + return " (" + unwrappedToken + ")"; + } + return null; + } - 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.emptyList(), + Collections.emptyList(), + Collections.emptyList()); } - String urlToParse = urlParts[1]; + int firstSemicolonIndex = connectionUrl.indexOf(';'); + if (firstSemicolonIndex == -1) { + return new ParsedConnectionUrl( + connectionUrl, + 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<>(); + 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. + } } - urlToParse = matcher.replaceFirst(""); + String formattedPartnerToken = formatPartnerTokenHeaderValue(decodedPartnerToken); + if (formattedPartnerToken != null) { + canonicalProperties.put(PARTNER_TOKEN_PROPERTY_NAME, formattedPartnerToken); + } else { + canonicalProperties.remove(PARTNER_TOKEN_PROPERTY_NAME); + } + partnerTokenMatcher.appendReplacement(remainingParameterSection, ""); + } + if (remainingParameterSection != null) { + partnerTokenMatcher.appendTail(remainingParameterSection); + parameterSection = remainingParameterSection.toString(); } - String[] parts = urlToParse.split(";"); - for (String part : parts) { - if (part.trim().isEmpty()) { + 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; + + if (segment.trim().isEmpty()) { continue; } - String[] kv = part.split("=", 2); - String key = kv[0].trim().toUpperCase(); - if (kv.length != 2 || !PROPERTY_NAME_MAP.containsKey(key)) { - String ref = (kv.length == 2) ? key : part; - String safeRef = ref.length() > 32 ? ref.substring(0, 32) + "..." : ref; - // Some tools can pass unknown keys. In order not to break compatibility, throw - // an exception only with incorrect format, otherwise log an error. - if (kv.length != 2) { - throw new BigQueryJdbcRuntimeException( - String.format("Wrong value or unknown setting: %s", safeRef)); - } else { - LOG.warning( - "Wrong value or unknown setting: %s", BigQueryConnection.sanitizeForLog(safeRef)); - continue; - } + segmentPosition++; + + int equalsIndex = segment.indexOf('='); + if (equalsIndex <= 0 || segment.substring(0, equalsIndex).trim().isEmpty()) { + malformedSegmentPositions.add(segmentPosition); + continue; + } + String uppercasePropertyKey = + segment.substring(0, equalsIndex).trim().toUpperCase(Locale.ROOT); + String canonicalPropertyName = PROPERTY_NAME_MAP.get(uppercasePropertyKey); + if (canonicalPropertyName == null) { + // Some tools pass unknown keys; preserve compatibility by warning in Phase 2 instead of + // failing the connection. + String truncatedPropertyKey = + uppercasePropertyKey.length() > 32 + ? uppercasePropertyKey.substring(0, 32) + "..." + : uppercasePropertyKey; + unknownPropertyKeys.add(BigQueryConnection.sanitizeForLog(truncatedPropertyKey)); + continue; } - String propertyName = PROPERTY_NAME_MAP.get(key); - String value = CharEscapers.decodeUriPath(kv[1].replace("+", "%2B")); - map.put(propertyName, value); + + 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); } - return Collections.unmodifiableMap(map); + + return new ParsedConnectionUrl( + urlPrefix, + canonicalProperties, + malformedSegmentPositions, + invalidPercentEncodingPositions, + unknownPropertyKeys); + } + + /** + * Returns the display URL for {@code connectionUrl}: the {@code jdbc:bigquery:} connection + * endpoint only, without any connection properties. + */ + static String sanitizeUrlForDisplay(String connectionUrl) { + return parseConnectionUrl(connectionUrl).toSanitizedDisplayUrl(); + } + + /** Warning logged when {@link #extractValidPropertyKey(Object)} ignores a property key. */ + static final String IGNORED_PROPERTY_KEY_WARNING = + "Ignoring a connection property key that is blank, has leading or trailing whitespace, or" + + " contains ';', '=', or control characters."; + + /** + * Returns a caller-supplied {@code Properties} key, or {@code null} if the key must be ignored + * because it is blank, has leading/trailing whitespace, or contains {@code ';'}, {@code '='}, or + * ASCII control characters. Such keys can never name a connection property. + * + * @throws BigQueryJdbcRuntimeException if the key is {@code null} or not a {@link String}; JDBC + * defines connection properties as String key/value pairs. + */ + static String extractValidPropertyKey(Object propertyKeyObject) { + if (!(propertyKeyObject instanceof String)) { + throw new BigQueryJdbcRuntimeException("Connection property keys must be non-null strings."); + } + String propertyKey = (String) propertyKeyObject; + if (propertyKey.isEmpty() || !propertyKey.equals(propertyKey.trim())) { + return null; + } + for (int index = 0; index < propertyKey.length(); index++) { + char character = propertyKey.charAt(index); + if (character == ';' || character == '=' || character < 0x20 || character == 0x7F) { + return null; + } + } + return propertyKey; + } + + /** + * Parses the URL into a map of key-value pairs, validating that all segments are well-formed. + * + * @param url The URL to parse. + * @return An unmodifiable map of canonical property names to decoded values. + * @throws BigQueryJdbcRuntimeException if any segment is malformed or has invalid URL encoding. + */ + static Map parseUrl(String url) { + return parseConnectionUrl(url).validateAndGetProperties(); } static boolean isUrlLogPathAllowed() { @@ -894,7 +1117,11 @@ 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 = extractValidPropertyKey(rawKey); + if (key == null) { + LOG.warning(IGNORED_PROPERTY_KEY_WARNING); + continue; + } String valueStr = String.valueOf(rawValue); if (!valueStr.isEmpty()) { LOG.finest( @@ -983,15 +1210,26 @@ static Map parsePropertiesMapFromValue( LOG.fine("Unable to parse property name: %s from context: %s", propertyName, context); return null; } - Map propertiesMap = new HashMap<>(); + Map propertiesMap = new LinkedHashMap<>(); for (String keyValuePair : Splitter.on(",").split(propertiesString)) { - List parts = Splitter.on("=").limit(2).splitToList(keyValuePair); - if (parts.size() == 2) { - propertiesMap.put(parts.get(0), parts.get(1)); + List keyValueParts = Splitter.on("=").limit(2).splitToList(keyValuePair); + if (keyValueParts.size() == 2) { + String entryKey = keyValueParts.get(0).trim(); + if (entryKey.isEmpty()) { + throw new BigQueryJdbcRuntimeException( + String.format("Invalid empty key in %s.", propertyName)); + } + if (propertiesMap.containsKey(entryKey)) { + throw new BigQueryJdbcRuntimeException( + String.format( + "Duplicate key '%s' in %s.", + BigQueryConnection.sanitizeForLog(entryKey), propertyName)); + } + propertiesMap.put(entryKey, keyValueParts.get(1)); } else { LOG.warning( "Invalid KeyValue pair: %s found in context: %s for property name: %s", - keyValuePair, context, propertyName); + BigQueryConnection.sanitizeForLog(keyValuePair), context, propertyName); } } return propertiesMap; diff --git a/java-bigquery-jdbc/src/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..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 @@ -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,255 @@ 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 ignored with a warning that does not echo the + // key. + capturedLogs.clear(); + Properties controlKeyProperties = new Properties(); + controlKeyProperties.setProperty("Custom\nKey", "secret-val"); + assertThat( + BigQueryJdbcUrlUtility.appendPropertiesToURL(baseUrl, "Caller", controlKeyProperties)) + .isEqualTo(baseUrl); + assertThat(assertLogContains(BigQueryJdbcUrlUtility.IGNORED_PROPERTY_KEY_WARNING)).isTrue(); + } + + @ParameterizedTest + @ValueSource( + strings = { + "custom_tag=1;EndpointOverrides", + "EndpointOverrides=BIGQUERY=https://127.0.0.1:8443,DUMMY", + "ProjectId;OAuthType", + "Key\r\nInject", + "Key\tTab", + " LeadingSpace", + "TrailingSpace ", + "" + }) + public void 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.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 + public void testParseUrl_noStaticParseCacheRetainingSecrets() { + for (Field field : BigQueryJdbcUrlUtility.class.getDeclaredFields()) { + assertFalse( + "PARSE_CACHE".equals(field.getName()), + "Static PARSE_CACHE must not exist because it retains secret-bearing URLs in heap."); + } + } + + @Test + public void testParseUrl_malformedSegmentDoesNotEchoRawSecretText() { + String secretFragment = "SECRET_PRIVATE_KEY_FRAGMENT_999"; + String connectionUrl = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=p;OAuthAccessToken=top_secret;" + + secretFragment; + + BigQueryJdbcRuntimeException malformedSegmentException = + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> BigQueryJdbcUrlUtility.parseUrl(connectionUrl)); + assertThat(malformedSegmentException.getMessage()).doesNotContain(secretFragment); + assertThat(malformedSegmentException.getMessage()).doesNotContain("top_secret"); + } + + @Test + public void testParsePropertiesMapFromValue_rejectsEmptyKeyAndExactDuplicateAndSanitizesLogs() { + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcUrlUtility.parsePropertiesMapFromValue( + "=orphanValue", "QueryProperties", "Test")); + + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcUrlUtility.parsePropertiesMapFromValue( + "dataset_project_id=tenant_a,dataset_project_id=tenant_b", + "QueryProperties", + "Test")); + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcUrlUtility.parsePropertiesMapFromValue( + "dataset_project_id=tenant_a, dataset_project_id=tenant_b", + "QueryProperties", + "Test")); + + // Case-variant duplicates must still pass through so BigQueryConnection can raise its + // specific case-insensitive session_id duplicate SQLException. + Map caseVariantProperties = + BigQueryJdbcUrlUtility.parsePropertiesMapFromValue( + "session_id=a,Session_Id=b", "QueryProperties", "Test"); + assertThat(caseVariantProperties).containsExactly("session_id", "a", "Session_Id", "b"); + + // Malformed pairs without '=' must sanitize CR/LF before logging a warning. + capturedLogs.clear(); + Map parsedWithMalformedPair = + BigQueryJdbcUrlUtility.parsePropertiesMapFromValue( + "time_zone=UTC,bad\r\nFORGED_LOG", "QueryProperties", "Test"); + assertThat(parsedWithMalformedPair).containsExactly("time_zone", "UTC"); + assertThat(assertLogContains("bad??FORGED_LOG")).isTrue(); + for (LogRecord logRecord : capturedLogs) { + assertThat(logRecord.getMessage()).doesNotContain("\r"); + assertThat(logRecord.getMessage()).doesNotContain("\n"); + } + } + + @Test + public void testParseConnectionUrl_twoPhaseLastWinsAndInvalidPercentEncodingWithoutSecretEcho() { + String connectionUrl = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "LogLevel=7;LogPath=/tmp/first;PartnerToken=(GPN:first;a);" + + "PartnerToken=(GPN:second;b);LogLevel=3;LogPath=/tmp/second;MalformedNoEquals"; + + // Phase 1 must not throw even with a malformed segment and must apply last-wins semantics. + BigQueryJdbcUrlUtility.ParsedConnectionUrl parsedUrl = + BigQueryJdbcUrlUtility.parseConnectionUrl(connectionUrl); + assertThat(parsedUrl.getPreConnectProperty("LogLevel")).isEqualTo("3"); + assertThat(parsedUrl.getPreConnectProperty("LogPath")).isEqualTo("/tmp/second"); + assertThat(parsedUrl.getPreConnectProperty("PartnerToken")).isEqualTo(" (GPN:second;b)"); + + // Phase 2 must throw without echoing the malformed segment. + BigQueryJdbcRuntimeException malformedSegmentException = + assertThrows(BigQueryJdbcRuntimeException.class, parsedUrl::validateAndGetProperties); + assertThat(malformedSegmentException.getMessage()).doesNotContain("MalformedNoEquals"); + assertThrows( + BigQueryJdbcRuntimeException.class, + () -> + BigQueryJdbcUrlUtility.parseUrl( + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443; =value")); + + // Invalid percent-escape inside a secret must not throw in Phase 1 or echo the secret in + // Phase 2. + String invalidPercentEncodingUrl = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=p;OAuthAccessToken=secret%ZZtoken"; + BigQueryJdbcUrlUtility.ParsedConnectionUrl parsedInvalidEncodingUrl = + BigQueryJdbcUrlUtility.parseConnectionUrl(invalidPercentEncodingUrl); + assertThat(parsedInvalidEncodingUrl.toSanitizedDisplayUrl()) + .isEqualTo("jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443"); + BigQueryJdbcRuntimeException invalidEncodingException = + assertThrows( + BigQueryJdbcRuntimeException.class, parsedInvalidEncodingUrl::validateAndGetProperties); + assertThat(invalidEncodingException.getMessage()).doesNotContain("secret"); + assertThat(invalidEncodingException.getMessage()).doesNotContain("%ZZ"); + } + + @Test + public void testSanitizeUrlForDisplay_returnsEndpointOnlyAndNormalizesPrefix() { + assertNull(BigQueryJdbcUrlUtility.sanitizeUrlForDisplay(null)); + assertThat(BigQueryJdbcUrlUtility.sanitizeUrlForDisplay("")).isEqualTo(""); + assertThat( + BigQueryJdbcUrlUtility.sanitizeUrlForDisplay( + "bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "ProjectId=p1;OAuthType=2;OAuthAccessToken=live_secret;" + + "ProxyPwd=proxy_secret;SSLTrustStorePwd=ts_secret;" + + "BYOID_CredentialSource={\"headers\":{\"Authorization\":\"Bearer x\"}};" + + "PartnerToken=(GPN:acme; prod);ProjectId=p2;UnknownCustom=hidden")) + .isEqualTo("jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443"); + assertThat( + BigQueryJdbcUrlUtility.sanitizeUrlForDisplay( + "jdbc:bigquery://h?OAuthAccessToken=x;ProjectId=p")) + .isEqualTo("jdbc:bigquery:"); + } + + @Test + public void testFormatPartnerTokenHeaderValue_doesNotDoubleDecodeAndPreservesLiteralPercent() { + assertNull(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue(null)); + assertNull(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue("(env)")); + assertNull(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue("(GPN:a\r\nX-Evil: 1)")); + assertThat(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue("(GPN:partner; prod)")) + .isEqualTo(" (GPN:partner; prod)"); + // Discrete Properties/DataSource inputs are already unencoded and must preserve literal '%xx'. + assertThat(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue("(GPN:partner%20name)")) + .isEqualTo(" (GPN:partner%20name)"); + + // URL parsing decodes percent-escapes once; re-formatting the result is idempotent. + String encodedPartnerTokenUrl = + "jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;" + + "PartnerToken=%28GPN%3Apartner%2520name%3Bprod%29"; + String parsedPartnerToken = + BigQueryJdbcUrlUtility.parseConnectionUrl(encodedPartnerTokenUrl) + .validateAndGetProperties() + .get(BigQueryJdbcUrlUtility.PARTNER_TOKEN_PROPERTY_NAME); + assertThat(parsedPartnerToken).isEqualTo(" (GPN:partner%20name;prod)"); + assertThat(BigQueryJdbcUrlUtility.formatPartnerTokenHeaderValue(parsedPartnerToken)) + .isEqualTo(" (GPN:partner%20name;prod)"); + } + + @Test + public void testSafeToLogProperties_exhaustivelyClassifiesEveryKnownProperty() { + // Explicit test-only inventory of known PROPERTY_NAME_MAP keys that must NOT be in + // SAFE_TO_LOG_PROPERTIES (sensitive credentials + internal endpoint-override sub-keys). + Set expectedNonAllowlistedProperties = + ImmutableSet.of( + BigQueryJdbcUrlUtility.OAUTH_PVT_KEY_PROPERTY_NAME, + BigQueryJdbcUrlUtility.OAUTH_ACCESS_TOKEN_PROPERTY_NAME, + BigQueryJdbcUrlUtility.OAUTH_REFRESH_TOKEN_PROPERTY_NAME, + BigQueryJdbcUrlUtility.OAUTH_CLIENT_SECRET_PROPERTY_NAME, + BigQueryJdbcUrlUtility.OAUTH_P12_PASSWORD_PROPERTY_NAME, + BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME, + BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME, + BigQueryJdbcUrlUtility.SSL_TRUST_STORE_PWD_PROPERTY_NAME, + BigQueryJdbcUrlUtility.GCP_TELEMETRY_CREDENTIALS_PROPERTY_NAME, + BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME, + BigQueryJdbcUrlUtility.BIGQUERY_ENDPOINT_OVERRIDE_PROPERTY_NAME, + BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME, + BigQueryJdbcUrlUtility.HTAPI_ENDPOINT_OVERRIDE_PROPERTY_NAME, + BigQueryJdbcUrlUtility.STS_ENDPOINT_OVERRIDE_PROPERTY_NAME); + + for (String canonicalPropertyName : BigQueryJdbcUrlUtility.PROPERTY_NAME_MAP.values()) { + boolean isAllowlisted = BigQueryConnection.isSafeToLogProperty(canonicalPropertyName); + boolean isExpectedNonAllowlisted = + expectedNonAllowlistedProperties.contains(canonicalPropertyName); + assertFalse( + isAllowlisted == isExpectedNonAllowlisted, + "Unclassified property: " + canonicalPropertyName); + } + assertFalse(BigQueryConnection.isSafeToLogProperty(null)); + assertFalse(BigQueryConnection.isSafeToLogProperty("UnknownCustomSecret")); } }