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


##########
fe/fe-connector/fe-connector-paimon/src/main/java/org/apache/doris/connector/paimon/PaimonConnectorProvider.java:
##########
@@ -106,7 +111,61 @@ public ConnectorSecuritySurface securitySurface() {
         // The secrets are those of every metastore flavor: the engine masks 
by key name alone.
         return ConnectorSecuritySurface.ofJdbcDriverUrls(
                 "paimon.catalog.type", "paimon.jdbc.driver_url", 
"jdbc.driver_url")
-                .withSensitiveKeys(MetaStoreProviders.sensitivePropertyKeys());
+                .withSensitiveKeys(MetaStoreProviders.sensitivePropertyKeys())
+                
.withSensitiveKeys(JdbcTlsStoreUrlSecurity.sensitivePropertyKeys("jdbc."))
+                
.withSensitiveKeys(JdbcTlsStoreUrlSecurity.sensitivePropertyKeys("paimon.jdbc."))
+                // The pass-through bearer token is opaque even when its bytes 
look like an HTTP URL.
+                .withSensitiveKeys("paimon.rest.token")
+                // REST token providers also perform HTTP calls; checking only 
the catalog URI misses them.
+                .withSsrfEndpoints("paimon.rest.uri", "uri", 
"paimon.rest.dlf.token-ecs-metadata-url",
+                        "hive.metastore.uris", "metastore.thrift.uris", 
"paimon.jdbc.uri")
+                .withSsrfEndpoints("paimon.rest.dlf.oss-endpoint", 
"dlf.endpoint", "dlf.catalog.endpoint")
+                .withSsrfEndpointPrefixes("paimon.rest.");
     }
 
