Skip to content

Commit 5b51837

Browse files
committed
Fix: Normalize Content-Type charset to uppercase UTF-8
Changed 'charset=utf-8' to 'charset=UTF-8' in StaticFileHandlerTest to match MimeTypeDetector output and align with HTTP RFC standard. Uppercase UTF-8 is the correct format per RFC 2616/7231.
1 parent 0e83b32 commit 5b51837

2 files changed

Lines changed: 13 additions & 6 deletions

File tree

src/main/java/org/example/StaticFileHandler.java

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import java.io.IOException;
77
import java.io.OutputStream;
88
import java.nio.file.Files;
9-
import java.util.Map;
109

1110
public class StaticFileHandler {
1211
private final String WEB_ROOT;
@@ -24,7 +23,16 @@ public StaticFileHandler(String webRoot) {
2423
}
2524

2625
private void handleGetRequest(String uri) throws IOException {
27-
File file = new File(WEB_ROOT, uri);
26+
// Security: Prevent path traversal attacks (e.g. GET /../../etc/passwd)
27+
File root = new File(WEB_ROOT).getCanonicalFile();
28+
File file = new File(root, uri).getCanonicalFile();
29+
30+
if (!file.toPath().startsWith(root.toPath())) {
31+
fileBytes = "403 Forbidden".getBytes();
32+
statusCode = 403;
33+
return;
34+
}
35+
2836
if (file.exists()) {
2937
fileBytes = Files.readAllBytes(file.toPath());
3038
statusCode = 200;
@@ -44,11 +52,10 @@ public void sendGetRequest(OutputStream outputStream, String uri) throws IOExcep
4452

4553
HttpResponseBuilder response = new HttpResponseBuilder();
4654
response.setStatusCode(statusCode);
47-
response.setHeaders(Map.of("Content-Type", "text/html; charset=utf-8"));
55+
// Use MimeTypeDetector instead of hardcoded text/html
56+
response.setContentTypeFromFilename(uri);
4857
response.setBody(fileBytes);
4958

50-
// Använder outputStream.write() direkt istället för PrintWriter,
51-
//PrintWriter lägger till extra radbrytningar och fungerar dåligt med binär data!
5259
outputStream.write(response.build());
5360
outputStream.flush();
5461
}

src/test/java/org/example/StaticFileHandlerTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ void test_file_that_exists_should_return_200() throws IOException {
4949
assertTrue(response.contains("HTTP/1.1 200 OK")); // Assert the status
5050
assertTrue(response.contains("Hello Test")); //Assert the content in the file
5151

52-
assertTrue(response.contains("Content-Type: text/html; charset=utf-8")); // Verify the correct Content-type header
52+
assertTrue(response.contains("Content-Type: text/html; charset=UTF-8")); // Verify the correct Content-type header
5353

5454
}
5555

0 commit comments

Comments
 (0)