Copilot commented on code in PR #914:
URL: https://github.com/apache/fesod/pull/914#discussion_r3225610720


##########
fesod-sheet/src/main/java/org/apache/fesod/sheet/converters/url/UrlImageFetchPolicy.java:
##########
@@ -0,0 +1,155 @@
+/*
+ * 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.fesod.sheet.converters.url;
+
+import java.net.IDN;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+
+/**
+ * Security policy for fetching images from URL values.
+ */
+@Getter
+@EqualsAndHashCode
+public final class UrlImageFetchPolicy {
+
+    public static final int DEFAULT_MAX_REDIRECTS = 3;
+    public static final int DEFAULT_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
+
+    private static final UrlImageFetchPolicy DEFAULT = builder().build();
+
+    private final boolean allowPrivateNetwork;
+    private final Set<String> allowedPrivateHosts;
+    private final List<CidrBlock> allowedPrivateCidrs;
+    private final Set<String> allowedSchemes;
+    private final int maxRedirects;
+    private final int maxImageBytes;
+
+    private UrlImageFetchPolicy(Builder builder) {
+        this.allowPrivateNetwork = builder.allowPrivateNetwork;
+        this.allowedPrivateHosts = 
Collections.unmodifiableSet(normalizeHosts(builder.allowedPrivateHosts));
+        this.allowedPrivateCidrs = Collections.unmodifiableList(new 
ArrayList<>(builder.allowedPrivateCidrs));
+        this.allowedSchemes = Collections.unmodifiableSet(new 
HashSet<>(builder.schemePolicy.getSchemes()));
+        this.maxRedirects = builder.maxRedirects;
+        this.maxImageBytes = builder.maxImageBytes;
+    }
+
+    public static UrlImageFetchPolicy defaultPolicy() {
+        return DEFAULT;
+    }
+
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    private static Set<String> normalizeHosts(Collection<String> hosts) {
+        Set<String> result = new HashSet<>();
+        for (String host : hosts) {
+            if (host == null) {
+                continue;
+            }
+            String normalized = normalizeHost(host);
+            if (!normalized.isEmpty()) {
+                result.add(normalized);
+            }
+        }
+        return result;
+    }
+
+    static String normalizeHost(String host) {
+        String normalized = host.trim().toLowerCase(Locale.ROOT);
+        while (normalized.endsWith(".")) {
+            normalized = normalized.substring(0, normalized.length() - 1);
+        }
+        if (normalized.isEmpty()) {
+            return normalized;
+        }

Review Comment:
   UrlImageFetchPolicy.normalizeHost() always applies IDN.toASCII(). This 
throws IllegalArgumentException for valid IPv6-literal hosts (e.g., URLs like 
http://[2001:db8::1]/), causing UrlImageConverter to reject otherwise-valid 
public IPv6 URLs. Consider bypassing IDN normalization for IP-literals 
(InetAddress parsing / presence of ':'), and only applying IDN.toASCII to DNS 
hostnames.
   



##########
fesod-sheet/src/main/java/org/apache/fesod/sheet/converters/url/UrlImageFetchPolicy.java:
##########
@@ -0,0 +1,155 @@
+/*
+ * 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.fesod.sheet.converters.url;
+
+import java.net.IDN;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+
+/**
+ * Security policy for fetching images from URL values.
+ */
+@Getter
+@EqualsAndHashCode
+public final class UrlImageFetchPolicy {
+
+    public static final int DEFAULT_MAX_REDIRECTS = 3;
+    public static final int DEFAULT_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
+
+    private static final UrlImageFetchPolicy DEFAULT = builder().build();
+
+    private final boolean allowPrivateNetwork;
+    private final Set<String> allowedPrivateHosts;
+    private final List<CidrBlock> allowedPrivateCidrs;
+    private final Set<String> allowedSchemes;
+    private final int maxRedirects;
+    private final int maxImageBytes;
+
+    private UrlImageFetchPolicy(Builder builder) {
+        this.allowPrivateNetwork = builder.allowPrivateNetwork;
+        this.allowedPrivateHosts = 
Collections.unmodifiableSet(normalizeHosts(builder.allowedPrivateHosts));
+        this.allowedPrivateCidrs = Collections.unmodifiableList(new 
ArrayList<>(builder.allowedPrivateCidrs));
+        this.allowedSchemes = Collections.unmodifiableSet(new 
HashSet<>(builder.schemePolicy.getSchemes()));
+        this.maxRedirects = builder.maxRedirects;
+        this.maxImageBytes = builder.maxImageBytes;
+    }
+
+    public static UrlImageFetchPolicy defaultPolicy() {
+        return DEFAULT;
+    }
+
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    private static Set<String> normalizeHosts(Collection<String> hosts) {
+        Set<String> result = new HashSet<>();
+        for (String host : hosts) {
+            if (host == null) {
+                continue;
+            }
+            String normalized = normalizeHost(host);
+            if (!normalized.isEmpty()) {
+                result.add(normalized);
+            }
+        }
+        return result;
+    }
+
+    static String normalizeHost(String host) {
+        String normalized = host.trim().toLowerCase(Locale.ROOT);
+        while (normalized.endsWith(".")) {
+            normalized = normalized.substring(0, normalized.length() - 1);
+        }
+        if (normalized.isEmpty()) {
+            return normalized;
+        }
+        return IDN.toASCII(normalized);
+    }
+
+    public static final class Builder {
+        private boolean allowPrivateNetwork;
+        private Set<String> allowedPrivateHosts = Collections.emptySet();
+        private List<CidrBlock> allowedPrivateCidrs = Collections.emptyList();
+        private SchemePolicy schemePolicy = SchemePolicy.HTTP_OR_HTTPS;
+        private int maxRedirects = DEFAULT_MAX_REDIRECTS;
+        private int maxImageBytes = DEFAULT_MAX_IMAGE_BYTES;
+
+        private Builder() {}
+
+        public Builder allowPrivateNetwork(boolean allowPrivateNetwork) {
+            this.allowPrivateNetwork = allowPrivateNetwork;
+            return this;
+        }
+
+        public Builder allowedPrivateHosts(Collection<String> 
allowedPrivateHosts) {
+            if (allowedPrivateHosts == null) {
+                this.allowedPrivateHosts = Collections.emptySet();
+            } else {
+                this.allowedPrivateHosts = new HashSet<>(allowedPrivateHosts);
+            }
+            return this;
+        }
+
+        public Builder allowedPrivateCidrs(Collection<CidrBlock> 
allowedPrivateCidrs) {
+            if (allowedPrivateCidrs == null) {
+                this.allowedPrivateCidrs = Collections.emptyList();
+            } else {
+                this.allowedPrivateCidrs = new 
ArrayList<>(allowedPrivateCidrs);
+            }
+            return this;
+        }
+
+        public Builder allowedSchemes(SchemePolicy schemePolicy) {
+            if (schemePolicy == null) {
+                throw new IllegalArgumentException("Scheme policy can not be 
null");
+            }
+            this.schemePolicy = schemePolicy;
+            return this;
+        }

Review Comment:
   Builder method name allowedSchemes(...) is misleading because it accepts a 
SchemePolicy (enum) rather than a collection of schemes. Consider renaming it 
to schemePolicy(...) (or similar) to avoid API confusion for callers.



##########
fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/UrlImageConverterTest.java:
##########
@@ -0,0 +1,222 @@
+/*
+ * 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.fesod.sheet.converter;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.fesod.sheet.converters.url.CidrBlock;
+import org.apache.fesod.sheet.converters.url.SchemePolicy;
+import org.apache.fesod.sheet.converters.url.UrlImageConverter;
+import org.apache.fesod.sheet.converters.url.UrlImageFetchPolicy;
+import org.apache.fesod.sheet.metadata.GlobalConfiguration;
+import org.apache.fesod.sheet.metadata.data.WriteCellData;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests {@link UrlImageConverter}.
+ */
+class UrlImageConverterTest {
+
+    private static final byte[] PNG_BYTES =
+            new byte[] {(byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 
0x00, 0x00, 0x00, 0x0D};
+
+    private final UrlImageConverter converter = new UrlImageConverter();
+    private HttpServer server;
+    private AtomicInteger requestCount;
+
+    @BeforeEach
+    void beforeEach() {
+        UrlImageConverter.resetFetchPolicy();
+        requestCount = new AtomicInteger();
+    }
+
+    @AfterEach
+    void afterEach() {
+        UrlImageConverter.resetFetchPolicy();
+        if (server != null) {
+            server.stop(0);
+        }
+    }
+
+    @Test
+    void test_rejectFileProtocol() {
+        IOException exception =
+                Assertions.assertThrows(IOException.class, () -> convert(new 
URL("file:///etc/passwd")));
+
+        Assertions.assertTrue(exception.getMessage().contains("protocol"));
+    }
+
+    @Test
+    void test_rejectNullSchemePolicy() {
+        Assertions.assertThrows(
+                IllegalArgumentException.class,
+                () -> 
UrlImageFetchPolicy.builder().allowedSchemes(null).build());
+    }
+
+    @Test
+    void test_httpsOnlyPolicyRejectsHttpUrl() throws Exception {
+        URL url = startServer(HttpStatus.OK, PNG_BYTES, "image/png");
+        UrlImageConverter.setFetchPolicy(
+                
UrlImageFetchPolicy.builder().allowedSchemes(SchemePolicy.HTTPS).build());
+
+        IOException exception = Assertions.assertThrows(IOException.class, () 
-> convert(url));
+
+        Assertions.assertTrue(exception.getMessage().contains("protocol"));
+        Assertions.assertEquals(0, requestCount.get());
+    }
+
+    @Test
+    void test_rejectLoopbackByDefault() throws Exception {
+        URL url = startServer(HttpStatus.OK, PNG_BYTES, "image/png");
+
+        IOException exception = Assertions.assertThrows(IOException.class, () 
-> convert(url));
+
+        Assertions.assertTrue(exception.getMessage().contains("restricted 
address"));
+        Assertions.assertEquals(0, requestCount.get());
+    }
+
+    @Test
+    void test_allowPrivateHostWhenExplicitlyAllowlisted() throws Exception {
+        URL url = startServer(HttpStatus.OK, PNG_BYTES, "image/png");
+        UrlImageConverter.setFetchPolicy(UrlImageFetchPolicy.builder()
+                .allowPrivateNetwork(true)
+                .allowedPrivateHosts(Collections.singleton("127.0.0.1"))
+                .build());
+
+        WriteCellData<?> cellData = convert(url);
+
+        Assertions.assertArrayEquals(
+                PNG_BYTES, cellData.getImageDataList().get(0).getImage());
+        Assertions.assertEquals(1, requestCount.get());
+    }
+
+    @Test
+    void test_allowPrivateCidrWhenExplicitlyAllowlisted() throws Exception {
+        URL url = startServer(HttpStatus.OK, PNG_BYTES, "image/png");
+        UrlImageConverter.setFetchPolicy(UrlImageFetchPolicy.builder()
+                .allowPrivateNetwork(true)
+                
.allowedPrivateCidrs(Collections.singleton(CidrBlock.parse("127.0.0.0/8")))
+                .build());
+
+        WriteCellData<?> cellData = convert(url);
+
+        Assertions.assertArrayEquals(
+                PNG_BYTES, cellData.getImageDataList().get(0).getImage());
+    }
+
+    @Test
+    void test_rejectNonImageResponse() throws Exception {
+        URL url = startServer(HttpStatus.OK, "root:x:0:0".getBytes("UTF-8"), 
"text/plain");
+        UrlImageConverter.setFetchPolicy(allowLoopbackPolicy());
+

Review Comment:
   Use StandardCharsets.UTF_8 instead of "UTF-8" to avoid checked 
UnsupportedEncodingException plumbing and to match the charset usage pattern 
used in other tests in this module.



##########
fesod-sheet/src/main/java/org/apache/fesod/sheet/converters/url/UrlImageConverter.java:
##########
@@ -53,18 +77,167 @@ public Class<?> supportJavaTypeKey() {
     public WriteCellData<?> convertToExcelData(
             URL value, ExcelContentProperty contentProperty, 
GlobalConfiguration globalConfiguration)
             throws IOException {
-        InputStream inputStream = null;
+        byte[] bytes = readImage(value, fetchPolicy);
+        ImageData.ImageType imageType = FileTypeUtils.getImageType(bytes);
+        if (imageType == null) {
+            throw new IOException("URL image data is not a supported image 
type");
+        }
+        return new WriteCellData<>(bytes);
+    }
+
+    private byte[] readImage(URL value, UrlImageFetchPolicy policy) throws 
IOException {
+        URL currentUrl = value;
+        for (int redirectCount = 0; redirectCount <= policy.getMaxRedirects(); 
redirectCount++) {
+            validateUrl(currentUrl, policy);
+            HttpURLConnection connection = openConnection(currentUrl);
+            try {
+                int responseCode = connection.getResponseCode();
+                if (isRedirect(responseCode)) {
+                    if (redirectCount == policy.getMaxRedirects()) {
+                        throw new IOException("URL image request exceeded 
redirect limit");
+                    }
+                    currentUrl = resolveRedirect(currentUrl, 
connection.getHeaderField("Location"));
+                    continue;
+                }
+                if (responseCode < HttpURLConnection.HTTP_OK || responseCode 
>= HttpURLConnection.HTTP_MULT_CHOICE) {
+                    throw new IOException("URL image request failed with HTTP 
status " + responseCode);
+                }
+                int contentLength = connection.getContentLength();
+                if (contentLength > policy.getMaxImageBytes()) {
+                    throw new IOException("URL image data exceeds maximum 
size");
+                }
+                try (InputStream inputStream = connection.getInputStream()) {
+                    return readLimited(inputStream, policy.getMaxImageBytes());
+                }
+            } finally {
+                connection.disconnect();
+            }
+        }
+        throw new IOException("URL image request exceeded redirect limit");
+    }
+
+    private HttpURLConnection openConnection(URL value) throws IOException {
+        HttpURLConnection connection = (HttpURLConnection) 
value.openConnection();
+        connection.setConnectTimeout(urlConnectTimeout);
+        connection.setReadTimeout(urlReadTimeout);
+        connection.setInstanceFollowRedirects(false);
+        return connection;
+    }
+
+    private void validateUrl(URL value, UrlImageFetchPolicy policy) throws 
IOException {
+        String protocol = value.getProtocol();
+        if (protocol == null || 
!policy.getAllowedSchemes().contains(protocol.toLowerCase(Locale.ROOT))) {
+            throw new IOException("URL image protocol is not allowed");
+        }
+        String host = value.getHost();
+        if (host == null || host.trim().isEmpty()) {
+            throw new IOException("URL image host is required");
+        }
+
+        String normalizedHost;
+        try {
+            normalizedHost = UrlImageFetchPolicy.normalizeHost(host);
+        } catch (IllegalArgumentException e) {
+            throw new IOException("URL image host is invalid", e);
+        }
+
+        InetAddress[] addresses = InetAddress.getAllByName(normalizedHost);
+        if (addresses.length == 0) {
+            throw new IOException("URL image host can not be resolved");
+        }
+        for (InetAddress address : addresses) {
+            if (isRestrictedAddress(address) && 
!isAllowedPrivateAddress(normalizedHost, address, policy)) {
+                throw new IOException("URL image host resolves to a restricted 
address");
+            }
+        }

Review Comment:
   validateUrl() resolves the hostname (InetAddress.getAllByName) and checks 
for restricted addresses, but the subsequent HttpURLConnection will perform its 
own DNS resolution when connecting. This leaves a DNS-rebinding window where 
validation can pass and the actual connection can go to a different 
(potentially restricted) IP. If SSRF protection is a goal, consider enforcing 
the resolved/validated IP at connection time (e.g., connect to the numeric IP 
and set the Host header, or use an HTTP client that exposes the remote address 
for post-connect verification).



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