Gabriel39 commented on code in PR #71205:
URL: https://github.com/apache/doris/pull/71205#discussion_r4779100253


##########
fe/fe-core/src/main/java/org/apache/doris/connector/JdbcEndpointParser.java:
##########
@@ -0,0 +1,728 @@
+// 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 org.apache.doris.foundation.security.JdbcProxyPropertySecurity;
+import org.apache.doris.foundation.security.JdbcTlsStoreUrlSecurity;
+
+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> sap(String url) {
+        String proxyHostName = "";
+        int query = url.indexOf('?');
+        if (query >= 0) {
+            // HANA selects the last value of a canonical raw key; bare 
options do not clear a value.
+            // Its driver splits before value decoding, and a nonempty proxy 
host is active in both modes.
+            for (String token : url.substring(query + 1).split("&")) {
+                int equals = token.indexOf('=');
+                if (equals >= 0 && 
JdbcProxyPropertySecurity.isHanaProxyHostProperty(token.substring(0, equals))) {
+                    proxyHostName = token.substring(equals + 1);
+                }
+            }
+        }
+        List<HostAndPort> result = new ArrayList<>();
+        for (String endpoint : 
JdbcProxyPropertySecurity.hanaProxyEndpointValues("proxyHostName", 
proxyHostName)) {
+            result.addAll(CatalogEndpointSecurity.parseEndpoints(endpoint, 
-1));
+        }
+        // The remaining query options (including URL-shaped WebSocket paths 
and passwords) keep the base peer.
+        result.addAll(CatalogEndpointSecurity.parseEndpoints(url.substring(5), 
-1));
+        return result;
+    }
+
+    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> mariaDb(String url) {
+        String prefix = "jdbc:mariadb://";
+        if (!url.startsWith(prefix)) {
+            throw new IllegalArgumentException("Unsupported MariaDB connection 
form");
+        }
+        int query = url.indexOf('?');
+        String server = url.substring(prefix.length(), query < 0 ? 
url.length() : query);
+        int slash = server.indexOf('/');
+        String authority = slash < 0 ? server : server.substring(0, slash);
+        if (authority.contains("(") || authority.contains(")") || 
authority.contains("@")) {
+            throw new IllegalArgumentException("Unsupported MariaDB host 
descriptor");
+        }
+        List<HostAndPort> result = new ArrayList<>();
+        for (String host : authority.split(",", -1)) {
+            result.add(CatalogEndpointSecurity.parseAuthority(host.trim(), 
3306));
+        }
+        Map<String, String> properties = new LinkedHashMap<>();
+        if (query >= 0) {
+            // MariaDB splits raw options before case-insensitive binding, 
without URI decoding or
+            // fragment removal. Only duplicates with the exact same spelling 
replace one another.
+            for (String token : url.substring(query + 1).split("&")) {
+                int equals = token.indexOf('=');
+                String key = equals < 0 ? token : token.substring(0, equals);
+                if (JdbcTlsStoreUrlSecurity.isMariaDbStoreUrlProperty(key)) {
+                    properties.put(key, equals < 0 ? "" : 
token.substring(equals + 1));
+                }
+            }
+        }
+        for (String value : properties.values()) {
+            for (String endpoint : 
JdbcTlsStoreUrlSecurity.mariaDbEndpointValues(value)) {
+                result.addAll(CatalogEndpointSecurity.parseEndpoints(endpoint, 
-1));
+            }
+        }
+        return result;
+    }
+
+    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 converts bare host tokens to empty strings and still 
selects its SOCKS factory.
+        // Probing only the database authority cannot admit this different 
transport destination.
+        String discovery = properties.get("dnsSrv");
+        if (properties.containsKey("socksProxyHost") || (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);

Review Comment:
   Fixed in 03940257960. Iceberg/Paimon admission now combines each MySQL URI 
alias with the supplied jdbc.port properties, including case variants and 
Paimon common aliases. Supplied defaults override query defaults; an explicit 
authority port retains precedence, including over an invalid inert fallback. 
Empty/-1 defaults and raw Properties values keep the driver's semantics. 
Conflicting case-alias defaults fail closed only when a fallback is needed, and 
projection is bounded rather than copying a large URI per alias. The separate 
MariaDB interpretation of an accepted MySQL-scheme URL retains its original 
fragment/TLS syntax.
   
   Validation passed on the exact committed candidate: 93-module FE Checkstyle, 
129 classes / 2224 tests with zero failures/errors/skips, fresh FE 
packaging/API checks, and real SQL with 330 expected policy refusals, 17 
positive CREATE admissions and 18 successful ALTERs. Five new CREATE controls 
distinguish forbidden port 1544 from the allowed URL/query defaults on the same 
host. ALTER controls reject supplied fallbacks and removal of an explicit port; 
a later successful warehouse ALTER under the same rejecting port policy proves 
the rejected URI was not published, without reading its masked value. The 
driver/pool precedence was traced through pinned primary sources; these SQL 
checks do not claim a live JDBC connection.



##########
fe/fe-foundation/src/main/java/org/apache/doris/foundation/security/JdbcTlsStoreUrlSecurity.java:
##########
@@ -0,0 +1,141 @@
+// 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.foundation.security;
+
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.LinkedHashSet;
+import java.util.List;
+
+/** Projects JDBC TLS material destinations without loading a driver or 
opening a resource. */
+public final class JdbcTlsStoreUrlSecurity {
+    private static final List<String> UNMODELED_ENDPOINT = 
List.of("http://unmodeled-jdbc-tls-store:0";);
+
+    private JdbcTlsStoreUrlSecurity() {
+    }
+
+    /** These classic JDBC option names are case-sensitive in Connector/J. */
+    public static boolean isStoreUrlProperty(String key) {
+        return key.equals("clientCertificateKeyStoreUrl") || 
key.equals("trustCertificateKeyStoreUrl");
+    }
+
+    public static boolean isMariaDbStoreUrlProperty(String key) {
+        // MariaDB binds native names and these Connector/J aliases 
case-insensitively.
+        return "serverSslCert".equalsIgnoreCase(key) || 
"keyStore".equalsIgnoreCase(key)
+                || "trustStore".equalsIgnoreCase(key) || 
"clientCertificateKeyStoreUrl".equalsIgnoreCase(key)
+                || "trustCertificateKeyStoreUrl".equalsIgnoreCase(key);
+    }
+
+    public static boolean mayUseMariaDb(String uri, String driverClass) {
+        if (driverClass != null && 
driverClass.trim().equals("org.mariadb.jdbc.Driver")) {
+            return true;
+        }
+        if (uri == null) {
+            return false;
+        }
+        String url = uri.trim();
+        return url.startsWith("jdbc:mariadb:")
+                || (url.startsWith("jdbc:mysql:") && 
url.contains("permitMysqlScheme"));
+    }
+
+    public static List<String> storePropertyEndpointValues(String key, String 
value, boolean mariaDb) {
+        LinkedHashSet<String> endpoints = new LinkedHashSet<>();
+        if (isStoreUrlProperty(key)) {

Review Comment:
   Fixed in 03940257960. A definitive native jdbc:mariadb: URI now selects 
MariaDB's material grammar for supplied canonical Connector/J aliases, so a 
local path or inline PEM is not rejected by an inapplicable Connector/J 
interpretation. Both grammars remain checked where a MySQL URI can admit both 
drivers; ordinary MySQL retains its exact suffix case and unsupported-store 
refusals. URI changes still recheck stored aliases.
   
   Canonical client/trust aliases now have native MariaDB admission controls 
for local and relative paths and inline PEM, including CREATE followed by 
ALTER. The real SQL fixture admits both canonical aliases, updates them 
successfully, preserves all nine default-masked URI/material/password fields, 
and retains the unique certificate-peer recheck after rejected updates. The 
exact committed candidate passed all 2224 selected tests, 93-module FE 
Checkstyle, fresh packaging and both SQL suites. No keystore/certificate read 
or live MariaDB connection 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]

Reply via email to