hello-stephen commented on code in PR #71205: URL: https://github.com/apache/doris/pull/71205#discussion_r4777415853
########## 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: [P2] Use MariaDB store semantics for an exclusively MariaDB URI With enforcement enabled, an Iceberg JDBC catalog explicitly using the MariaDB driver and `iceberg.jdbc.uri=jdbc:mariadb://allowed.example.com:3306/db` cannot supply `jdbc.clientCertificateKeyStoreUrl=/fixtures/client.jks`: this branch first applies Connector/J's parser and retains its invalid port-zero endpoint. [MariaDB 3.5.6 maps that alias to `keyStore`](https://github.com/mariadb-corporation/mariadb-connector-j/blob/3.5.6/src/main/java/org/mariadb/jdbc/util/options/OptionAliases.java#L15), whose [loader accepts local paths](https://github.com/mariadb-corporation/mariadb-connector-j/blob/3.5.6/src/main/java/org/mariadb/jdbc/plugin/tls/main/DefaultTlsSocketPlugin.java#L59-L64). Connector/J cannot consume this MariaDB-only URI. The identical path already passes with the uppercase alias or native `jdbc.keyStore`, so the union rejects a valid local configuration on CREATE, reconstruction and ALTER. Select the applicable driver grammar for definitive MariaDB routing; retain the uni on where both drivers can apply, and add a canonical-case local-alias admission test. ########## 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: [P2] Include supplied MySQL port properties in endpoint admission An Iceberg JDBC catalog with `iceberg.jdbc.uri=jdbc:mysql://allowed.example.com/db` and `jdbc.port=1544` is checked only at `allowed.example.com:3306`. `IcebergCatalogFactory` retains the supplied option; [Iceberg 1.12's pool](https://github.com/apache/iceberg/blob/apache-iceberg-1.12.0/core/src/main/java/org/apache/iceberg/jdbc/JdbcClientPool.java#L78-L81) passes it to the driver, and [Connector/J 8.4](https://github.com/mysql/mysql-connector-j/blob/8.4.0/src/main/core-api/java/com/mysql/cj/conf/ConnectionUrl.java#L459-L470) uses that port when the URL authority omits one. Consequently a policy allowing port 3306 but rejecting 1544 never checks the effective destination during CREATE with `test_connection=false` or ALTER. Resolve destinations from the URL and supplied driver properties together, preserving explicit authority-port precedence, and cover rejecting CREATE/ALTER plus an explicit-port control. This is an admission mismatch; runtime interception remains separate. ########## fe/fe-filesystem/fe-filesystem-api/src/main/java/org/apache/doris/filesystem/properties/StorageEndpointProperties.java: ########## @@ -0,0 +1,129 @@ +// 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.filesystem.properties; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.function.Predicate; + +/** Network endpoint aliases consumed by filesystem providers and their authentication clients. */ +public final class StorageEndpointProperties { + private static final List<String> PAIMON_STORAGE_PREFIXES = List.of( + "paimon.s3.", "paimon.s3a.", "paimon.fs.s3.", "paimon.fs.oss."); + + private StorageEndpointProperties() { + } + + /** + * Shared aliases can reach different SDKs; require an explicit scheme or port instead of guessing it. + * @throws IllegalArgumentException if a proxy route cannot be established from independent endpoint values + */ + public static Map<String, Integer> endpoints(Map<String, String> properties, Predicate<String> opaqueCredential) { + Map<String, Integer> endpoints = new LinkedHashMap<>(); + // OSS-HDFS prefers its specific alias over oss.endpoint before emitting fs.oss.endpoint. + for (String key : new String[] {"s3.endpoint", "AWS_ENDPOINT", "endpoint", "ENDPOINT", "aws.endpoint", Review Comment: [P2] Check S3 endpoints derived from region-only properties For a Paimon filesystem catalog with `warehouse=s3://bucket/warehouse`, `fs.s3.support=true`, AK/SK, `s3.region=us-east-1`, `use_path_style=true` and no explicit endpoint, this extractor selects no storage peer. However, `S3FileSystemProperties.normalizeForLegacyS3Compatibility` builds `https://s3.us-east-1.amazonaws.com`, and `toHadoopConfigurationMap` exports it as `fs.s3a.endpoint` to Paimon FileIO; [Hadoop's client factory](https://github.com/apache/hadoop/blob/rel/release-3.4.2/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/DefaultS3ClientFactory.java#L271-L322) uses that endpoint override. A configured policy rejecting this host therefore rejects an explicit identical endpoint but never sees the region-only destination on CREATE with `test_connection=false` or ALTER. Resolve and check the effective derived endpoint, including supported region aliases, with rejecting CREATE/ALTER and valid-region controls. This concerns statement admission, not a demonstrated runtime-hook bypass. -- 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]
