Repository navigation
Description
Summary
MONAI has grown several near-duplicate helpers that all implement the same primitive: "join a
relative/remote-supplied name onto a base directory and refuse the result if it resolves outside
that directory." They were added independently, so they diverge in behaviour and return type, and
every new file-writing call site re-implements the check by hand. We should consolidate them into
one shared helper and route all call sites through it.
Current copies (on dev)
| Location | Helper | Returns | Notable behaviour |
|---|---|---|---|
monai/apps/utils.py:138 |
safe_extract_member |
safe join path | resolve+commonpath, plus archive-specific abs/.. text reject and symlink/hardlink member reject |
monai/apps/nnunet/nnunetv2_runner.py:43 |
_confine_to_dir(candidate, allowed_dir, description) |
the resolved path | resolve+commonpath |
monai/bundle/scripts.py:2011 |
_safe_large_file_path(bundle_path, filepath) |
the unresolved normpath | resolve+commonpath, but returns a different path than it checked |
monai/apps/auto3dseg/bundle_gen.py:83 |
_confined_join(root, name) |
the unresolved join | resolve+commonpath, also rejects the root itself |
Divergences that make this worth fixing, not just tidying:
- Two return the resolved path, two return the unresolved path (one checks
target_realbut returnstarget). - One forbids the root directory itself; the others allow it.
- Error messages and wording are copy-pasted and have drifted.
Related in-flight work introduces a fifth variant, _tmp_download_path in
monai/apps/utils.py (PR #9312), which is the "direct child only, no subdirectories" case. It
should be built on the shared helper rather than standing alone.
Proposal
Add one helper (suggested home monai/apps/utils.py, next to safe_extract_member):
def confined_path(
root: PathLike,
relative: PathLike,
*,
require_existing_dir: bool = False, # root must already be a directory
allow_subdirs: bool = True, # False => reject a/b, direct children only
create_parents: bool = False, # mkdir the resolved parent before returning
) -> Path:
root = Path(root).resolve()
if require_existing_dir and not root.is_dir():
raise ValueError(f"{root} is not an existing directory")
target = Path(root, relative).resolve()
if target == root or not target.is_relative_to(root):
raise ValueError(f"path traversal: {relative!r} escapes {root}")
if not allow_subdirs and target.parent != root:
raise ValueError(f"subdirectory not allowed: {relative!r}")
if create_parents:
target.parent.mkdir(parents=True, exist_ok=True)
return targetNotes on the implementation:
- Resolve both sides. Comparing a resolved target against an unresolved root gives false
positives on platforms where the base is itself a symlink (for example/tmp->/private/tmp
on macOS). The current copies that returnrealpath(root)happen to be fine; a naive
relative_to(root)without resolvingrootwould not be. - Use
is_relative_to(component-wise) rather than a string prefix, so/x/foo2is not treated as
inside/x/foo. - The returned path is the resolved path, so callers write to exactly what was checked.
Call sites to convert
monai/apps/utils.py:138safe_extract_member: keep the archive-member-specific symlink/hardlink
and absolute/..rejects as a thin layer, delegate the join+containment toconfined_path.monai/apps/nnunet/nnunetv2_runner.py:43_confine_to_dir: replace body withconfined_path,
keep the descriptive error wrapping.monai/bundle/scripts.py:2011_safe_large_file_path: replace withconfined_path
(allow_subdirs=True); note this changes the returned path from unresolved to resolved.monai/apps/auto3dseg/bundle_gen.py:83_confined_join: replace withconfined_path(it already
rejects the root, whichconfined_pathdoes too).monai/apps/utils.py_tmp_download_path(PR Keep server-named downloads inside the temporary directory #9312): rebuild onconfined_path(..., allow_subdirs=False).monai/bundle/scripts.py:263_download_from_ngc: the per-file write currently joins the
manifest-suppliedpathonto the bundle directory directly; route it through
confined_path(filepath, file, create_parents=True)so the public NGC download applies the same
containment the other download/extract paths already do.
Acceptance criteria
- A single
confined_pathhelper exists with the signature above and unit tests covering:..
escape, absolute path, sibling-prefix (/x/foo2vs/x/foo), symlinked base directory, the root
itself,allow_subdirs=Falserejectinga/b, andcreate_parents=Truecreating the parent. - All five existing helpers above delegate to it (behaviour preserved except the documented
_safe_large_file_pathreturn-path change), and_download_from_ngcroutes its per-file write
through it. - No call site keeps its own
realpath/commonpathcontainment block. - Existing tests for extraction, nnU-Net inference-info loading, large-file download and BundleGen
export continue to pass.
Per-caller flag mapping
| Caller | allow_subdirs |
create_parents |
require_existing_dir |
|---|---|---|---|
| archive extraction | True | n/a (caller mkdirs) | False |
| nnU-Net inference-info | True | False | False |
| large-file download | True | False | False |
| BundleGen export | True | False | False |
| temp server-named download (#9312) | False | False | False |
| NGC per-file download | True | True | False |
Activity
Consolidate path-confinement helpers into confined_path
Resolve _confine_to_dir candidate against the working directory
Return the resolved destination that passed the containment check
Reject a symlinked export destination before rmtree
Preserve the joined return path from _confined_join
Consolidate path-confinement helpers into confined_path (Project-MONA…