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


##########
fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergConnectorProvider.java:
##########
@@ -95,11 +101,184 @@ public ConnectorSecuritySurface securitySurface() {
         // Keep secret masking and JDBC restrictions when REST decryption adds 
a KMS endpoint check.
         return 
ConnectorSecuritySurface.ofJdbcDriverUrls("iceberg.catalog.type", 
"iceberg.jdbc.driver_url")
                 .withSensitiveKeys(MetaStoreProviders.sensitivePropertyKeys())
+                
.withSensitiveKeys(JdbcTlsStoreUrlSecurity.sensitivePropertyKeys("jdbc."))
                 // Protect inline SDK credentials even when the additional 
name-pattern rule is disabled.
                 .withSensitiveKeys(List.of("gcp.auth.credentials-json", 
"gcs.oauth2.token",
                         "gcs.encryption-key", "gcs.decryption-key"))
-                // Standalone DLF proxies open HMS clients too; Hive's surface 
only covers HMS catalogs.
-                .withSsrfEndpoints("kms.endpoint", "hive.metastore.uris", 
"uri", "metastore.thrift.uris")
+                .withSensitiveKeyPrefix("client.credentials-provider.",
+                        "credential", "password", "secret", "token", "key", 
"authorization", "header")
+                .withSsrfEndpoints("kms.endpoint", "iceberg.rest.uri", "uri",
+                        "hive.metastore.uris", "metastore.thrift.uris", 
"s3tables.endpoint", "iceberg.jdbc.uri",
+                        "dynamodb.endpoint",
+                        "http-client.proxy-endpoint", "signer.uri")
+                // Native GCS overrides its storage service host independently 
of the catalog's REST URI.
+                .withSsrfEndpoints("gcs.service.host")
+                .withSsrfEndpoints("glue.endpoint", "aws.endpoint", 
"aws.glue.endpoint")
+                // DLF accepts bare hosts and uses HTTPS, including on its 
standalone HMS proxy path.
                 .withSsrfEndpoints(443, "dlf.endpoint", 
"dlf.catalog.endpoint");
     }
+
+    @Override
+    public ConnectorSecuritySurface securitySurface(Map<String, String> 
properties) {
+        // Retired aliases and inactive proxy clients must not contribute 
unused metadata destinations.
+        ConnectorSecuritySurface surface = securitySurface()
+                
.withSsrfEndpointValues("dlf.endpoint").withSsrfEndpointValues("dlf.catalog.endpoint");
+        String flavor = 
properties.getOrDefault(IcebergCatalogProperties.ICEBERG_CATALOG_TYPE,
+                IcebergCatalogProperties.TYPE_HMS).trim();
+        Map<String, String> endpointProperties = new HashMap<>(properties);
+        for (String key : new String[] {"signer.endpoint", 
"rest.remote-signing.endpoint",
+                "client.refresh-credentials-endpoint", 
"iceberg.rest.oauth2.server-uri", "oauth2-server-uri",
+                "client.credentials-provider.oauth2-server-uri", 
"gcs.oauth2.refresh-credentials-endpoint"}) {
+            String value = properties.get(key);
+            if (value != null && key.equals("iceberg.rest.oauth2.server-uri")) 
{
+                // The canonical holder trims Strings before emitting the SDK 
OAuth option; raw aliases do not.
+                value = value.trim();
+            }
+            // Iceberg appends signer, credential-refresh and OAuth paths 
(including GCS refresh) to a checked base.
+            // Only these lowercase absolute forms replace that base with an 
independent destination.
+            if (value != null && (value.startsWith("http://";) || 
value.startsWith("https://";))) {
+                surface = surface.withSsrfEndpoints(key);
+            } else {
+                endpointProperties.remove(key);
+            }
+        }
+        if (properties.containsKey("rest.client.proxy.port")) {
+            // The REST client activates this separate host only when a port 
is supplied, including on ALTER.
+            surface = surface.withSsrfEndpoints("rest.client.proxy.hostname");
+            int port = 
explicitProxyPort(properties.get("rest.client.proxy.port"));
+            if (port > 0) {
+                surface = surface.withSsrfEndpoints(port, 
"rest.client.proxy.hostname");
+            }
+        }
+        surface = withProviderProxyEndpoints(surface, properties);
+        // Google credentials are opaque secrets, but their structured token 
endpoints select independent peers.
+        for (String key : new String[] {"gcp.auth.credentials-json",
+                "client.credentials-provider.gcp.auth.credentials-json"}) {
+            if (properties.containsKey(key)) {
+                surface = surface.withSsrfEndpointValues(key,
+                        
IcebergGoogleCredentialValidator.ssrfTokenEndpoints(properties.get(key))
+                                .toArray(new String[0]));
+            }
+        }
+        // JdbcCatalog forwards these as driver Properties, independently of 
options inside the JDBC URL.
+        // Keep Connector/J's exact option names unless a URI alias or 
selected driver also admits MariaDB.
+        String jdbcUriKey = 
JdbcProxyPropertySecurity.metastoreUriKey(properties, "iceberg.jdbc.uri");
+        String jdbcUri = properties.get(jdbcUriKey);
+        // Retired URI aliases cannot choose either a database peer or another 
driver's TLS-store grammar.
+        boolean mariaDb = JdbcTlsStoreUrlSecurity.mayUseMariaDb(jdbcUri, 
properties.get("iceberg.jdbc.driver_class"));
+        boolean connectorJ = JdbcTlsStoreUrlSecurity.mayUseConnectorJ(jdbcUri);
+        List<String> suppliedPorts = new ArrayList<>();
+        Map<String, String> suppliedProperties = new HashMap<>();
+        for (Map.Entry<String, String> entry : properties.entrySet()) {
+            String key = entry.getKey();
+            if (key.startsWith("jdbc.")) {
+                String option = key.substring(5);
+                suppliedProperties.put(option, entry.getValue());
+                if (option.equalsIgnoreCase("port")) {
+                    suppliedPorts.add(entry.getValue());
+                }
+                if (JdbcTlsStoreUrlSecurity.isStoreUrlProperty(option)
+                        || (mariaDb && 
JdbcTlsStoreUrlSecurity.isMariaDbStoreUrlProperty(option))) {
+                    surface = surface.withSsrfEndpointValues(key,
+                            
JdbcTlsStoreUrlSecurity.storePropertyEndpointValues(
+                                    option, entry.getValue(), connectorJ, 
mariaDb)
+                                    .toArray(new String[0]));
+                }
+                // Supplied properties can select proxy/discovery routes 
absent from the JDBC URL.
+                List<String> proxy = 
JdbcProxyPropertySecurity.driverPropertyEndpointValues(option, 
entry.getValue());
+                if (!proxy.isEmpty()) {
+                    surface = surface.withSsrfEndpointValues(key, 
proxy.toArray(new String[0]));
+                }
+            }
+        }
+        List<String> jdbcEndpoints = new ArrayList<>();
+        for (String endpoint : 
JdbcProxyPropertySecurity.mysqlPortEndpointValues(jdbcUri, suppliedPorts)) {
+            
jdbcEndpoints.add(JdbcProxyPropertySecurity.postgresqlPropertyEndpointValue(endpoint,
 suppliedProperties));
+        }
+        surface = surface.withSsrfEndpointValues(jdbcUriKey, 
jdbcEndpoints.toArray(new String[0]))
+                .withSsrfEndpointValues(jdbcUriKey.equals("uri") ? 
"iceberg.jdbc.uri" : "uri");
+        if (IcebergCatalogProperties.TYPE_DLF.equalsIgnoreCase(flavor)) {
+            // Region-only DLF catalogs still contact a metastore, 
independently of their OSS storage peer.
+            for (Map.Entry<String, String> entry
+                    : 
AbstractDlfMetaStoreProperties.serviceEndpointValues(properties).entrySet()) {
+                surface = surface.withSsrfEndpoints(443, entry.getKey())
+                        .withSsrfEndpointValues(entry.getKey(), 
entry.getValue());
+            }
+            for (Map.Entry<String, List<String>> entry
+                    : 
OssEndpointProperties.s3CompatibleEndpointValues(properties).entrySet()) {
+                List<String> values = new ArrayList<>();
+                if 
(surface.ssrfEndpointKeys(properties).contains(entry.getKey())) {
+                    values.addAll(surface.ssrfEndpointValues(entry.getKey(), 
properties.get(entry.getKey())));
+                }
+                // DLF's S3FileIO and CREATE HEAD use a separate S3-compatible 
socket host.
+                values.addAll(entry.getValue());
+                surface = surface.withSsrfEndpointValues(entry.getKey(), 
values.toArray(new String[0]));
+            }
+        }
+        String restUri = properties.get("iceberg.rest.uri");
+        if (IcebergCatalogProperties.TYPE_REST.equalsIgnoreCase(flavor)
+                && restUri != null && !restUri.isBlank()) {
+            // REST binds its dedicated URI before the generic fallback; 
storage retains its independent raw URI.
+            surface = surface.withSsrfEndpointValues("uri");
+        }
+        String metastore = properties.get("hive.metastore.uris");
+        boolean dlf = "dlf".equalsIgnoreCase(flavor);
+        if ("hadoop".equalsIgnoreCase(flavor) || (dlf && 
!AbstractDlfMetaStoreProperties.usesHmsClient(properties))
+                || (("hms".equalsIgnoreCase(flavor) || dlf)
+                && metastore != null && !metastore.isBlank())) {
+            // Hadoop and DLF-only have no HMS URI; an active HMS client 
prefers its dedicated alias.
+            surface = surface.withSsrfEndpointValues("uri");

Review Comment:
   Fixed in 70b28a4171e67318ea11019487a6bae6f655217f.
   
   Retired the generic metadata URI before adding DLF FileIO destinations, 
preserving the independent native OSS and S3-compatible peers attributed to 
that URI. Coverage checks both peers in DLF_ONLY and DLF_METASTORE_FAILURE, 
CREATE ordering, refused ALTER retention, and exact SQL peer/port controls.
   
   The current head passed 2846 FE tests, strict FE Checkstyle, a fresh FE 
build, and both local SQL suites. Scope and verification limits are recorded in 
the PR description.



##########
fe/fe-foundation/src/main/java/org/apache/doris/foundation/security/JdbcProxyPropertySecurity.java:
##########
@@ -0,0 +1,146 @@
+// 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.URLDecoder;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/** Projects independent JDBC property routes without initializing the 
operator-selected driver. */
+public final class JdbcProxyPropertySecurity {
+    private static final List<String> UNMODELED_JDBC_ROUTE = 
List.of("http://unmodeled-jdbc-route:0";);
+
+    private JdbcProxyPropertySecurity() {
+    }
+
+    /** The metastore holders bind the first nonblank URI alias, independently 
of driver options. */
+    public static String metastoreUriKey(Map<String, String> properties, 
String connectorAlias) {
+        String uri = properties.get("uri");
+        return uri != null && !uri.isBlank() ? "uri" : connectorAlias;

Review Comment:
   Fixed in 70b28a4171e67318ea11019487a6bae6f655217f.
   
   URI alias selection now reuses ConnectorPropertiesUtils String conversion, 
matching trim-empty control characters. Both actual metastore holder tests and 
admission/CREATE/ALTER tests cover ASCII controls 0 and 31; ordinary trim-empty 
fallback is also exercised through SQL.
   
   The current head passed 2846 FE tests, strict FE Checkstyle, a fresh FE 
build, and both local SQL suites. Scope and verification limits are recorded in 
the PR description.



##########
fe/fe-filesystem/fe-filesystem-api/src/main/java/org/apache/doris/filesystem/properties/StorageEndpointProperties.java:
##########
@@ -0,0 +1,275 @@
+// 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.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Predicate;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/** 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 static final List<String> S3_REGION_ALIASES = List.of("s3.region", 
"AWS_REGION", "region", "REGION",
+            "aws.region", "glue.region", "aws.glue.region", 
"iceberg.rest.signing-region", "rest.signing-region",
+            "client.region");
+    private static final List<String> S3_ENDPOINT_ALIASES = 
List.of("s3.endpoint", "AWS_ENDPOINT", "endpoint",
+            "ENDPOINT", "aws.endpoint", "glue.endpoint", "aws.glue.endpoint");
+    private static final Pattern[] S3_ENDPOINT_PATTERNS = new Pattern[] {
+            Pattern.compile(
+                    "^(?:https?://)?(?:"
+                            + 
"s3(?:[-.]fips)?(?:[-.]dualstack)?[-.]([a-z0-9-]+)|"
+                            + "s3express-control\\.([a-z0-9-]+)|"
+                            + "s3express-[a-z0-9-]+\\.([a-z0-9-]+)"
+                            + ")\\.amazonaws\\.com(?:/.*)?$",
+                    Pattern.CASE_INSENSITIVE),
+            Pattern.compile(
+                    
"^(?:https?://)?glue(?:-fips)?\\.([a-z0-9-]+)\\.(amazonaws\\.com(?:\\.cn)?|api\\.aws)$",
+                    Pattern.CASE_INSENSITIVE)
+    };
+
+    private StorageEndpointProperties() {
+    }
+
+    public static Map<String, List<String>> derivedEndpointValues(Map<String, 
String> properties) {
+        Map<String, List<String>> result = new 
LinkedHashMap<>(derivedS3EndpointValues(properties));
+        OssEndpointProperties.derivedEndpointValues(properties).forEach((key, 
values) ->
+                result.merge(key, values, (existing, added) -> {
+                    List<String> combined = new ArrayList<>(existing);
+                    combined.addAll(added);
+                    return combined;
+                }));
+        return result;
+    }
+
+    public static boolean hasExplicitFilesystem(Map<String, String> 
properties) {
+        return "true".equalsIgnoreCase(properties.get("oss.hdfs.enabled"))
+                || properties.entrySet().stream().anyMatch(entry -> 
entry.getKey() != null
+                        && entry.getKey().startsWith("fs.") && 
entry.getKey().endsWith(".support")
+                        && "true".equalsIgnoreCase(entry.getValue()));
+    }
+
+    private static Map<String, List<String>> 
derivedS3EndpointValues(Map<String, String> properties) {
+        // S3 yields to inferred GCS too; an unused shared region must not 
invent an AWS destination.
+        if ((hasExplicitFilesystem(properties) && 
!Boolean.parseBoolean(properties.get("fs.s3.support")))
+                || (!GcsEndpointProperties.hasExplicitS3Request(properties)
+                && GcsEndpointProperties.guessIsGcs(properties))) {
+            return Map.of();
+        }
+        String regionKey = firstNonblankKey(properties, S3_REGION_ALIASES);
+        String endpointKey = firstNonblankKey(properties, S3_ENDPOINT_ALIASES);
+        String sourceKey = endpointKey;
+        String endpoint = endpointKey == null ? null : 
properties.get(endpointKey).trim();
+        if (regionKey == null && endpointKey == null) {
+            // The binder's legacy URI fallback runs on its HashMap snapshot, 
including URI key aliases.
+            Map<String, String> raw = new HashMap<>(properties);
+            sourceKey = raw.keySet().stream().filter(key -> 
key.equalsIgnoreCase("uri")).findFirst().orElse(null);
+            if (sourceKey == null) {
+                return Map.of();
+            }
+            String pathKey = firstNonblankKey(properties, 
List.of("use_path_style", "s3.path-style-access"));
+            String forceKey = firstNonblankKey(properties, 
List.of("force_parsing_by_standard_uri"));
+            endpoint = LegacyS3Uri.deriveEndpointQuietly(raw,
+                    pathKey == null ? "false" : properties.get(pathKey).trim(),
+                    forceKey == null ? "false" : 
properties.get(forceKey).trim());
+        }
+        if (endpointKey == null && regionKey == null && endpoint != null
+                && !endpoint.toLowerCase(Locale.ROOT).contains("glue")) {
+            // Ordinary legacy resource URIs also bind an endpoint; 
S3ObjStorage supplies HTTPS to bare authorities.
+            return s3RegionFromEndpoint(endpoint).isPresent()
+                    ? Map.of(sourceKey, List.of("https://"; + endpoint)) : 
Map.of();
+        }
+        if (endpoint != null && 
!endpoint.toLowerCase(Locale.ROOT).contains("glue")) {
+            return Map.of();
+        }
+        // Glue normalization infers a missing region before rewriting the S3 
endpoint. Reuse the
+        // storage binder's inference and retain the original peer for callers 
that also contact Glue.
+        String region = regionKey == null
+                ? (endpoint == null ? "" : 
s3RegionFromEndpoint(endpoint).orElse(""))
+                : properties.get(regionKey).trim();
+        if (region.isEmpty()) {
+            return Map.of();
+        }
+        if (!region.matches("[A-Za-z0-9-]+")) {
+            throw new IllegalArgumentException("S3 region must be a literal 
hostname component");
+        }
+        String serviceEndpoint = s3EndpointForRegion(region);
+        if (regionKey != null) {
+            return Map.of(regionKey, List.of(serviceEndpoint));
+        }
+        String source = properties.get(sourceKey);
+        String normalized = source.trim().toLowerCase(Locale.ROOT);
+        // An S3 URI is a resource locator; its rewritten endpoint is the 
socket peer. An HTTP URI
+        // can also name the catalog service, so retain that independently 
checked original peer.
+        boolean originalPeer = endpointKey != null || 
normalized.startsWith("http://";)
+                || normalized.startsWith("https://";);
+        return Map.of(sourceKey, originalPeer ? List.of(source, 
serviceEndpoint) : List.of(serviceEndpoint));
+    }
+
+    public static String s3EndpointForRegion(String region) {
+        return "https://s3."; + region + ".amazonaws.com";
+    }
+
+    public static Optional<String> s3RegionFromEndpoint(String endpoint) {
+        String lowerEndpoint = endpoint.toLowerCase(Locale.ROOT);
+        for (Pattern pattern : S3_ENDPOINT_PATTERNS) {
+            Matcher matcher = pattern.matcher(lowerEndpoint);
+            if (matcher.matches()) {
+                for (int i = 1; i <= matcher.groupCount(); i++) {
+                    String group = matcher.group(i);
+                    if (group != null && !group.isBlank()) {
+                        return Optional.of(group);
+                    }
+                }
+            }
+        }
+        return Optional.empty();
+    }
+
+    private static String firstNonblankKey(Map<String, String> properties, 
List<String> aliases) {
+        for (String key : aliases) {
+            String value = properties.get(key);
+            if (value != null && !value.isBlank()) {
+                return key;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * 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",
+                "glue.endpoint", "aws.glue.endpoint", "oss.endpoint", 
"oss.hdfs.endpoint", "OSS_ENDPOINT",
+                "fs.oss.endpoint", "cos.endpoint", "COS_ENDPOINT",
+                "obs.endpoint", "OBS_ENDPOINT", "azure.endpoint", 
"AZURE_ENDPOINT", "azure.oauth2_server_uri",
+                "azure.oauth2_account_host", "gs.endpoint", "minio.endpoint", 
"ozone.endpoint", "fs.s3a.endpoint",

Review Comment:
   Fixed in 70b28a4171e67318ea11019487a6bae6f655217f.
   
   Bare gs.endpoint values now retain HTTPS port 443, matching native GCS 
Hadoop and the HMAC adapter. Recording admission covers acceptance and exact 
port-443 denial; the SQL suite covers both a supported bare endpoint and an 
exact peer/port refusal.
   
   The current head passed 2846 FE tests, strict FE Checkstyle, a fresh FE 
build, and both local SQL suites. Scope and verification limits are recorded in 
the PR description.



##########
fe/fe-core/src/main/java/org/apache/doris/connector/CatalogEndpointSecurity.java:
##########
@@ -0,0 +1,421 @@
+// 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 okhttp3.HttpUrl;
+
+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;
+import java.util.Set;
+
+/** 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() {
+        // The admission decision consumes the point; callers may ask about 
availability more than once.
+        return SecurityChecker.getInstance().isEnabled() || 
DebugPointUtil.isEnableWithoutCounting(REJECT_HOST_POINT);
+    }
+
+    public static void validate(String catalogName, ConnectorSecuritySurface 
surface, Map<String, String> properties)
+            throws DdlException {
+        validateAndRemember(catalogName, surface, properties, null);
+    }
+
+    /** A receipt is valid only within one CREATE statement and for the same 
checker instance. */
+    static final class Admission {
+        private final SecurityChecker checker;
+        private final boolean enabled;
+        private final Set<HostAndPort> destinations;
+
+        private Admission(SecurityChecker checker, Set<HostAndPort> 
destinations) {
+            this.checker = checker;
+            this.enabled = checker.isEnabled();
+            this.destinations = Set.copyOf(destinations);
+        }
+    }
+
+    static Admission validateAndRemember(String catalogName, 
ConnectorSecuritySurface surface,
+            Map<String, String> properties, Admission previous) throws 
DdlException {
+        SecurityChecker checker = SecurityChecker.getInstance();
+        DebugPoint rejection = DebugPointUtil.getDebugPoint(REJECT_HOST_POINT);
+        if (!checker.isEnabled() && rejection == null) {
+            return null;
+        }
+        Map<String, Integer> storageEndpoints;
+        Map<String, List<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, List<HostAndPort>> parsedEndpoints = new LinkedHashMap<>();
+        Map<String, Integer> storageKeys = new 
LinkedHashMap<>(storageEndpoints);
+        derivedStorageEndpoints.keySet().forEach(key -> 
storageKeys.putIfAbsent(key, -1));
+        for (Map.Entry<String, Integer> entry : storageKeys.entrySet()) {
+            String key = entry.getKey();
+            int port = entry.getValue() < 0 ? 
surface.ssrfEndpointDefaultPort(key) : entry.getValue();
+            List<String> values = derivedStorageEndpoints.getOrDefault(key,
+                    properties.get(key) == null ? List.of() : 
List.of(properties.get(key)));
+            appendEndpoints(catalogName, key, values, port, entry.getValue() 
== 8020, properties, parsedEndpoints);
+        }
+        Map<String, Integer> serviceKeys = new LinkedHashMap<>();
+        for (String key : surface.ssrfEndpointKeys(properties)) {
+            serviceKeys.put(key, surface.ssrfEndpointDefaultPort(key));
+        }
+        // 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://";)) {
+                    serviceKeys.put(key, -1);
+                }
+            }
+        }
+        // One property can feed metadata and storage clients with different 
normalization and ports.
+        // Keep both interpretations; a provider's inactive metadata alias 
cannot erase a storage route.
+        for (Map.Entry<String, Integer> entry : serviceKeys.entrySet()) {
+            String key = entry.getKey();
+            appendEndpoints(catalogName, key, surface.ssrfEndpointValues(key, 
properties.get(key)),
+                    entry.getValue(), false, properties, parsedEndpoints);
+        }
+        Set<HostAndPort> admitted = new LinkedHashSet<>();
+        if (previous != null && previous.checker == checker && 
previous.enabled == checker.isEnabled()) {
+            admitted.addAll(previous.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 cannot bypass real policy or allow a 
connection, including receipt reuse.
+                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");
+                }
+                if (admitted.add(destination)) {
+                    checker.checkEndpointForSsrf(destination.getHost(), 
destination.getPort());
+                }
+            }
+        }
+        return new Admission(checker, admitted);
+    }
+
+    private static void appendEndpoints(String catalogName, String key, 
List<String> values, int defaultPort,
+            boolean hdfs, Map<String, String> properties, Map<String, 
List<HostAndPort>> parsed) throws DdlException {
+        try {
+            List<HostAndPort> destinations = parsed.computeIfAbsent(key, 
ignored -> new ArrayList<>());
+            for (String endpoint : values) {
+                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 (hdfs) {
+                    for (String authority : 
HdfsEndpointProperties.authorities(endpoint.trim(), properties)) {
+                        destinations.add(parseAuthority(authority, 8020));
+                    }
+                } else {
+                    destinations.addAll(parseEndpoints(endpoint.trim(), 
defaultPort));
+                }
+            }
+        } 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");
+        }
+    }
+
+    /** 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<>();
+        // An SRV seed is a discovery name, not a server at MongoDB's ordinary 
default port.
+        // Until discovery peers are modeled, require literal mongodb:// 
authorities under enforcement.
+        if (normalized.startsWith("mongodb+srv://")) {
+            throw new IllegalArgumentException("Unsupported MongoDB SRV 
discovery routing");
+        }
+        if (normalized.startsWith("mongodb://")) {
+            int authorityEnd = normalized.indexOf('/', "mongodb://".length());
+            authorityEnd = authorityEnd < 0 ? normalized.length() : 
authorityEnd;
+            int query = normalized.indexOf('?');
+            if (query >= 0) {
+                authorityEnd = Math.min(authorityEnd, query);
+            }
+            // MongoDB treats '#' in userinfo as ordinary bytes; Java URI ends 
its authority there.
+            // Reject that disagreement before either the database or proxy 
endpoint is probed.
+            int fragment = normalized.indexOf('#');
+            if (fragment >= 0 && fragment < authorityEnd) {
+                throw new IllegalArgumentException("Ambiguous MongoDB URI 
authority");
+            }
+            parseSingle(normalized, defaultPort, result);
+            addMongoProxy(normalized, result);
+            return result;
+        }
+        // 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)) {

Review Comment:
   Fixed in 70b28a4171e67318ea11019487a6bae6f655217f.
   
   Removed global URI-list splitting. Actual HMS, Fluss bootstrap/nested HMS 
and Trino HMS list fields use the existing explicit list declaration. Single 
REST path/query commas now produce one actual destination. Tests cover both 
catalogs, real node lists, and an actual-peer replacement refusal followed by a 
successful update under the same policy.
   
   The current head passed 2846 FE tests, strict FE Checkstyle, a fresh FE 
build, and both local SQL suites. Scope and verification limits are recorded in 
the PR description.



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