Skip to content

Keep server-named downloads inside the temporary directory - #9312

Closed
garciadias wants to merge 2 commits into
devfrom
download-remote-filename-confine
Closed

garciadias wants to merge 2 commits into
devfrom
download-remote-filename-confine

Conversation

@garciadias

@garciadias garciadias commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Description

When download_and_extract(url, output_dir=...) is called without filepath, it downloads the archive into a temporary directory under the file name the server reports (Content-Disposition, or the last part of the URL). That name was joined to the temporary directory unchanged, so a name containing .. components or an absolute path resolved outside the temporary directory and the downloaded file was moved there.

This PR:

  • requires the reported name to be a single path component, and raises ValueError before anything is downloaded when it is not: a name containing / or \ (for example ../a.zip, a/b.zip, /abs/a.zip), and a name that is empty, . or ..;
  • keeps a realpath check that the resolved destination is directly inside the temporary directory;
  • asks the server for the file name once, so the extension check and the download destination use the same response (previously two HEAD requests were made).

An explicit filepath behaves as before, including a nested destination. All built-in callers (MedNISTDataset, DecathlonDataset, the MMAR and TCIA helpers, BundleGen) pass filepath, so their behaviour does not change. The only behaviour change is for a caller that omits filepath and downloads from a server whose reported name contains a directory part: it now gets a ValueError instead of a file stored under the flattened name.

Tests

  • New tests/apps/test_download_remote_filename.py (HTTP mocked, no network): ../, ../../, ..\, sub/archive.zip, sub/.. and an absolute name are all rejected with nothing downloaded and nothing written next to the temporary directory; names with no usable base name (.., ., /, //) are rejected; a plain name round trip, an explicit nested filepath, and a single HEAD request are also covered. 11 of the 13 tests fail on dev; the round trip and explicit-filepath controls pass on both.
  • Re-verified on a second machine (Python 3.12, CUDA host): 13 passed on this branch, 11 failed on dev.
  • tests/apps/test_download_and_extract.py passes locally (13 passed).

Types of changes

  • Non-breaking change (fix or new feature that would not break existing functionality).
  • New tests added to cover the changes.

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review.

Walkthrough

When filepath is omitted, download_and_extract validates the remote filename before using it as a temporary download destination. It retrieves the remote filename once. Tests cover invalid names, successful extraction, request count, and the unchanged behavior when filepath is supplied.

Estimated code review effort: 2 (Simple) | ~10 minutes

Merge Risk: Minimal · previous review 84888

Downloads that rely on a server-reported filename are now confined to the temporary directory, and unsafe names are rejected before any download starts. Behavior with an explicit filepath is unchanged. No merge-blocking risk remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: server-named downloads are kept inside the temporary directory. It matches the raw summary and the PR objectives, so it is specific and accurate.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description covers the problem, the fix, the behaviour change for callers that omit filepath, and the test evidence. It lists the template's Description and Types of changes sections. It leaves th…
Full details: Description check

Explanation

The description covers the problem, the fix, the behaviour change for callers that omit filepath, and the test evidence. It lists the template's Description and Types of changes sections. It leaves the 'New tests added' box ticked by the author, which matches the added test file. Unchecked items (integration tests, quick tests, docs) are not confirmed as run, but the template treats these as checklist items. The description is mostly complete.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 7c00fe0 and 84888ed.

Files selected for processing: 2

  • monai/apps/utils.py
  • tests/apps/test_download_remote_filename.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

…tory

download_and_extract() without filepath now rejects a file name reported by
the server that is not a single path component (it contains a path
separator, or is empty, '.' or '..'), before anything is downloaded. Callers
that need a nested destination pass filepath explicitly. The server is asked
for the name once, so the extension check and the destination use the same
response.

Signed-off-by: R. Garcia-Dias <rafaelagd@gmail.com>
@garciadias
garciadias force-pushed the download-remote-filename-confine branch from 7c00fe0 to 84888ed Compare November 23, 2026 17:36
@ericspod

Copy link
Copy Markdown
Member

I think this one is overtaken by #9324 so closing now.

@ericspod ericspod closed this Nov 26, 2026
ericspod added a commit that referenced this pull request Nov 26, 2026
### Description

Fixes #9324.

MONAI had four near-duplicate helpers that all implement the same
primitive, "join an
untrusted name onto a base directory and reject the result if it
resolves outside that
directory", plus one more variant in flight (#9312). They had drifted:
two returned the
resolved path, two returned the unresolved path (one checked
`target_real` but returned the
unresolved `target`), one forbade the root directory itself and the
others did not, and the error
messages were copy-pasted.

This PR adds a single `monai.apps.utils.confined_path(root, relative, *,
require_existing_dir,
allow_subdirs, create_parents)` helper and routes the existing call
sites through it:

- `safe_extract_member` (archive extraction) keeps its member-specific
symlink/hardlink and
  absolute/`..` rejects, and delegates the join + containment check.
- `nnunetv2_runner._confine_to_dir` keeps its descriptive error and
delegates the check.
- `scripts._safe_large_file_path` delegates (now returns the resolved
path, as it already checked).
- `auto3dseg/bundle_gen._confined_join` delegates (it already rejected
the root).
- `scripts._download_from_ngc` now routes its per-file write (a path
taken from the NGC
`modelFiles` manifest) through `confined_path(...,
create_parents=True)`, so the public NGC
download applies the same containment the other download and extract
paths already have.

Implementation notes:
- Both `root` and the joined target are resolved before comparison, so a
symlinked base directory
(for example `/tmp` -> `/private/tmp` on macOS) does not cause a false
rejection.
- Uses `Path.is_relative_to` (component-wise) rather than a string
prefix, so `/x/foo2` is not
  treated as inside `/x/foo`.
- The containment check stops `..` and symlinked-parent escapes at check
time; the archive path
  keeps its own symlink/hardlink member rejection for the TOCTOU case.

### Tests

- New `tests/apps/test_confined_path.py` (11 tests): plain child, nested
child, `..` traversal,
absolute escape, absolute-inside-root, sibling prefix (`/x/foo2` vs
`/x/foo`), symlinked base
directory, the root itself, `require_existing_dir`,
`allow_subdirs=False`, `create_parents`.
- New `tests/bundle/test_bundle_download.py::TestNgcPathTraversal` (2
tests, HTTP mocked, no
network): a manifest entry with a `..` component is rejected before any
`download_url` call and
nothing is written outside the bundle directory; a legitimate nested
manifest path downloads
inside the bundle directory. Both fail on `dev` and pass on this branch.
- Existing suites that exercise the refactored helpers pass unchanged:
`tests/apps/test_download_and_extract.py` (13),
`tests/auto3dseg/test_export_to_disk.py` and
`tests/apps/nnunet/test_nnunetv2_runner_command.py` (18 + 11 subtests).

### Types of changes
- [x] Non-breaking change (fix or new feature that would not break
existing functionality).
- [x] New tests added to cover the changes.

---------

Signed-off-by: garciadias <rafaelagd@gmail.com>
Co-authored-by: Eric Kerfoot <17726042+ericspod@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants