hello-stephen commented on code in PR #71205: URL: https://github.com/apache/doris/pull/71205#discussion_r4776492492
########## fe/fe-core/src/main/java/org/apache/doris/connector/CatalogEndpointSecurity.java: ########## @@ -0,0 +1,309 @@ +// 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.cloud.security.SecurityChecker; +import org.apache.doris.common.DdlException; +import org.apache.doris.common.util.DatasourcePrintableMap; +import org.apache.doris.common.util.DebugPointUtil; +import org.apache.doris.common.util.DebugPointUtil.DebugPoint; +import org.apache.doris.connector.spi.ConnectorSecuritySurface; +import org.apache.doris.filesystem.properties.HdfsEndpointProperties; +import org.apache.doris.filesystem.properties.StorageEndpointProperties; + +import com.google.common.net.HostAndPort; +import com.google.common.net.InetAddresses; + +import java.net.IDN; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** Shared endpoint admission for root and indirectly created catalog connectors. */ +public final class CatalogEndpointSecurity { + private static final String REJECT_HOST_POINT = "CatalogEndpointSecurity.reject_host"; + + private CatalogEndpointSecurity() { + } + + public static boolean isEnabled() { + return SecurityChecker.getInstance().isEnabled() || DebugPointUtil.isEnable(REJECT_HOST_POINT); + } + + public static void validate(String catalogName, ConnectorSecuritySurface surface, Map<String, String> properties) + throws DdlException { + SecurityChecker checker = SecurityChecker.getInstance(); + DebugPoint rejection = DebugPointUtil.getDebugPoint(REJECT_HOST_POINT); + if (!checker.isEnabled() && rejection == null) { + return; + } + Map<String, Integer> storageEndpoints; + try { + storageEndpoints = StorageEndpointProperties.endpoints(properties, DatasourcePrintableMap::isSensitiveKey); + } catch (IllegalArgumentException e) { + // Storage routing can fail before URI parsing; never expose credential-bearing option values. + throw new DdlException("Cannot validate shared storage routing against the SSRF policy"); + } + Map<String, Integer> endpoints = new LinkedHashMap<>(storageEndpoints); + for (String key : surface.ssrfEndpointKeys(properties)) { + int defaultPort = surface.ssrfEndpointDefaultPort(key); + endpoints.put(key, defaultPort < 0 ? endpoints.getOrDefault(key, -1) : defaultPort); + } + // Driver downloads can connect during pre-validation, before a connector's connectivity test. + String flavor = surface.jdbcDriverUrlFlavorKey(); + String flavorValue = flavor == null ? "jdbc" : properties.getOrDefault(flavor, "").trim(); + if ("jdbc".equalsIgnoreCase(flavorValue)) { + for (String key : surface.jdbcDriverUrlKeys()) { + String value = properties.getOrDefault(key, "").trim().toLowerCase(Locale.ROOT); + if (value.startsWith("http://") || value.startsWith("https://")) { + endpoints.put(key, -1); + } + } + } + // Validate every candidate on ALTER: a flavor/authentication change can activate a stored address + // without modifying its key. Replays never enter this statement-time path. + Map<String, List<HostAndPort>> parsedEndpoints = new LinkedHashMap<>(); + for (Map.Entry<String, Integer> entry : endpoints.entrySet()) { + String key = entry.getKey(); + String value = properties.get(key); + List<HostAndPort> destinations; + try { + destinations = new ArrayList<>(); + for (String endpoint : surface.ssrfEndpointValues(key, value)) { + // A provider can derive destinations even when this raw property is absent. + if (endpoint == null || endpoint.trim().isEmpty()) { + continue; + } + if (endpoint.contains("${")) { + throw new DdlException("Endpoint property '" + key + "' must be literal under the SSRF policy; " + + "a placeholder can change its destination after validation"); + } + if (storageEndpoints.getOrDefault(key, -1) == 8020) { + for (String authority : HdfsEndpointProperties.authorities(endpoint.trim(), properties)) { + destinations.add(parseAuthority(authority, 8020)); + } + } else { + destinations.addAll(parseEndpoints(endpoint.trim(), entry.getValue())); + } + } + } catch (IllegalArgumentException e) { + // Do not echo URLs: their authority or query can carry credentials. + throw new DdlException("Cannot validate endpoint property '" + key + "' of catalog '" + + catalogName + "' against the SSRF policy: use an explicit network URI or host:port"); + } + parsedEndpoints.put(key, destinations); + } + for (Map.Entry<String, List<HostAndPort>> entry : parsedEndpoints.entrySet()) { + String key = entry.getKey(); + for (HostAndPort destination : entry.getValue()) { + // A fail-only seam lets SQL regression tests exercise routing without the optional SDK. + // It cannot bypass a real policy rejection or allow a connection. + if (rejection != null && destination.getHost().equals(rejection.param("host", "127.0.0.1"))) { + throw new DdlException("Endpoint property '" + key + "' is rejected by the SSRF policy"); + } + checker.checkEndpointForSsrf(destination.getHost(), destination.getPort()); + } + } + } + + /** Parses URI lists, multi-host authorities and scheme-less endpoints without splitting URL path commas. */ + public static List<HostAndPort> parseEndpoints(String value, int defaultPort) { + String normalized = value.trim(); + List<HostAndPort> result = parseUnnormalizedEndpoints(normalized, defaultPort); + if (normalized.regionMatches(true, 0, "jdbc:", 0, 5) && normalized.contains(" ")) { + // Standalone JDBC strips spaces; Paimon and Iceberg pass the raw URL to their drivers. + // Checking both interpretations prevents normalization from hiding an active host override. + LinkedHashSet<HostAndPort> destinations = new LinkedHashSet<>(result); + destinations.addAll(parseUnnormalizedEndpoints(normalized.replace(" ", ""), defaultPort)); + return new ArrayList<>(destinations); + } + return result; + } + + private static List<HostAndPort> parseUnnormalizedEndpoints(String normalized, int defaultPort) { + List<HostAndPort> result = new ArrayList<>(); + // JDBC-specific parameters and Oracle descriptors are not ordinary URI authorities. + if (normalized.regionMatches(true, 0, "jdbc:mysql:", 0, 11) + || normalized.regionMatches(true, 0, "jdbc:mysql+srv:", 0, 15)) { + return JdbcEndpointParser.mysql(normalized); + } + if (normalized.startsWith("jdbc:oceanbase:")) { + return JdbcEndpointParser.oceanbase(normalized); + } + if (normalized.startsWith("jdbc:postgresql:")) { + return JdbcEndpointParser.postgresql(normalized); + } + if (normalized.startsWith("jdbc:sqlserver://")) { + return JdbcEndpointParser.sqlServer(normalized); + } + if (normalized.startsWith("jdbc:oracle:thin:")) { + return JdbcEndpointParser.oracle(normalized); + } + if (normalized.startsWith("jdbc:clickhouse:") || normalized.startsWith("jdbc:ch:")) { + return JdbcEndpointParser.clickhouse(normalized); + } + if (normalized.startsWith("jdbc:trino:") || normalized.startsWith("jdbc:presto:")) { + return JdbcEndpointParser.trinoOrPresto(normalized); + } + if (normalized.startsWith("jdbc:sap:")) { + return JdbcEndpointParser.sap(normalized); + } + if (normalized.startsWith("jdbc:db2:") || normalized.startsWith("jdbc:ibmdb:") + || normalized.startsWith("jdbc:ids:") || normalized.startsWith("jdbc:informix-sqli:") + || normalized.startsWith("jdbc:db2os390:") || normalized.startsWith("jdbc:db2os390sqlj:")) { + return JdbcEndpointParser.db2(normalized); + } + if (normalized.startsWith("postgresql://") || normalized.startsWith("postgres://")) { + validateNativePostgresql(normalized); + parseSingle(normalized, defaultPort, result); + return result; + } + if (normalized.startsWith("jdbc:")) { Review Comment: [P2] Include MariaDB TLS URLs in endpoint admission With enforcement enabled and an operator-installed MariaDB driver, `jdbc:mariadb://allowed.example.com:3306/db?sslMode=verify-ca&serverSslCert=http://127.0.0.1:9000/cert` falls through here and probes only the database authority. `JdbcDbType.parseFromUrl` explicitly supports this scheme and `JdbcUrlNormalizer` preserves the option; [MariaDB 3.5.6's TLS implementation](https://github.com/mariadb-corporation/mariadb-connector-j/blob/3.5.6/src/main/java/org/mariadb/jdbc/plugin/tls/main/DefaultTlsSocketPlugin.java#L66-L78) opens `serverSslCert` as a URL before parsing the certificate. CREATE with `test_connection=false` and ALTER therefore admit an independent HTTP peer without applying the endpoint policy. Model MariaDB's TLS locations, or reject unmodeled remote locations under enforcement, and add rejecting CREATE/ALTER cases plus allowed/local controls. Later sanitization/runtime hooks are separate; this does not establish a runtime bypass. ########## fe/fe-core/src/main/java/org/apache/doris/connector/JdbcEndpointParser.java: ########## @@ -0,0 +1,644 @@ +// 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> 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); + 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)); + } + // Supplied driver Properties can replace URL TLS mode/type, so check every configured store location. + for (Map.Entry<String, String> entry : properties.entrySet()) { + if (JdbcTlsStoreUrlSecurity.isStoreUrlProperty(entry.getKey())) { + for (String endpoint : JdbcTlsStoreUrlSecurity.endpointValues(entry.getValue())) { + result.addAll(CatalogEndpointSecurity.parseEndpoints(endpoint, -1)); + } + } + } + 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") + || JdbcTlsStoreUrlSecurity.isStoreUrlProperty(key)) { + properties.put(key, value); + } + } + return properties; + } + + static List<HostAndPort> postgresql(String url) { + int query = url.indexOf('?'); + String server = url.substring("jdbc:postgresql:".length(), query < 0 ? url.length() : query); + Map<String, String> properties = new LinkedHashMap<>(); + if (server.startsWith("//") && !server.equals("//") && !server.equals("///")) { + int slash = server.indexOf('/', 2); + if (slash < 0 || server.indexOf('/', slash + 1) >= 0) { + throw new IllegalArgumentException("Invalid PostgreSQL authority"); + } + List<String> hosts = new ArrayList<>(); + List<String> ports = new ArrayList<>(); + for (String address : server.substring(2, slash).split(",", -1)) { + int colon = address.lastIndexOf(':'); + if (colon >= 0 && address.lastIndexOf(']') < colon) { + hosts.add(colon == 0 ? "localhost" : address.substring(0, colon)); + ports.add(address.substring(colon + 1)); + } else { + hosts.add(address); + ports.add("5432"); + } + } + properties.put("PGHOST", String.join(",", hosts)); + properties.put("PGPORT", String.join(",", ports)); + } else if (server.startsWith("/") && !server.equals("//") && !server.equals("///")) { + throw new IllegalArgumentException("Invalid PostgreSQL destination"); + } + if (query >= 0) { + for (String token : url.substring(query + 1).split("&")) { + int equals = token.indexOf('='); + String key = equals < 0 ? token : token.substring(0, equals); + // pgJDBC decodes values only, translates aliases only for key=value, and uses the last key. + if (equals >= 0) { + if (key.equalsIgnoreCase("host")) { + key = "PGHOST"; + } else if (key.equalsIgnoreCase("port")) { + key = "PGPORT"; + } + } + String decoded = equals < 0 ? "" : URLDecoder.decode(token.substring(equals + 1), + StandardCharsets.UTF_8); + if (equals >= 0 && key.equals("service")) { + throw new IllegalArgumentException("PostgreSQL service discovery requires literal destinations"); + } + if (key.equals("PGHOST") || key.equals("PGPORT")) { + properties.put(key, decoded); + } + } + } + String[] hosts = properties.getOrDefault("PGHOST", "localhost").split(",", -1); + String[] ports = properties.getOrDefault("PGPORT", "5432").split(",", -1); + if (hosts.length != ports.length) { + throw new IllegalArgumentException("PostgreSQL host/port count mismatch"); + } + List<HostAndPort> result = new ArrayList<>(); + for (int i = 0; i < hosts.length; i++) { + result.add(endpoint(hosts[i], Integer.parseInt(ports[i]))); + } + return result; + } + + static List<HostAndPort> sqlServer(String url) { + String body = url.substring("jdbc:sqlserver://".length()); + int delimiter = body.indexOf(';'); + String authority = delimiter < 0 ? body : body.substring(0, delimiter); + Map<String, String> properties = sqlServerProperties(delimiter < 0 ? "" : body.substring(delimiter)); + int instance = authority.indexOf('\\'); + boolean namedInstance = instance >= 0 || !properties.getOrDefault("instancename", "").isEmpty(); + if (instance >= 0) { + int port = authority.indexOf(':', instance); + authority = authority.substring(0, instance) + (port < 0 ? "" : authority.substring(port)); + } + HostAndPort address = HostAndPort.fromString(authority); + String host = properties.getOrDefault("servername", address.getHost()); + boolean explicitPort = properties.containsKey("portnumber") || address.hasPort(); + int port = properties.containsKey("portnumber") ? Integer.parseInt(properties.get("portnumber")) + : address.getPortOrDefault(1433); + // Named-instance and failover discovery can select a port not determined by this URL's authority. + if ((namedInstance && !explicitPort) || !properties.getOrDefault("failoverpartner", "").isEmpty()) { + throw new IllegalArgumentException("JDBC discovery requires an explicit literal destination"); + } + List<HostAndPort> result = new ArrayList<>(); + result.add(endpoint(host, port)); + String attestation = properties.get("enclaveattestationurl"); + if (attestation != null && !attestation.isEmpty()) { + result.addAll(CatalogEndpointSecurity.parseEndpoints(attestation, -1)); + } + return result; + } + + private static Map<String, String> sqlServerProperties(String value) { + Map<String, String> properties = new LinkedHashMap<>(); + int position = 0; + while (position < value.length()) { + if (value.charAt(position) == ';') { + position++; + continue; + } + int start = position; + while (position < value.length() && value.charAt(position) != '=' && value.charAt(position) != ';') { + position++; + } + if (position == value.length() || value.charAt(position) != '=') { + throw new IllegalArgumentException("Invalid JDBC property"); + } + String key = value.substring(start, position++).trim().toLowerCase(Locale.ROOT); + StringBuilder decoded = new StringBuilder(); + // The driver permits whitespace before a braced value; its semicolons remain credential bytes. + while (position < value.length() && Character.isWhitespace(value.charAt(position))) { + position++; + } + if (position < value.length() && value.charAt(position) == '{') { + position++; + boolean closed = false; + while (position < value.length()) { + char character = value.charAt(position++); + if (character == '}') { + if (position < value.length() && value.charAt(position) == '}') { + position++; + } else { + closed = true; + break; + } + } + decoded.append(character); + } + if (!closed) { + throw new IllegalArgumentException("Unclosed JDBC property"); + } + while (position < value.length() && Character.isWhitespace(value.charAt(position))) { + position++; + } + if (position < value.length() && value.charAt(position) != ';') { + throw new IllegalArgumentException("Trailing JDBC property text"); + } + } else { + start = position; + while (position < value.length() && value.charAt(position) != ';') { + position++; + } + decoded.append(value, start, position); + } + // The driver normalizes these aliases and lets the last URL occurrence override its authority. + if (key.equals("server")) { + key = "servername"; + } else if (key.equals("port")) { + key = "portnumber"; + } + properties.put(key, decoded.toString().trim()); + } + return properties; + } + + static List<HostAndPort> oracle(String url) { + int separator = url.indexOf('@', "jdbc:oracle:thin:".length()); + if (separator < 0) { + throw new IllegalArgumentException("Missing Oracle destination"); + } + String target = url.substring(separator + 1).trim(); + if (target.startsWith("(")) { + return new OracleDescriptor(target).endpoints(); + } + int query = target.indexOf('?'); + if (query >= 0) { + for (String option : target.substring(query + 1).split("&")) { + String key = URLDecoder.decode(option.split("=", 2)[0], StandardCharsets.UTF_8); + if (key.equalsIgnoreCase("https_proxy") || key.equalsIgnoreCase("https_proxy_port")) { Review Comment: [P2] Check Oracle's full proxy connection-property names With an Oracle 21c driver and enforcement enabled, `jdbc:oracle:thin:@//allowed.example.com:1521/service?oracle.net.socksProxyHost=127.0.0.1&oracle.net.socksProxyPort=9000` passes this filter, after which the query is discarded and only the database host is probed. [Oracle's Easy Connect contract](https://docs.oracle.com/en/database/oracle/oracle-database/21/jajdb/oracle/jdbc/OracleDriver.html) accepts full connection-property names, and its [SOCKS property contract](https://docs.oracle.com/en/database/oracle/oracle-database/21/jajdb/oracle/jdbc/OracleConnection.html#CONNECTION_PROPERTY_SOCKS_PROXY_HOST) selects that separate proxy peer. Thus CREATE with `test_connection=false` and ALTER admit a configured destination that the policy never checks. Supplied `jdbc.oracle.net.*` properties in Iceberg/Paimon are also omitted by `JdbcProxyPropertySecurity`. Include these full proxy names in URL/property admission, or reject active unmodeled routing, with enabled-policy CREATE/ALTER tes ts. This concerns admission independently of later sanitization/runtime hooks. -- 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]