+    @Override
+    public ConnectorSecuritySurface securitySurface(Map<String, String> 
properties) {
+        ConnectorSecuritySurface surface = securitySurface();
+        // A complete ALTER can switch either URI alias or driver and activate 
stored native options.
+        boolean mariaDb = 
JdbcTlsStoreUrlSecurity.mayUseMariaDb(properties.get("uri"),
+                properties.get("paimon.jdbc.driver_class"))
+                || 
JdbcTlsStoreUrlSecurity.mayUseMariaDb(properties.get("paimon.jdbc.uri"),
+                        properties.get("jdbc.driver_class"));
+        boolean connectorJ = JdbcTlsStoreUrlSecurity.mayUseConnectorJ(
+                properties.get("uri"), properties.get("paimon.jdbc.uri"));
+        List<String> suppliedPorts = new ArrayList<>();
+        for (Map.Entry<String, String> entry : properties.entrySet()) {
+            String key = entry.getKey();
+            // Common options strip only the outer paimon prefix 
case-insensitively; the JDBC suffix is exact.
+            String option = key.toLowerCase(Locale.ROOT).startsWith("paimon.") 
? key.substring(7) : key;
+            if (option.startsWith("jdbc.") && 
option.substring(5).equalsIgnoreCase("port")) {
+                suppliedPorts.add(entry.getValue());

Review Comment:
   Fixed in 02750a18de1. Admission and actual Paimon option assembly now share 
the effective common/raw JDBC overlay. A common paimon.jdbc.* option wins over 
its exact raw jdbc.* key before port ambiguity, TLS-store and proxy checks; 
genuine driver case aliases remain distinct. The original raw/prefixed CREATE 
and ALTER example is covered, including an ignored invalid raw fallback and 
rejected common-value replacement.
   
   The same production code passed 2348 selected tests and FE 
Checkstyle/packaging. Fresh SQL verifies the accepted common port survives a 
rejected update under one exact host/port policy, and covers ignored raw 
proxy/TLS options with masking and effective-option refusal controls. The full 
suite passed 204 CREATE and 148 ALTER refusals, 18 positive CREATE admissions 
and 25 successful ALTERs.



##########
fe/fe-core/src/main/java/org/apache/doris/connector/CatalogEndpointSecurity.java:
##########
@@ -0,0 +1,320 @@
+// 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;
+        Map<String, String> derivedStorageEndpoints;
+        try {
+            storageEndpoints = StorageEndpointProperties.endpoints(properties, 
DatasourcePrintableMap::isSensitiveKey);
+            derivedStorageEndpoints = 
StorageEndpointProperties.derivedEndpointValues(properties);
+        } 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);
+        derivedStorageEndpoints.keySet().forEach(key -> 
endpoints.putIfAbsent(key, -1));
+        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<>();
+                List<String> values = derivedStorageEndpoints.containsKey(key)
+                        ? List.of(derivedStorageEndpoints.get(key)) : 
surface.ssrfEndpointValues(key, value);
+                for (String endpoint : values) {
+                    // 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);
+        }
+        int rejectedPort = rejection == null ? -1 : rejection.param("port", 
-1);
+        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.
+                // Optional port matching distinguishes peers on one host; 
every real checker call remains below.
+                if (rejection != null && 
destination.getHost().equals(rejection.param("host", "127.0.0.1"))
+                        && (rejectedPort < 0 || destination.getPort() == 
rejectedPort)) {
+                    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:mariadb:")) {
+            return JdbcEndpointParser.mariaDb(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:")) {
+            normalized = normalized.substring(5);
+        }
+        for (String endpoint : 
normalized.split(",(?=\\s*[A-Za-z][A-Za-z0-9+.-]*://)", -1)) {
+            parseSingle(endpoint.trim(), defaultPort, result);
+        }
+        return result;
+    }
+
+    private static void validateNativePostgresql(String value) {
+        int start = value.indexOf("://") + 3;
+        int slash = value.indexOf('/', start);
+        int query = value.indexOf('?', start);
+        int at = value.indexOf('@', start);
+        int authorityEnd = slash < 0 ? value.length() : slash;
+        if (query >= 0) {
+            authorityEnd = Math.min(authorityEnd, query);
+        }
+        int secondAt = at < 0 ? -1 : value.indexOf('@', at + 1);
+        // libpq has no fragment syntax and scans userinfo up to the first 
slash, even across '?'.
+        // Reject structures whose destination differs from Java URI authority 
parsing.
+        if (value.indexOf('#') >= 0 || (at >= 0 && query >= 0 && query < at && 
(slash < 0 || at < slash))
+                || (at >= 0 && at < authorityEnd && secondAt >= 0 && secondAt 
< authorityEnd)) {
+            throw new IllegalArgumentException("Ambiguous native PostgreSQL 
URI");
+        }
+        if (query >= 0) {
+            for (String token : value.substring(query + 1).split("&")) {
+                String rawKey = token.split("=", 2)[0];
+                // libpq percent-decodes keys once and preserves literal plus 
signs.
+                String key = URLDecoder.decode(rawKey.replace("+", "%2B"), 
StandardCharsets.UTF_8);
+                if (key.equals("host") || key.equals("hostaddr") || 
key.equals("port") || key.equals("service")) {
+                    throw new IllegalArgumentException("Native PostgreSQL 
routing requires literal URI authorities");
+                }
+            }
+        }
+    }
+
+    private static void parseSingle(String endpoint, int defaultPort, 
List<HostAndPort> result) {
+        if (endpoint.isEmpty()) {
+            throw new IllegalArgumentException("Empty endpoint");
+        }
+        if (endpoint.regionMatches(true, 0, "file:", 0, 5)) {
+            try {
+                URI local = new URI(endpoint);
+                String authority = local.getRawAuthority();
+                if (local.isOpaque() || (authority != null && 
!authority.isEmpty()
+                        && !"localhost".equalsIgnoreCase(authority))) {
+                    throw new IllegalArgumentException("Remote or opaque file 
URI");
+                }
+                return;
+            } catch (URISyntaxException e) {
+                throw new IllegalArgumentException("Invalid local file URI");
+            }
+        }
+        if (!endpoint.contains("://")) {
+            String authority = endpoint.split("/", 2)[0];
+            for (String host : authority.split(",", -1)) {
+                result.add(parseAuthority(host.trim(), defaultPort));
+            }
+            return;
+        }
+        URI uri;
+        try {
+            uri = new URI(endpoint);
+        } catch (URISyntaxException e) {
+            throw new IllegalArgumentException("Invalid endpoint URI");
+        }
+        String scheme = uri.getScheme().toLowerCase(Locale.ROOT);
+        String authority = uri.getRawAuthority();
+        if (authority == null || authority.isEmpty()) {
+            throw new IllegalArgumentException("Missing endpoint authority");
+        }
+        authority = authority.substring(authority.lastIndexOf('@') + 1);
+        int port = defaultPortForScheme(scheme, defaultPort);
+        for (String host : authority.split(",", -1)) {
+            result.add(parseAuthority(host, port));
+        }
+    }
+
+    static HostAndPort parseAuthority(String value, int defaultPort) {
+        HostAndPort address = HostAndPort.fromString(value);
+        String host = address.getHost();
+        if (host.isEmpty() || host.contains("%") || host.contains("\\") || 
host.contains("$") || host.contains("@")) {
+            throw new IllegalArgumentException("Invalid endpoint host");
+        }
+        if (!host.contains(":")) {
+            host = IDN.toASCII(host, IDN.USE_STD3_ASCII_RULES);
+        }
+        // libc/native clients accept octal, hex and shortened IPv4 forms that 
a JDK probe may resolve
+        // differently or not at all. Require canonical IP spelling before 
admitting a native client's URL.
+        if 
(host.matches("(?i)(0x[0-9a-f]+|[0-9]+)(\\.(0x[0-9a-f]+|[0-9]+)){0,3}")
+                && !InetAddresses.isInetAddress(host)) {
+            throw new IllegalArgumentException("Non-canonical numeric host");
+        }
+        int port = address.hasPort() ? address.getPort() : defaultPort;
+        if (port < 1 || port > 65535) {
+            throw new IllegalArgumentException("Missing or invalid endpoint 
port");
+        }
+        return HostAndPort.fromParts(host, port);
+    }
+
+    private static int defaultPortForScheme(String scheme, int fallback) {
+        switch (scheme) {
+            case "http":
+            case "grpc":
+            case "grpc+tcp":
+                return 80;
+            case "https":
+            case "grpcs":
+            case "grpc+tls":
+                return 443;
+            case "mongodb":
+            case "mongodb+srv":
+                return 27017;

Review Comment:
   Fixed in 02750a18de1 by handling SRV as an explicitly unsupported discovery 
route under endpoint enforcement. The parser no longer fabricates seed:27017 or 
probes the seed's A/AAAA address. It fails closed before any endpoint probe; 
ALTER now also applies admission before provider type validation, which can 
itself perform TXT/discovery work. This change intentionally does not claim to 
resolve or validate SRV-discovered peers. Literal mongodb:// authorities remain 
the supported alternative, and disabled-policy behavior is unchanged.
   
   Recording-only CREATE/ALTER and ordering controls cover SRV refusal, literal 
peers, query SOCKS destinations/defaults, ambiguous authority fragments and 
policy-disabled compatibility, without a live DNS/discovery experiment. The 
matching real SQL cases passed. The behavior and runtime/topology boundary are 
documented in the guide and PR description.



##########
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:
   The remaining variants retained in the latest full review body are fixed in 
02750a18de1. Admission and the S3 binder share region inference and 
service-endpoint construction, including Glue/FIPS/China/api.aws inference when 
no region is supplied. Both the original Glue/HTTP peer and the rewritten S3 
peer are retained. Legacy URI fallback uses the unchanged shared parser and 
binder-compatible path-style/forced-standard/alias precedence; its original SPI 
class and public descriptors remain available through a compatibility facade. 
Fluss derives against the actual canonical lake-storage mapping, including 
fs.s3a.endpoint.region.
   
   Fresh SQL verifies the rewritten S3 host:443 through four inferred-Glue 
ALTERs, two URI-fallback ALTERs and exact CREATE peer controls. Region 
precedence, persisted-region refusal and default credential masking remain 
covered. All 2348 selected Java tests, full SPI tests, FE Checkstyle/packaging, 
both SQL suites and shipped-copy byte checks passed; these are 
admission/persistence checks, not live S3 requests.



-- 
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