rishabhdaim commented on code in PR #75:
URL: 
https://github.com/apache/sling-org-apache-sling-engine/pull/75#discussion_r4795776101


##########
src/main/java/org/apache/sling/engine/impl/helper/ContentTypeUtil.java:
##########
@@ -0,0 +1,49 @@
+/*
+ * 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.sling.engine.impl.helper;
+
+import org.jetbrains.annotations.Nullable;
+
+public final class ContentTypeUtil {
+
+    private ContentTypeUtil() {}
+
+    /**
+     * Returns the charset parameter of a Content-Type header, or {@code null}
+     * if no non-empty charset parameter is present.
+     */
+    public static @Nullable String getCharset(@Nullable final String 
contentType) {
+        if (contentType == null) {
+            return null;
+        }
+        final String[] parts = contentType.split(";");

Review Comment:
   ๐ŸŸ  **P2** ยท ๐ŸŽฏ Correctness
   
   **๐Ÿ” Issue:** `text/plain; name="note;charset=US-ASCII;.txt"; charset=UTF-8` 
selects the charset inside the quoted name, corrupting UTF-8 uploaded-file 
content returned by `getString()`.
   
   **๐Ÿ› ๏ธ Fix:** Parse parameter separators only outside quoted strings, 
respecting escaped quotes, and add a regression asserting this Content-Type 
with UTF-8 bytes for `รค` decodes to `รค`.
   
   **Attribution:** Introduced



##########
src/main/java/org/apache/sling/engine/impl/parameters/ParameterMap.java:
##########
@@ -71,6 +71,7 @@ void renameParameter(String oldName, String newName) {
         }
 
         super.put(newName, params);
+        this.stringParameterMap = null;

Review Comment:
   ๐ŸŸก **P3** ยท ๐ŸŽฏ Correctness
   
   **๐Ÿ” Issue:** The rename and append tests never populate the string-map cache 
before mutation, so removing these new invalidations would leave the tests 
passing.
   
   **๐Ÿ› ๏ธ Fix:** Call `getStringParameterMap()` before each mutation, then assert 
a fresh read replaces the renamed key or includes the appended value.
   
   **Attribution:** Introduced



##########
src/test/java/org/apache/sling/engine/impl/parameters/ParameterSupportTest.java:
##########
@@ -252,4 +558,52 @@ public int read() {
             }
         };
     }
