Copilot commented on code in PR #914: URL: https://github.com/apache/fesod/pull/914#discussion_r3220209872
########## fesod-sheet/src/test/java/org/apache/fesod/sheet/converter/UrlImageConverterTest.java: ########## @@ -0,0 +1,209 @@ +/* + * 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.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_rejectUnsupportedPolicyScheme() { + Assertions.assertThrows(IllegalArgumentException.class, () -> UrlImageFetchPolicy.builder() + .allowedSchemes(Collections.singleton("file")) + .build()); + } + + @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"); Review Comment: Prefer `StandardCharsets.UTF_8` over `"UTF-8"` to avoid the checked-encoding lookup and to make the test simpler/safer (no dependency on string-identified charset names). ########## fesod-sheet/src/main/java/org/apache/fesod/sheet/converters/url/UrlImageFetchPolicy.java: ########## @@ -0,0 +1,174 @@ +/* + * 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.Arrays; +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(normalizeSchemes(builder.allowedSchemes)); + 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: `normalizeHost` always applies `IDN.toASCII(...)`, which will throw for IPv6 literals (e.g., `::1`, `2001:db8::1`). This prevents using IPv6 literal hosts in URLs and also breaks configuring `allowedPrivateHosts` with IPv6 values. Consider detecting IP-literals (especially hosts containing `:`) and bypassing IDN conversion for them (while still lowercasing/trimming and removing trailing dots where applicable), so IPv6 allowlisting and URL fetching works as intended. ########## fesod-sheet/src/main/java/org/apache/fesod/sheet/converters/url/UrlImageConverter.java: ########## @@ -44,6 +51,23 @@ public class UrlImageConverter implements Converter<URL> { public static int urlConnectTimeout = 1000; public static int urlReadTimeout = 5000; + private static volatile UrlImageFetchPolicy fetchPolicy = UrlImageFetchPolicy.defaultPolicy(); + + public static UrlImageFetchPolicy getFetchPolicy() { + return fetchPolicy; + } + + public static void setFetchPolicy(UrlImageFetchPolicy fetchPolicy) { + if (fetchPolicy == null) { + throw new IllegalArgumentException("Fetch policy can not be null"); + } + UrlImageConverter.fetchPolicy = fetchPolicy; + } + + public static void resetFetchPolicy() { + fetchPolicy = UrlImageFetchPolicy.defaultPolicy(); Review Comment: The policy is global mutable static state. Even with `volatile`, callers in different threads/components can race to change policy, leading to unpredictable behavior and potential security misconfiguration in multi-tenant or concurrent environments. Consider making the policy an instance-level dependency (e.g., constructor injection) or sourcing it from `GlobalConfiguration` so calls to `convertToExcelData(...)` are not affected by unrelated threads updating global state. ########## fesod-sheet/src/main/java/org/apache/fesod/sheet/converters/url/UrlImageConverter.java: ########## @@ -44,6 +51,23 @@ public class UrlImageConverter implements Converter<URL> { public static int urlConnectTimeout = 1000; public static int urlReadTimeout = 5000; + private static volatile UrlImageFetchPolicy fetchPolicy = UrlImageFetchPolicy.defaultPolicy(); + + public static UrlImageFetchPolicy getFetchPolicy() { + return fetchPolicy; + } + + public static void setFetchPolicy(UrlImageFetchPolicy fetchPolicy) { + if (fetchPolicy == null) { + throw new IllegalArgumentException("Fetch policy can not be null"); Review Comment: The error message uses “can not”, which is typically spelled “cannot” in user-facing messages. Consider updating for consistency/readability (and apply the same change to other newly added messages using “can not”). ########## 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: The SSRF protection validates DNS results via `InetAddress.getAllByName(...)`, but the subsequent `openConnection(currentUrl)` will resolve the hostname again at connect time. This creates a DNS rebinding/TOCTOU gap: a hostname could validate to a public IP, then resolve to a restricted/private IP when the connection is actually established. To close the gap, consider connecting to a specific validated `InetAddress` (for HTTP, by using the IP literal in the connection target while preserving the original Host header; for HTTPS, you’ll need to ensure SNI/hostname verification still uses the original hostname), or otherwise implement a transport where the resolved address used for the TCP connection can be verified against the validated addresses. -- 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]
