diff --git a/.jules/sentinel.md b/.jules/sentinel.md
index c42c07ed..bb4f2aa4 100644
--- a/.jules/sentinel.md
+++ b/.jules/sentinel.md
@@ -37,3 +37,8 @@
**Vulnerability:** In `DownloadGetRequestHandler.java`, `info.getFileName()` derived from user-supplied `Upload-Metadata` was embedded directly into the `Content-Disposition` header without stripping path traversal sequences (`../`, `..\`) or directory paths (`/`, `\`). Downstream clients saving files using the suggested filename could write files outside target directories. Additionally, `X-Content-Type-Options: nosniff` was missing when serving completed downloads, leaving browsers susceptible to MIME sniffing attacks.
**Learning:** File download endpoints that reflect user-supplied filenames in `Content-Disposition` headers can cause path traversal vulnerabilities on consuming clients. Serving user-uploaded content without explicit MIME-sniffing protection allows potential content sniffing / script execution.
**Prevention:** Sanitize filenames before constructing `Content-Disposition` by stripping directory paths (Unix `/` and Windows `\`), removing directory traversal sequences (`..`), and falling back to a safe identifier if the sanitized name is empty. Always include `X-Content-Type-Options: nosniff` when serving user-uploaded files.
+
+## 2026-11-15 - Prevent Path Traversal in UploadInfo.getFileName()
+**Vulnerability:** `UploadInfo.getFileName()` returned untrusted client-supplied metadata directly without sanitizing path traversal sequences (`../`, `..\`) or directory delimiters (`/`, `\`). Downstream consumers relying on `uploadInfo.getFileName()` to persist uploaded files were vulnerable to path traversal and arbitrary file overwrite outside the destination directory. Additionally, calling `getFileName()` on an `UploadInfo` with a null ID caused a `NullPointerException`.
+**Learning:** Helper methods that extract filenames from untrusted client metadata must enforce path sanitization at the source, preventing downstream consumers from accidentally introducing path traversal vulnerabilities.
+**Prevention:** Sanitize filenames at extraction in `UploadInfo.getFileName()` via `Utils.sanitizeFileName(...)`, stripping directory paths, traversal sequences, and null bytes while safely falling back to the upload ID or `"download"` if null.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 261bf510..e94f3666 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -47,6 +47,7 @@ See [docs/UPGRADING.md](docs/UPGRADING.md) for details and code examples.
- **`UploadStorageService.cleanupExpiredUploads(UploadLockingService)`**: deprecated in favor of the zero-argument `cleanupExpiredUploads()`.
### Security
+- **UploadInfo filename sanitization**: sanitize `UploadInfo.getFileName()` to prevent directory traversal and null-byte injection, stripping directory paths and traversal sequences with safe fallback to the upload ID.
- **Download extension**: sanitize filenames in `Content-Disposition` to prevent client directory traversal and add `X-Content-Type-Options: nosniff`.
- **CORS origin validation**: prevent arbitrary `Origin` header reflection in CORS responses ([#132](https://github.com/tomdesair/tus-java-server/pull/132)).
- **Temporary file permissions**: use `Files.createTempFile` instead of `File.createTempFile` to enforce owner-only permissions (`0600`, CWE-378) ([#131](https://github.com/tomdesair/tus-java-server/pull/131)).
diff --git a/src/main/java/me/desair/tus/server/download/DownloadGetRequestHandler.java b/src/main/java/me/desair/tus/server/download/DownloadGetRequestHandler.java
index 309348e0..1a8b5c90 100644
--- a/src/main/java/me/desair/tus/server/download/DownloadGetRequestHandler.java
+++ b/src/main/java/me/desair/tus/server/download/DownloadGetRequestHandler.java
@@ -9,12 +9,12 @@
import me.desair.tus.server.HttpMethod;
import me.desair.tus.server.exception.TusException;
import me.desair.tus.server.exception.UploadNotFoundException;
-import me.desair.tus.server.upload.UploadId;
import me.desair.tus.server.upload.UploadInfo;
import me.desair.tus.server.upload.UploadStorageService;
import me.desair.tus.server.util.AbstractRequestHandler;
import me.desair.tus.server.util.TusServletRequest;
import me.desair.tus.server.util.TusServletResponse;
+import me.desair.tus.server.util.Utils;
/** Send the uploaded bytes of finished uploads. */
public class DownloadGetRequestHandler extends AbstractRequestHandler {
@@ -51,7 +51,9 @@ public void process(
servletResponse.setHeader(HttpHeader.CONTENT_LENGTH, Objects.toString(info.getLength()));
- String sanitizedFileName = sanitizeFileName(info.getFileName(), info.getId());
+ // info.getFileName() is pre-sanitized, but passing through Utils.sanitizeFileName ensures
+ // idempotent directory traversal protection before generating Content-Disposition headers
+ String sanitizedFileName = Utils.sanitizeFileName(info.getFileName(), info.getId());
servletResponse.setHeader(
HttpHeader.CONTENT_DISPOSITION,
String.format(
@@ -67,26 +69,4 @@ public void process(
uploadStorageService.copyUploadTo(info, servletResponse.getOutputStream());
}
-
- /**
- * Sanitizes the given filename to prevent directory traversal and header corruption attacks on
- * clients consuming the Content-Disposition header.
- */
- private String sanitizeFileName(String fileName, UploadId uploadId) {
- if (fileName == null || fileName.trim().isEmpty()) {
- return uploadId != null ? uploadId.toString() : "download";
- }
- // Prevent client-side path traversal: strip directory paths across Unix and Windows separators
- String sanitized = fileName.trim();
- int lastSlash = Math.max(sanitized.lastIndexOf('/'), sanitized.lastIndexOf('\\'));
- if (lastSlash >= 0) {
- sanitized = sanitized.substring(lastSlash + 1).trim();
- }
- // Remove directory traversal sequences (..)
- sanitized = sanitized.replace("..", "").trim();
- if (sanitized.isEmpty()) {
- return uploadId != null ? uploadId.toString() : "download";
- }
- return sanitized;
- }
}
diff --git a/src/main/java/me/desair/tus/server/upload/UploadInfo.java b/src/main/java/me/desair/tus/server/upload/UploadInfo.java
index 56f6356f..4691907f 100644
--- a/src/main/java/me/desair/tus/server/upload/UploadInfo.java
+++ b/src/main/java/me/desair/tus/server/upload/UploadInfo.java
@@ -339,20 +339,27 @@ public String getUploadConcatHeaderValue() {
/**
* Try to guess the filename of the uploaded data. If we cannot guess the name we fall back to the
- * ID.
- * NOTE: This is only a guess, there are no guarantees that the return value is correct
+ * ID (or {@code "download"} if the ID is not set).
*
- * @return A potential file name
+ *
The returned filename is sanitized via {@link Utils#sanitizeFileName(String, UploadId)} to + * strip directory paths and path traversal sequences. + * + *
NOTE: This is only a guess, there are no guarantees that the return value is correct.
+ *
+ * @return A sanitized potential file name (never null or blank)
*/
public String getFileName() {
Map Strips Unix ({@code /}) and Windows ({@code \}) directory prefixes, removes {@code ..}
+ * traversal sequences and null bytes ({@code \0}), and falls back to {@code "download"} when the
+ * resulting name is null or blank.
+ *
+ * @param fileName The raw filename string (may be null)
+ * @return A non-null, non-blank sanitized filename
+ */
+ public static String sanitizeFileName(String fileName) {
+ return sanitizeFileName(fileName, null);
+ }
+
+ /**
+ * Sanitizes a client-supplied filename to prevent directory traversal and null-byte injection
+ * when serving downloads or persisting uploaded files.
+ *
+ * Strips Unix ({@code /}) and Windows ({@code \}) directory prefixes, removes {@code ..}
+ * traversal sequences and null bytes ({@code \0}), and falls back to the provided {@link
+ * UploadId} (or {@code "download"} if {@code uploadId} is {@code null}) when the resulting name
+ * is null or blank.
+ *
+ * @param fileName The raw filename string (may be null)
+ * @param uploadId Optional fallback upload ID if the filename is null, blank, or unsafe
+ * @return A non-null, non-blank sanitized filename
+ */
+ public static String sanitizeFileName(String fileName, UploadId uploadId) {
+ if (fileName == null || fileName.trim().isEmpty()) {
+ return uploadId != null ? uploadId.toString() : "download";
+ }
+ // Strip Unix and Windows directory segments so only the terminal filename remains
+ String sanitized = fileName.trim();
+ int lastSlash = Math.max(sanitized.lastIndexOf('/'), sanitized.lastIndexOf('\\'));
+ if (lastSlash >= 0) {
+ sanitized = sanitized.substring(lastSlash + 1).trim();
+ }
+ // Remove path traversal sequences and null bytes that could bypass filesystem or header checks
+ sanitized = sanitized.replace("..", "").replace("\0", "").trim();
+ if (sanitized.isEmpty() || ".".equals(sanitized)) {
+ return uploadId != null ? uploadId.toString() : "download";
+ }
+ return sanitized;
+ }
}
diff --git a/src/test/java/me/desair/tus/server/CoverageGapTest.java b/src/test/java/me/desair/tus/server/CoverageGapTest.java
index 8ddde36f..e0640b58 100644
--- a/src/test/java/me/desair/tus/server/CoverageGapTest.java
+++ b/src/test/java/me/desair/tus/server/CoverageGapTest.java
@@ -193,6 +193,21 @@ public void testAbstractTusExtensionHandleError5Args() throws Exception {
DummyAbstractExtension ext = new DummyAbstractExtension();
ext.handleError(HttpMethod.POST, null, null, null, null);
assertThat(ext.handleError8Called, is(true));
+
+ // Verify 5-arg validate delegates cleanly
+ ext.validate(
+ HttpMethod.POST, new org.springframework.mock.web.MockHttpServletRequest(), null, "owner");
+
+ // Verify 5-arg process delegates cleanly
+ org.springframework.mock.web.MockHttpServletResponse response =
+ new org.springframework.mock.web.MockHttpServletResponse();
+ ext.process(
+ HttpMethod.POST,
+ new TusServletRequest(new org.springframework.mock.web.MockHttpServletRequest()),
+ new TusServletResponse(response),
+ null,
+ "owner");
+ assertThat(ext.getName(), is("dummy"));
}
@Test
diff --git a/src/test/java/me/desair/tus/server/upload/UploadInfoTest.java b/src/test/java/me/desair/tus/server/upload/UploadInfoTest.java
index 9d7371f5..af0af642 100644
--- a/src/test/java/me/desair/tus/server/upload/UploadInfoTest.java
+++ b/src/test/java/me/desair/tus/server/upload/UploadInfoTest.java
@@ -13,7 +13,9 @@
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
+import java.nio.charset.StandardCharsets;
import java.text.ParseException;
+import java.util.Base64;
import java.util.Stack;
import java.util.UUID;
import me.desair.tus.server.HttpHeader;
@@ -194,11 +196,26 @@ public void testGetNameAndTypeWithMetadata() throws Exception {
assertThat(info.getFileName(), is("test.jpg"));
assertThat(info.getFileMimeType(), is("image/jpeg"));
+
+ // Untrusted path traversal sequences in filename metadata must be stripped by getFileName()
+ info.setEncodedMetadata(
+ "filename "
+ + Base64.getEncoder()
+ .encodeToString("../../etc/passwd".getBytes(StandardCharsets.UTF_8)));
+ assertThat(info.getFileName(), is("passwd"));
+
+ // Traversal-only or directory metadata must safely fall back to the upload ID
+ info.setId(new UploadId("test-id"));
+ info.setEncodedMetadata(
+ "filename " + Base64.getEncoder().encodeToString("../..".getBytes(StandardCharsets.UTF_8)));
+ assertThat(info.getFileName(), is("test-id"));
}
@Test
public void testGetNameAndTypeWithoutMetadata() throws Exception {
UploadInfo info = new UploadInfo();
+ assertThat(info.getFileName(), is("download"));
+
final UploadId id = new UploadId(UUID.randomUUID());
info.setId(id);
diff --git a/src/test/java/me/desair/tus/server/util/UtilsTest.java b/src/test/java/me/desair/tus/server/util/UtilsTest.java
index 2661a3b8..caa9210b 100644
--- a/src/test/java/me/desair/tus/server/util/UtilsTest.java
+++ b/src/test/java/me/desair/tus/server/util/UtilsTest.java
@@ -35,6 +35,7 @@
import me.desair.tus.server.HttpHeader;
import me.desair.tus.server.checksum.ChecksumAlgorithm;
import me.desair.tus.server.upload.NoOpUploadLockingService;
+import me.desair.tus.server.upload.UploadId;
import me.desair.tus.server.upload.UploadLockingService;
import me.desair.tus.server.upload.UploadStorageService;
import org.apache.commons.io.FileUtils;
@@ -988,6 +989,23 @@ public void testSanitizePrefix() {
assertEquals("custom/", Utils.sanitizePrefix("/custom///"));
}
+ @Test
+ public void testSanitizeFileName() {
+ UploadId fallbackId = new UploadId("id-1");
+ assertEquals("download", Utils.sanitizeFileName(null));
+ assertEquals("download", Utils.sanitizeFileName(""));
+ assertEquals("id-1", Utils.sanitizeFileName(" ", fallbackId));
+ assertEquals("passwd", Utils.sanitizeFileName("../../etc/passwd", fallbackId));
+ assertEquals("secret.pdf", Utils.sanitizeFileName("C:\\Users\\test\\..\\secret.pdf"));
+ assertEquals("id-1", Utils.sanitizeFileName("../..", fallbackId));
+ assertEquals("download", Utils.sanitizeFileName("../..", null));
+ assertEquals("id-1", Utils.sanitizeFileName(".", fallbackId));
+ assertEquals("download", Utils.sanitizeFileName(".", null));
+ assertEquals("id-1", Utils.sanitizeFileName(".../...", fallbackId));
+ assertEquals("filename.txt", Utils.sanitizeFileName("file\0name.txt"));
+ assertEquals("normal-file.txt", Utils.sanitizeFileName("normal-file.txt", fallbackId));
+ }
+
@Test
public void testCreateUploadExecutor() throws Exception {
ThreadPoolExecutor executor = Utils.createUploadExecutor(2, "test-upload");