+
+    @Test
+    public void testContainerMultipartSizeLimitIsRejectedAndCached() throws 
IOException, ServletException {
+        mockMultipartPost();
+        Mockito.doThrow(new IllegalStateException("Request exceeds configured 
multipart size"))
+                .when(mockRequest)
+                .getParts();
+
+        final SlingParameterParseException failure =
+                assertThrows(SlingParameterParseException.class, 
support::getRequestParameterMap);
+        assertTrue(failure.getCause() instanceof IllegalStateException);
+        assertSame(failure, assertThrows(SlingParameterParseException.class, 
support::getRequestParameterList));
+    }
+
+    private void mockMultipartPost() throws IOException, ServletException {
+        Mockito.doReturn("POST").when(mockRequest).getMethod();
+        
Mockito.doReturn("multipart/form-data").when(mockRequest).getContentType();
+        
Mockito.doReturn("qkey1=qvalue2&qkey2=qvalue2").when(mockRequest).getQueryString();
+
+        Map<String, String[]> containerParams = new HashMap<>();
+        containerParams.put("key1", new String[] {"value1"});
+        containerParams.put("key2", new String[] {"value2"});
+        Mockito.doReturn(containerParams).when(mockRequest).getParameterMap();
+
+        Part part1 = Mockito.mock(Part.class);
+        Mockito.doReturn("key1").when(part1).getName();
+        Mockito.doReturn(new ByteArrayInputStream("value1".getBytes()))
+                .when(part1)
+                .getInputStream();
+        Part part2 = Mockito.mock(Part.class);
+        Mockito.doReturn("key2").when(part2).getName();
+        Mockito.doReturn("file2.txt").when(part2).getSubmittedFileName();
+        Mockito.doReturn(new ByteArrayInputStream("value2".getBytes()))
+                .when(part2)
+                .getInputStream();
+        Mockito.doReturn(List.of(part1, part2)).when(mockRequest).getParts();

Review Comment:
   ๐ŸŸก **P3** ยท ๐ŸŽฏ Correctness
   
   **๐Ÿ” Issue:** Mocked Parts bypass the new container-decoding boundary, 
leaving its interaction with Sling recoding untested for non-ASCII 
names/filenames, repeated fields, and charset overrides.
   
   **๐Ÿ› ๏ธ Fix:** Add container-backed tests using raw multipart bodies through 
the service-processing entry point, asserting RequestParameter/Part results for 
an explicit request charset, `_charset_`, repeated values, and non-ASCII 
names/filenames.
   
   **Attribution:** Introduced



##########
src/main/java/org/apache/sling/engine/impl/SlingMainServlet.java:
##########
@@ -181,6 +186,22 @@ private Dictionary<String, Object> 
getServletContextRegistrationProps(final Stri
         if (servletName != null) {
             
servletConfig.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, 
servletName);
         }
+
+        // configure support for multipart file uploads
+        
servletConfig.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_MULTIPART_ENABLED,
 true);
+        // dig the multipart configuration out of the "Request Parameter 
Handling" configuration
+        final String multipartLocation = reqParamConfig.resolveLocation();
+        if (multipartLocation != null) {
+            
servletConfig.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_MULTIPART_LOCATION,
 multipartLocation);
+        }
+        final 
org.apache.sling.engine.impl.parameters.RequestParameterConfig.Config config = 
reqParamConfig.getConfig();
+        
servletConfig.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_MULTIPART_MAXFILESIZE,
 config.file_max());

Review Comment:
   ๐ŸŸก **P3** ยท ๐ŸŽฏ Correctness
   
   **๐Ÿ” Issue:** The servlet fixture now supplies multipart configuration, but 
no assertion checks the newly registered whiteboard properties.
   
   **๐Ÿ› ๏ธ Fix:** Inspect the registered Servlet service properties for 
default/non-default enablement, location, byte limits, threshold, and file 
count, then reactivate with changed configuration and assert the updated 
registration.
   
   **Attribution:** Introduced



##########
src/main/java/org/apache/sling/engine/impl/parameters/ParameterSupport.java:
##########
@@ -418,55 +381,27 @@ private static final boolean 
isWWWFormEncodedContent(HttpServletRequest request)
         return 
WWW_FORM_URL_ENC.equals(contentType.trim().toLowerCase(Locale.ENGLISH));
     }
 
