unsloth/studio/backend/utils/paths/external_media.py
ramisworld 01f7e14988
Fix Studio custom folders on Linux external drives (#6799)
* Fix external drive custom folder selection

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update studio/backend/tests/test_linux_external_media_paths.py

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep legacy media scan validation strict

* Apply sensitive-dir denylist to legacy folder browser for PR #6799

The legacy /api/models browse endpoint gained the new /run/media mount
roots in its allowlist but not the credential/config guard that scan-folder
registration and the Hub browser already enforce. Filter sensitive names
during enumeration and reject them in _resolve_browse_target so .ssh, .aws,
.config, etc. under allowlisted roots stay unbrowseable, matching the Hub
browser. Add a public contains_sensitive_path_component helper and cover the
legacy resolver with a regression test.

* Trim redundant comments in PR #6799 changes

* Skip sensitive Linux media roots

* Reject sensitive dirs at exact browse roots for PR #6799

Both _resolve_browse_target functions only checked contains_sensitive_path_component
while walking descendant parts, so requesting an allowlisted root itself (empty
relative path) returned it unchecked. A pre-existing scan-folder row under ~/.ssh,
~/.aws, ~/.config, etc. (registerable before the denylist was added) is re-added to
the allowlist on upgrade and could then be browsed. Check the resolved target once
before returning in both the legacy and Hub browsers, and cover the root case in
both test suites.

* fix: avoid unused path helper reexports

* fix: import sensitive path helpers directly

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <danielhanchen@gmail.com>
Co-authored-by: imagineer99 <samleejackson0@gmail.com>
Co-authored-by: Lee Jackson <130007945+Imagineer99@users.noreply.github.com>
2026-07-03 19:10:04 +01:00

100 lines
3.1 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""External media path helpers."""
from __future__ import annotations
import getpass
import os
import platform
from pathlib import Path
from utils.paths.sensitive import (
contains_sensitive_path_component,
is_sensitive_path_component,
)
def _is_linux_media_mount_path(path: str, media_root: Path | str) -> bool:
normalized = os.path.normpath(os.path.realpath(os.path.expanduser(path)))
root = os.path.normpath(os.path.realpath(os.path.expanduser(str(media_root))))
try:
rel = os.path.relpath(normalized, root)
except ValueError:
return False
if rel == "." or rel == ".." or rel.startswith(f"..{os.sep}"):
return False
parts = [part for part in rel.split(os.sep) if part]
return len(parts) >= 2 and all(part not in (".", "..") for part in parts[:2])
def is_linux_run_media_path(path: str) -> bool:
"""True for Linux removable-media paths under /run/media/<user>/<volume>."""
if platform.system() != "Linux":
return False
return _is_linux_media_mount_path(path, "/run/media")
def _current_username() -> str | None:
try:
user = getpass.getuser().strip()
except Exception:
return None
return user or None
def _contains_sensitive_media_component(path: Path, media_root: Path) -> bool:
try:
rel = path.relative_to(media_root)
except ValueError:
rel = path
return contains_sensitive_path_component(str(rel))
def linux_run_media_mount_roots(
base: Path | str = "/run/media", *, user: str | None = None
) -> list[Path]:
"""Readable /run/media/<user>/<volume> roots for the folder browser."""
if platform.system() != "Linux":
return []
user = user or _current_username()
if not user or user in (".", "..") or os.sep in user:
return []
base_path = Path(base)
try:
resolved_base = base_path.resolve()
except (OSError, RuntimeError, ValueError):
return []
roots: list[Path] = []
seen: set[str] = set()
user_dir = base_path / user
try:
if not user_dir.is_dir():
return []
volume_dirs = list(user_dir.iterdir())
except (OSError, RuntimeError, ValueError):
return []
for volume_dir in volume_dirs:
if is_sensitive_path_component(volume_dir.name):
continue
try:
resolved = volume_dir.resolve()
except (OSError, RuntimeError, ValueError):
continue
if not _is_linux_media_mount_path(str(resolved), resolved_base):
continue
if _contains_sensitive_media_component(resolved, resolved_base):
continue
key = os.path.normcase(os.path.realpath(str(resolved)))
if key in seen:
continue
try:
is_dir = resolved.is_dir()
except OSError:
continue
if is_dir and os.access(resolved, os.R_OK | os.X_OK):
seen.add(key)
roots.append(resolved)
return roots