Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
Expand All @@ -42,25 +43,49 @@ public void service(HttpRequest request, HttpResponse response)
}

// This code will process each file uploaded.
String tempDirectory = System.getProperty("java.io.tmpdir");
Path tempDirectory =
Paths.get(System.getProperty("java.io.tmpdir")).toAbsolutePath().normalize();
for (HttpRequest.HttpPart httpPart : request.getParts().values()) {
String filename = httpPart.getFileName().orElse(null);
if (filename == null) {
continue;
}

logger.info("Processed file: " + filename);
// Strip any client-supplied path components to prevent path traversal.
Path filePath;
String sanitizedFilename;
try {
Path baseName = Paths.get(filename).getFileName();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

On Unix-like systems, backslashes (\\) are treated as regular characters rather than directory separators. If a client uploads a file with a Windows-style path (e.g., ..\\..\\foo.txt) to a Unix server, Paths.get(filename).getFileName() will return the entire string ..\\..\\foo.txt as the filename. While this prevents directory traversal on the Unix server itself, it results in an unusual filename containing backslashes and .. components, which could cause issues if processed further or transferred to a Windows system.

Normalizing both forward and backward slashes to / before extracting the filename ensures consistent and secure behavior across all operating systems.

Suggested change
Path baseName = Paths.get(filename).getFileName();
Path baseName = Paths.get(filename.replace('\\', '/')).getFileName();

if (baseName == null) {
response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST);
return;
}
sanitizedFilename = baseName.toString();
filePath = tempDirectory.resolve(sanitizedFilename).normalize();
} catch (InvalidPathException e) {
response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST);
return;
}

if (!filePath.startsWith(tempDirectory) || filePath.equals(tempDirectory)) {
response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST);
return;
}

logger.info("Processed file: " + sanitizedFilename);

// Note: GCF's temp directory is an in-memory file system
// Thus, any files in it must fit in the instance's memory.
Path filePath = Paths.get(tempDirectory, filename).toAbsolutePath();

// Note: files saved to a GCF instance itself may not persist across executions.
// Persistent files should be stored elsewhere, e.g. a Cloud Storage bucket.
Files.copy(httpPart.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
try {
Files.copy(httpPart.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

// TODO(developer): process saved files here
Files.delete(filePath);
// TODO(developer): process saved files here
} finally {
Files.deleteIfExists(filePath);
}
}

// This code will process other form fields.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Optional;
Expand Down Expand Up @@ -116,4 +119,66 @@ public void functionsHttpFormData_shouldProcessFields() throws IOException {
assertThat(logHandler.getStoredLogRecords().get(0).getMessage()).isEqualTo(
"Processed field: foo (value: bar)");
}

@Test
public void functionsHttpFormData_shouldPreventPathTraversal() throws IOException {
when(request.getMethod()).thenReturn("POST");

Path canaryDir = Files.createTempDirectory("http-form-data-canary");
Path canary = Files.writeString(canaryDir.resolve("canary.txt"), "original");
try {
Path tmpDir = Paths.get(System.getProperty("java.io.tmpdir")).toAbsolutePath().normalize();
String traversalFilename = tmpDir.relativize(canary.toAbsolutePath().normalize()).toString();
Comment on lines +130 to +131

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using toAbsolutePath().normalize() on temporary directories can sometimes lead to flaky tests on systems with symlinked temporary directories (such as macOS, where /var is a symlink to /private/var). If System.getProperty("java.io.tmpdir") and Files.createTempDirectory resolve to different symlinked paths, tmpDir.relativize(canary) can produce an unexpected relative path (e.g., starting with ../ to traverse back to the root), or throw an IllegalArgumentException.

Using toRealPath() resolves all symbolic links and ensures that both paths are fully resolved and on the same canonical path, making the relativization robust and reliable across all platforms.

Suggested change
Path tmpDir = Paths.get(System.getProperty("java.io.tmpdir")).toAbsolutePath().normalize();
String traversalFilename = tmpDir.relativize(canary.toAbsolutePath().normalize()).toString();
Path tmpDir = Paths.get(System.getProperty("java.io.tmpdir")).toRealPath();
String traversalFilename = tmpDir.relativize(canary.toRealPath()).toString();


MockHttpPart mockHttpPart = new MockHttpPart();
mockHttpPart.setFileName(traversalFilename);
mockHttpPart.setInputStream(
new ByteArrayInputStream("attacker".getBytes(StandardCharsets.UTF_8)));

when(request.getParts()).thenReturn(Map.of("mock", mockHttpPart));

new HttpFormData().service(request, response);

assertThat(Files.exists(canary)).isTrue();
assertThat(Files.readString(canary)).isEqualTo("original");
assertThat(logHandler.getStoredLogRecords().get(0).getMessage())
.isEqualTo("Processed file: canary.txt");
} finally {
Files.deleteIfExists(canary);
Files.deleteIfExists(canaryDir);
}
}

@Test
public void functionsHttpFormData_shouldRejectDotDotFilename() throws IOException {
when(request.getMethod()).thenReturn("POST");

MockHttpPart mockHttpPart = new MockHttpPart();
mockHttpPart.setFileName("..");
mockHttpPart.setInputStream(
new ByteArrayInputStream("attacker".getBytes(StandardCharsets.UTF_8)));

when(request.getParts()).thenReturn(Map.of("mock", mockHttpPart));

new HttpFormData().service(request, response);

verify(response, times(1)).setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST);
}

@Test
public void functionsHttpFormData_shouldStripParentTraversalPrefix() throws IOException {
when(request.getMethod()).thenReturn("POST");

MockHttpPart mockHttpPart = new MockHttpPart();
mockHttpPart.setFileName("../../escape-test.txt");
mockHttpPart.setInputStream(
new ByteArrayInputStream("attacker".getBytes(StandardCharsets.UTF_8)));

when(request.getParts()).thenReturn(Map.of("mock", mockHttpPart));

new HttpFormData().service(request, response);

assertThat(logHandler.getStoredLogRecords().get(0).getMessage())
.isEqualTo("Processed file: escape-test.txt");
}
}