-    private RequestContext getMultiPartContext() {
-        return new RequestContext() {
-            @Override
-            public String getCharacterEncoding() {
-                String enc = getServletRequest().getCharacterEncoding();
-                return (enc != null) ? enc : Util.ENCODING_DIRECT;
-            }
-
-            @Override
-            public int getContentLength() {
-                return getServletRequest().getContentLength();
-            }
-
-            @Override
-            public String getContentType() {
-                return getServletRequest().getContentType();
-            }
-
-            @Override
-            public InputStream getInputStream() throws IOException {
-                return getServletRequest().getInputStream();
-            }
-        };
+    /**
+     * Checks if the request is a multipart post
+     *
+     * @param request the request to check
+     * @return true if the request is multipart, false otherwise
+     */
+    private static boolean isMultipartContent(HttpServletRequest request) {
+        final String contentType = request.getContentType();
+        return contentType != null && 
contentType.toLowerCase(Locale.ENGLISH).startsWith(MULTIPART);
     }
 
-    private void parseMultiPartPost(ParameterMap parameters) {
-        // Create a new file upload handler
-        ServletFileUpload upload = new ServletFileUpload();
-        upload.setSizeMax(ParameterSupport.maxRequestSize);
-        upload.setFileSizeMax(ParameterSupport.maxFileSize);
-        upload.setFileItemFactory(
-                new DiskFileItemFactory(ParameterSupport.fileSizeThreshold, 
ParameterSupport.location));
-        upload.setFileCountMax(ParameterSupport.maxFileCount);
-        final RequestContext rc = this.getMultiPartContext();
-
-        // Parse the request. A FileUploadException is request-fatal.
-        List<?> /* FileItem */ items = null;
-        try {
-            items = upload.parseRequest(rc);
-        } catch (FileUploadException fue) {
-            throw failParse("Error parsing multipart request", fue);
+    private void parseMultiPartPost(ParameterMap parameters, String encoding) 
throws IOException, ServletException {
+        final Collection<Part> parts = this.getServletRequest().getParts();
+        long filePartCount =

Review Comment:
   ๐ŸŸก **P3** ยท ๐Ÿ—๏ธ Design/deduplication
   
   **๐Ÿ” Issue:** Buffered and streaming paths separately encode the same 
file-count predicate, boundary, and exception contract, requiring coordinated 
edits when that policy changes.
   
   **๐Ÿ› ๏ธ Fix:** Extract a package-private collect-and-check helper shared with 
`RequestPartsIterator`, preserving lazy invocation, the unlimited case, and 
each caller's exception wrapping.
   
   **Attribution:** Introduced



##########
src/test/java/org/apache/sling/engine/impl/parameters/RequestParameterConfigTest.java:
##########
@@ -0,0 +1,109 @@
+/*
+ * 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.sling.engine.impl.parameters;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Map;
+
+import org.apache.sling.settings.SlingSettingsService;
+import org.apache.sling.testing.mock.osgi.junit.OsgiContext;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+/**
+ *
+ */
+public class RequestParameterConfigTest {
+    @Rule
+    public final OsgiContext osgiContext = new OsgiContext();
+
+    private RequestParameterConfig config;
+
+    private String tmpDir;
+
+    @Before
+    public void before() {
+        // Satisfy mandatory reference to SlingSettingsService
+        SlingSettingsService mockSettingSvc =
+                osgiContext.registerService(SlingSettingsService.class, 
Mockito.mock(SlingSettingsService.class));
+        tmpDir = System.getProperty("java.io.tmpdir");
+        Mockito.doReturn(tmpDir).when(mockSettingSvc).getSlingHomePath();
+
+        config = osgiContext.registerInjectActivateService(
+                RequestParameterConfig.class, 
Map.of("sling.default.max.parameters", -1L, "request.max", 1000L));
+    }
+
+    /**
+     * Test method for {@link 
org.apache.sling.engine.impl.parameters.RequestParameterConfig#getConfig()}.
+     */
+    @Test
+    public void testGetConfig() {
+        assertNotNull(config.getConfig());
+    }
+
+    /**
+     * Test method for {@link 
org.apache.sling.engine.impl.parameters.RequestParameterConfig#resolveLocation()}.
+     */
+    @Test
+    public void testResolveLocationWithNull() {
+        assertNull(config.resolveLocation());
+    }
+
+    @Test
+    public void testResolveLocationWithRelativePath() {
+        config = osgiContext.registerInjectActivateService(
+                RequestParameterConfig.class, Map.of("file.location", "temp"));
+        assertNotNull(config.resolveLocation());
+    }
+
+    @Test
+    public void testResolveLocationWithAbsoluteFolderPath() throws IOException 
{
+        final Path tempFile = Files.createTempDirectory("test");

Review Comment:
   ๐ŸŸก **P3** ยท ๐Ÿ”ง Resource lifecycle
   
   **๐Ÿ” Issue:** These tests create a temporary directory and two files without 
cleanup, while the relative-path case also uses the shared temporary-directory 
child `temp`.
   
   **๐Ÿ› ๏ธ Fix:** Put all fixtures and the mock Sling home under one unique 
test-owned root, retain the original file path before resolving its child, and 
delete the root in `@After`.
   
   **Attribution:** Introduced



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

Reply via email to