Gabriel39 commented on code in PR #71205: URL: https://github.com/apache/doris/pull/71205#discussion_r4774335572
########## fe/fe-core/src/main/java/org/apache/doris/connector/JdbcEndpointParser.java: ########## @@ -0,0 +1,610 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector; + +import com.google.common.net.HostAndPort; + +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** Extracts literal destinations without loading the user-selected JDBC driver during admission. */ +final class JdbcEndpointParser { + private static final Pattern ORACLE_SID = Pattern.compile("^(\\[[^\\]]+\\]|[^:/?]+):(\\d+):([^:/?]+)$"); + private static final Pattern MYSQL_HOST_PORT = Pattern.compile("^(\\[[^\\]]+\\]|[^:]*)(?::([^:]*))?$"); + + private JdbcEndpointParser() { + } + + static List<HostAndPort> oceanbase(String url) { + String prefix = "jdbc:oceanbase://"; + if (!url.startsWith(prefix)) { + throw new IllegalArgumentException("Unsupported OceanBase discovery or connection form"); + } + int query = url.indexOf('?', prefix.length()); + Map<String, String> properties = oceanbaseProperties(query < 0 ? "" : url.substring(query + 1)); + // These transports can select a peer independently of the URL's literal database authorities. + for (String key : new String[] {"socksProxyHost", "socketFactory", "pipe", "localSocket", + "sharedMemory", "obProxySocket"}) { + if (properties.containsKey(key)) { + throw new IllegalArgumentException("Unsupported OceanBase socket routing"); + } + } + Integer overridePort = properties.containsKey("port") ? Integer.parseInt(properties.get("port")) : null; + int slash = url.indexOf('/', prefix.length()); + int end = slash < 0 ? url.length() : slash; + if (query >= 0) { + end = Math.min(end, query); + } + String authority = url.substring(prefix.length(), end); + if (authority.contains("(") || authority.contains(")") || authority.contains("@")) { + throw new IllegalArgumentException("Unsupported OceanBase authority"); + } + List<HostAndPort> result = new ArrayList<>(); + for (String value : authority.trim().split(",")) { + String address = value.trim(); + if (!address.startsWith("[") && address.indexOf(':') != address.lastIndexOf(':')) { + throw new IllegalArgumentException("OceanBase IPv6 requires a literal port"); + } + String host; + int literalPort; + if (address.startsWith("[")) { + int closing = address.indexOf(']'); + if (closing < 0 || (closing + 1 < address.length() && address.charAt(closing + 1) != ':')) { + throw new IllegalArgumentException("Invalid OceanBase IPv6 authority"); + } + host = address.substring(1, closing); + // Bracketed IPv6 defaults to zero in this driver; only a query override can make it valid. + literalPort = closing + 1 == address.length() ? 0 + : Integer.parseInt(address.substring(closing + 2)); + } else { + int colon = address.indexOf(':'); + host = colon < 0 ? address : address.substring(0, colon); + literalPort = colon < 0 ? 3306 : Integer.parseInt(address.substring(colon + 1)); + } + // OceanBase's query port replaces even explicit per-host ports, rather than acting as a fallback. + result.add(endpoint(host, overridePort == null ? literalPort : overridePort)); + } + if (result.isEmpty()) { + throw new IllegalArgumentException("Missing OceanBase peer"); + } + return result; + } + + private static Map<String, String> oceanbaseProperties(String query) { + Map<String, String> properties = new LinkedHashMap<>(); + char quote = 0; + // The driver uses this initial lookbehind and asymmetric quote rules, even for an unknown first key. + char previous = query.isEmpty() ? 0 : query.charAt(0); + int start = 0; + for (int position = 0; position <= query.length(); position++) { + if (position == query.length() || (query.charAt(position) == '&' && quote == 0)) { + String token = query.substring(start, position); + int equals = token.indexOf('='); + String key = equals < 0 ? token : token.substring(0, equals); + String value = equals < 0 ? "" : token.substring(equals + 1); + // Keys/values stay undecoded, '#' is literal, and the first exact-key occurrence wins. + properties.putIfAbsent(key, value); + start = position + 1; + } + if (position == query.length()) { + break; + } + char character = query.charAt(position); + if (quote == 0) { + if ((character == '\'' && previous != '\\') || (character == '"' && previous != '"')) { + quote = character; + } + } else if (character == quote && previous != '\\') { + quote = 0; + } + previous = character; + } + return properties; + } + + static List<HostAndPort> trinoOrPresto(String url) { + URI uri = URI.create(url.substring("jdbc:".length())); + if (uri.getHost() == null || uri.getPort() < 1) { + throw new IllegalArgumentException("Trino/Presto require a literal coordinator and port"); + } + // Trino/Presto decode the entire query before splitting; an encoded '&' can introduce a proxy option. + String query = uri.getQuery(); + if (query != null) { + for (String token : query.split("&")) { + String key = token.split("=", 2)[0]; + if (key.equals("httpProxy") || key.equals("socksProxy")) { + throw new IllegalArgumentException("Unsupported Trino/Presto proxy routing"); + } + } + } + return List.of(endpoint(uri.getHost(), uri.getPort())); + } + + static List<HostAndPort> clickhouse(String url) { + // The driver selects its legacy grammar by raw substring, even inside a path or fragment. + if (url.contains("clickhouse.jdbc.v1=true") || url.contains("clickhouse.jdbc.v2=false") + || Boolean.getBoolean("clickhouse.jdbc.v1")) { + throw new IllegalArgumentException("Legacy ClickHouse routing requires a separate parser"); + } + String body = url.substring(url.startsWith("jdbc:ch:") ? "jdbc:ch:".length() : "jdbc:clickhouse:".length()); + URI uri = URI.create(body.startsWith("//") ? "http:" + body : body); + if (!("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) || uri.getHost() == null) { + throw new IllegalArgumentException("Unsupported ClickHouse transport or authority"); + } + Map<String, String> properties = new LinkedHashMap<>(); + if (uri.getRawQuery() != null) { + for (String token : uri.getRawQuery().split("&")) { + String[] pair = token.split("=", 2); + if (pair.length != 2) { + throw new IllegalArgumentException("Invalid ClickHouse URL property"); + } + String key = URLDecoder.decode(pair[0], StandardCharsets.UTF_8).trim(); + String value = URLDecoder.decode(pair[1], StandardCharsets.UTF_8); + // connection_url replaces the whole authority; proxy settings select another network peer. + if (key.equals("connection_url") || key.equals("proxy_host") || key.equals("proxy_port") + || key.equals("proxy_type")) { + throw new IllegalArgumentException("Unsupported ClickHouse URL routing"); + } + properties.put(key, value); + } + } + // ClickHouse's implicit HTTP(S) ports differ from the generic URI defaults, including ssl=true. + boolean secure = "https".equals(uri.getScheme()) || Boolean.parseBoolean(properties.get("ssl")); + return List.of(endpoint(uri.getHost(), uri.getPort() < 0 ? (secure ? 8443 : 8123) : uri.getPort())); + } + + static List<HostAndPort> db2(String url) { + String prefix = "jdbc:db2://"; + if (!url.startsWith(prefix)) { + throw new IllegalArgumentException("Unsupported DB2 connection form or alias"); + } + int slash = url.indexOf('/', prefix.length()); + if (slash < 0) { + throw new IllegalArgumentException("Missing DB2 database"); + } + int separator = url.indexOf(':', slash); + if (separator >= 0) { + for (String token : url.substring(separator + 1).split(";")) { + int equals = token.indexOf('='); + String key = (equals < 0 ? token : token.substring(0, equals)).trim().toLowerCase(Locale.ROOT); + // JCC can route through configured alternate servers or a JNDI list without server discovery. + if (key.equals("clientreroutealternateservername") || key.equals("clientreroutealternateportnumber") + || key.equals("alternategroupservername") || key.equals("alternategroupportnumber") + || key.equals("clientrerouteserverlistjndiname")) { + throw new IllegalArgumentException("Unsupported DB2 client reroute"); + } + } + } + return List.of(CatalogEndpointSecurity.parseAuthority(url.substring(prefix.length(), slash), 446)); + } + + static List<HostAndPort> mysql(String url) { + String prefix = "jdbc:mysql://"; + if (!url.regionMatches(true, 0, prefix, 0, prefix.length())) { + throw new IllegalArgumentException("Unsupported MySQL discovery or connection scheme"); + } + int fragment = url.indexOf('#'); + String literal = fragment < 0 ? url : url.substring(0, fragment); + int query = literal.indexOf('?'); + Map<String, String> properties = mysqlProperties(query < 0 ? "" : literal.substring(query + 1)); + // Connector/J selects its SOCKS factory for any non-null host, including an empty string. + // Probing only the database authority cannot admit this different transport destination. + String discovery = properties.get("dnsSrv"); + if (properties.get("socksProxyHost") != null || (discovery != null && !discovery.isEmpty() + && !discovery.equalsIgnoreCase("false") && !discovery.equalsIgnoreCase("no"))) { + throw new IllegalArgumentException("MySQL proxy and DNS discovery require literal destinations"); + } + List<String> fallbackPorts = new ArrayList<>(); + properties.forEach((key, value) -> { + if (key.equalsIgnoreCase("port")) { + fallbackPorts.add(value); + } + }); + String server = literal.substring(prefix.length(), query < 0 ? literal.length() : query); + int slash = server.indexOf('/'); + String authority = slash < 0 ? server : server.substring(0, slash); + if (authority.contains("(") || authority.contains(")")) { + throw new IllegalArgumentException("Unsupported MySQL host descriptor"); + } + Integer fallbackPort = null; + List<HostAndPort> result = new ArrayList<>(); + // MySQL credentials belong to each host segment; authority-wide stripping hides earlier hosts. + for (String segment : authority.split(",", -1)) { + int userinfo = segment.indexOf('@'); + if (userinfo >= 0) { + URLDecoder.decode(segment.substring(0, userinfo), StandardCharsets.UTF_8); + } + String target = segment.substring(userinfo + 1).trim(); + Matcher address = MYSQL_HOST_PORT.matcher(target); + if (!address.matches()) { + throw new IllegalArgumentException("Unsupported MySQL host list"); + } + String host = URLDecoder.decode(address.group(1).trim(), StandardCharsets.UTF_8); + String rawPort = address.group(2); + String decodedPort = rawPort == null ? "" : URLDecoder.decode(rawPort.trim(), StandardCharsets.UTF_8); + int port = decodedPort.isEmpty() ? -1 : Integer.parseInt(decodedPort); + if (port == -1 && fallbackPort == null) { + // The driver normalizes case after HashMap collection, so mixed-case aliases have no + // token-order precedence. Only an unambiguous fallback can select a literal destination. + if (fallbackPorts.size() > 1) { + throw new IllegalArgumentException("Ambiguous MySQL port aliases"); + } + String fallback = fallbackPorts.isEmpty() ? null : fallbackPorts.get(0); + int configuredPort = fallback == null || fallback.isEmpty() ? 3306 : Integer.parseInt(fallback); + // Connector/J treats -1 as an omitted port even when explicitly supplied in the URL. + fallbackPort = configuredPort == -1 ? 3306 : configuredPort; + } + result.add(endpoint(host, port == -1 ? fallbackPort : port)); + } + return result; + } + + private static Map<String, String> mysqlProperties(String query) { + Map<String, String> properties = new LinkedHashMap<>(); + for (String token : query.split("&")) { + int equals = token.indexOf('='); + String key = URLDecoder.decode((equals < 0 ? token : token.substring(0, equals)).trim(), + StandardCharsets.UTF_8); + String value = equals < 0 ? null : URLDecoder.decode(token.substring(equals + 1).trim(), + StandardCharsets.UTF_8); + if (key.equalsIgnoreCase("port") || key.equals("socksProxyHost") || key.equals("dnsSrv")) { Review Comment: Fixed in b2669e792d9ebe9e534e57069d5ee7625711cdc6. The shared MySQL URL parser now checks both clientCertificateKeyStoreUrl and trustCertificateKeyStoreUrl independently of the database peer. Iceberg and Paimon also project supplied jdbc.* values; Paimon includes its paimon.jdbc.* aliases with the consumer’s exact case rules. Every configured/stored location is checked because supplied driver properties can replace SSL mode, store type or URL settings on a later ALTER. The projection follows Connector/J query decoding/last-duplicate semantics and the JDK URL constructor, including url: prefixes and local file forms. HTTP(S) peers enter the existing policy. Remote file authorities (which can delegate to FTP), FTP/JAR and other unmodeled routes fail closed with enforcement enabled. Empty options preserve operator fallback without reading system settings. Store URLs/passwords are explicitly masked even when the optional sensitive-name pattern is disabled; passwords and type values never become peers. Validation: the omission first reproduced 16 assertion failures; the actual redactor separately reproduced one privacy failure. The final candidate passed FE Checkstyle, 129 selected classes / 1986 tests, both compiled SPI baselines and forced FE packaging. Real SQL passed 119 CREATE + 76 ALTER policy rejections, 10 allowed CREATEs and 4 successful ALTERs. A subsequent rejected ALTER proves admission observes the persisted updated store peer while all four present URI/store/password fields remain masked and rejected new properties remain absent. These are admission/source-contract checks; no live MySQL TLS connection or keystore fetch is claimed. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
