Skip to content

Consolidate duplicate path-confinement helpers into one shared helper #9324

Done

Description

@garciadias

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_real but returns target).
  • 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 target

Notes 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 return realpath(root) happen to be fine; a naive
    relative_to(root) without resolving root would not be.
  • Use is_relative_to (component-wise) rather than a string prefix, so /x/foo2 is 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:138 safe_extract_member: keep the archive-member-specific symlink/hardlink
    and absolute/.. rejects as a thin layer, delegate the join+containment to confined_path.
  • monai/apps/nnunet/nnunetv2_runner.py:43 _confine_to_dir: replace body with confined_path,
    keep the descriptive error wrapping.
  • monai/bundle/scripts.py:2011 _safe_large_file_path: replace with confined_path
    (allow_subdirs=True); note this changes the returned path from unresolved to resolved.
  • monai/apps/auto3dseg/bundle_gen.py:83 _confined_join: replace with confined_path (it already
    rejects the root, which confined_path does too).
  • monai/apps/utils.py _tmp_download_path (PR Keep server-named downloads inside the temporary directory #9312): rebuild on confined_path(..., allow_subdirs=False).
  • monai/bundle/scripts.py:263 _download_from_ngc: the per-file write currently joins the
    manifest-supplied path onto 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_path helper exists with the signature above and unit tests covering: ..
    escape, absolute path, sibling-prefix (/x/foo2 vs /x/foo), symlinked base directory, the root
    itself, allow_subdirs=False rejecting a/b, and create_parents=True creating the parent.
  • All five existing helpers above delegate to it (behaviour preserved except the documented
    _safe_large_file_path return-path change), and _download_from_ngc routes its per-file write
    through it.
  • No call site keeps its own realpath/commonpath containment 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

  1. self-assigned this
    on Nov 25, 2026
  2. added 5 commits that reference this issue on Nov 25, 2026
    18f5a56
    d316cf4
    c6b0635
    f2b1cc5
    415ba5f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions