Video in progress
This endpoint lets users download files from their own directories. Does it pass a security review? What layers of protection do you put in multi-tenant file storage?
@GetMapping("/tenants/{tenant}/files")
Resource download(@PathVariable String tenant, @RequestParam String name) {
Path p = Paths.get("/data", tenant, name);
return new FileSystemResource(p);
}
It does not: by passing ../../other-tenant/secret.pdf or an absolute path as name, you can get another customer's file. You need to normalize the path and check that it stays inside the root, but the main protection is not using user-supplied names as a path at all.
📖 Answer
This code has several holes: name can contain ..; nobody checks that tenant itself belongs to the user's current tenant; and if the code is later changed to use resolve, an absolute path (/etc/passwd) replaces the earlier part entirely. Paths.get(first, more...) just joins the pieces with a separator, so the main hole here is ...
The minimal fix is normalize plus a prefix check:
Path root = Path.of("/data").resolve(currentTenant()).toRealPath();
Path target = root.resolve(name).normalize();
if (!target.startsWith(root)) throw new AccessDeniedException(name);
Path real = target.toRealPath(); // symlinks are resolved
if (!real.startsWith(root)) throw new AccessDeniedException(name);
startsWith on a Path compares components, not strings, so /data/acme2 is not considered to be inside /data/acme. Checking with String.startsWith makes exactly this mistake.
But this is only the first layer. At the architecture level I add several more layers:
- Names in the database. The user requests a file by ID; the ID → (tenant, storage key) mapping is in the database, and the storage key is a UUID the service generated. User text never becomes a path, and the permission check becomes a plain SQL condition.
- Symlinks. If a tenant can upload files and archives get extracted, a symlink can be used to escape the root. When extracting an archive, guard against "zip slip": check every entry name as above and reject symlink entries.
- Isolation. In object storage, a separate prefix and IAM policy per tenant, or for very sensitive data a separate bucket and encryption key. Even if there is a bug in the code, the permission layer won't hand out another tenant's data.
- Response headers.
Content-Disposition: attachmentandX-Content-Type-Options: nosniff, so that an uploaded HTML file doesn't run as a script on your domain. - Testing. Automated tests with path traversal payloads (
..%2f,..\\, URL-encoded, Unicode variants) and a security scanner on every release.
Sign up to mark studied questions and save your progress.