web_server_files.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. """Managed-files policy for the dashboard file browser: root resolution, path containment, entry metadata.
  2. """
  3. import logging
  4. import mimetypes
  5. import os
  6. import re
  7. import stat
  8. import urllib.request
  9. from contextlib import contextmanager
  10. from dataclasses import dataclass
  11. from fastapi import HTTPException, Request
  12. from pathlib import Path
  13. from typing import Any, Dict, Iterator, Optional
  14. logger = logging.getLogger(__name__)
  15. _MANAGED_FILES_ROOT_ENV = "HERMES_DASHBOARD_FILES_ROOT"
  16. _HOSTED_MANAGED_FILES_ROOT = Path("/opt/data")
  17. @dataclass(frozen=True)
  18. class ManagedFilesPolicy:
  19. default_path: Path
  20. locked_root: Path | None
  21. can_change_path: bool
  22. def _resolve_fs_candidate(raw: str, *, cwd: str | None = None) -> Path:
  23. candidate = Path(raw).expanduser()
  24. if not candidate.is_absolute():
  25. base = Path(cwd).expanduser() if cwd is not None else Path.cwd()
  26. if not base.is_absolute():
  27. raise HTTPException(status_code=400, detail="Session working directory is unavailable")
  28. candidate = base / candidate
  29. return candidate.resolve(strict=False)
  30. def _decoded_candidate(raw: str, *, cwd: str | None = None) -> Path | None:
  31. """``raw`` percent-decoded once and resolved, or None when decoding adds a dot-segment.
  32. The decode rescues a name that arrived encoded twice (issue #103425). A ``.`` or ``..`` it
  33. produces (``..%2f``, ``%2e%2e/``) would move the lookup out of the folder the caller named."""
  34. decoded = urllib.parse.unquote(raw)
  35. separators = r"[\\/]" if os.name == "nt" else "/"
  36. def dot_segments(path: str) -> int:
  37. return sum(segment in (".", "..") for segment in re.split(separators, path))
  38. if dot_segments(decoded) > dot_segments(raw):
  39. return None
  40. return _resolve_fs_candidate(decoded, cwd=cwd)
  41. def _file_url_path(url: str) -> str:
  42. """The native path a ``file:`` URL names, percent-decoded once.
  43. A URL that encodes a separator is refused (ValueError) as ``apps/shared/src/file-url.ts``
  44. refuses it in the renderer and Electron: ``%2f``, and ``%5c`` on a Windows gateway or in a
  45. Windows URL (a UNC host or a drive letter). Decoding it would add a segment, so ``..%2f`` would
  46. name a file outside the folder the URL spells.
  47. """
  48. parsed = urllib.parse.urlparse(url)
  49. uri_path = parsed.path
  50. host = "" if parsed.netloc.lower() == "localhost" else parsed.netloc
  51. drive = re.match(r"/[a-z]:", urllib.parse.unquote(uri_path), re.IGNORECASE)
  52. windows = os.name == "nt" or bool(host) or drive is not None
  53. if re.search(r"%2f", uri_path, re.IGNORECASE) or (windows and re.search(r"%5c", uri_path, re.IGNORECASE)):
  54. raise ValueError("file: URL encodes a path separator")
  55. if host:
  56. if os.name != "nt":
  57. raise ValueError("file: URL names another host")
  58. uri_path = f"//{host}{uri_path}"
  59. return urllib.request.url2pathname(uri_path)
  60. def _fs_path(raw_path: str, *, cwd: str | None = None, decode_fallback: bool = True) -> Path:
  61. raw = str(raw_path or "").strip()
  62. if not raw:
  63. raise HTTPException(status_code=400, detail="Path is required")
  64. if "\0" in raw:
  65. raise HTTPException(status_code=400, detail="Invalid path")
  66. try:
  67. from_url = raw.lower().startswith("file:")
  68. if from_url:
  69. raw = _file_url_path(raw)
  70. elif os.name == "nt":
  71. # MEDIA links can reuse Git Bash paths; native Path would read /c/ as C:\c\.
  72. from tools.environments.local import _msys_to_windows_path
  73. raw = _msys_to_windows_path(raw)
  74. candidate = _resolve_fs_candidate(raw, cwd=cwd)
  75. # A remote client hop may percent-encode a path on top of HTTP's own
  76. # decoding, so a non-ASCII name can arrive as a literal "%E5%8D%8A..."
  77. # string that stats as missing (issue #103425). The verbatim path wins
  78. # whenever it exists, so filenames that genuinely contain "%XX" keep
  79. # resolving as-is; the unquoted form only rescues the lookup. A file: URL
  80. # was decoded once above, and a second decode would read ..%252f as ../.
  81. if decode_fallback and not from_url and "%" in raw and not candidate.exists():
  82. decoded = _decoded_candidate(raw, cwd=cwd)
  83. if decoded is not None and decoded.exists():
  84. candidate = decoded
  85. return candidate
  86. except (OSError, RuntimeError, ValueError):
  87. raise HTTPException(status_code=400, detail="Invalid path")
  88. _WORKSPACE_KEY_RE = re.compile(r"^[0-9a-f]{16}$")
  89. def _session_workspace(session_id: str, cwd: str | None) -> tuple[str, str]:
  90. """``(digest, host cwd)`` of this session's per-workspace Docker sandbox, or ``("", "")``.
  91. The live override is the key the container was created under, and its cwd is the
  92. workspace the turn mounted. After that binding is gone, the session row's host cwd
  93. hashes to the same digest. ``/workspace`` and ``/root`` are container paths, not host
  94. workspaces. Call it in the session's profile scope, where the turn registered the key.
  95. """
  96. from tools.terminal_tool import resolve_task_overrides, workspace_key_for
  97. overrides = resolve_task_overrides(session_id)
  98. key = overrides.get("workspace_key")
  99. if isinstance(key, str) and _WORKSPACE_KEY_RE.fullmatch(key):
  100. bound = overrides.get("cwd")
  101. return key, bound if isinstance(bound, str) else ""
  102. host = (cwd or "").strip()
  103. if not host or "\0" in host or _is_container_cwd(host):
  104. return "", ""
  105. expanded = os.path.expanduser(host)
  106. if not os.path.isdir(expanded):
  107. return "", ""
  108. return workspace_key_for(expanded), expanded
  109. def _is_container_cwd(host: str) -> bool:
  110. return any(host == root or host.startswith(root + "/") for root in ("/workspace", "/root"))
  111. def _translate_agent_path(
  112. candidate: Path, workspace_key: str = "", own_sandbox_only: bool = False, workspace_cwd: str = "",
  113. ) -> Path | None:
  114. """One translation attempt under whatever scope is bound; None off the docker backend.
  115. The gate keeps a local-backend gateway with leftover ``docker_volumes`` from serving
  116. mount sources in place of real host files. Quiet: fs callers also see ordinary host
  117. paths, which are not MEDIA misses worth a warning. ``own_sandbox_only`` (a session's
  118. Save) refuses with 409 a file the translator found only in a fallback sandbox."""
  119. from gateway.platforms.base import _docker_env_active, _translate_docker_container_media_path
  120. from tools.terminal_tool import _ensure_terminal_env_bridged
  121. _ensure_terminal_env_bridged()
  122. if not _docker_env_active():
  123. return None
  124. translated = _translate_docker_container_media_path(
  125. candidate, quiet=True, workspace_key=workspace_key, workspace_cwd=workspace_cwd,
  126. )
  127. if own_sandbox_only and translated is not None and (
  128. _in_fallback_sandbox(translated, workspace_key) or _in_shared_cwd_mount_guess(translated, workspace_key)
  129. ):
  130. raise HTTPException(status_code=409, detail=SANDBOX_COPY_MISSING)
  131. return translated
  132. SANDBOX_COPY_MISSING = "File is no longer in this session's workspace"
  133. def _in_fallback_sandbox(target: Path, workspace_key: str) -> bool:
  134. """Whether *target* is in a Docker sandbox other than the session's own, the first in the
  135. translator's order (then the profile's shared ones). The session's own is that first name
  136. whether or not its directory exists: reads fall through to the shared copies when the session's
  137. file or its whole sandbox is gone, and a Save that did would change another sandbox's file."""
  138. from gateway.platforms.docker_media_paths import _docker_sandbox_dir_candidates
  139. from tools.environments.base import get_sandbox_dir
  140. base = get_sandbox_dir() / "docker"
  141. names = _docker_sandbox_dir_candidates("", workspace_key)
  142. fallbacks = [(base / name).resolve(strict=False) for name in names[1:]]
  143. return any(_path_is_under(sandbox, target) for sandbox in fallbacks)
  144. def _in_shared_cwd_mount_guess(target: Path, workspace_key: str) -> bool:
  145. """Whether *target* is in the cwd a shared container's ``/workspace`` is only assumed to mount:
  146. that container mounts its first session's cwd, which nothing records, so a Save there could
  147. change a file the agent never sees."""
  148. from gateway.platforms.docker_media_paths import _shared_cwd_mount_guess
  149. return any(_path_is_under(root, target) for root in _shared_cwd_mount_guess(workspace_key))
  150. @contextmanager
  151. def _agent_path_scope(profile_home: Path | None = None) -> Iterator[None]:
  152. """Bind the profile whose sandbox a container path names: its home and its terminal policy.
  153. A requested ``profile_home`` other than the current home binds that home and its complete
  154. terminal policy, as MEDIA delivery does (#109024). A home already bound by the caller (a
  155. native profile ticket's override) gets its own terminal policy when no scope is bound, so
  156. translation never reads the launch profile's ambient ``TERMINAL_DOCKER_VOLUMES``. An
  157. override naming the launch home keeps the ambient env, which may carry env-only policy.
  158. Translation and the unmapped-path classification both run inside this scope, so they
  159. agree about the backend.
  160. """
  161. from hermes_cli.config import get_hermes_home
  162. from hermes_constants import (
  163. get_hermes_home_override, get_process_hermes_home, reset_hermes_home_override,
  164. set_hermes_home_override,
  165. )
  166. from tools.terminal_scope import get_terminal_scope, install_profile_terminal_scope, reset_terminal_scope
  167. home_token = scope_token = None
  168. if profile_home is not None and Path(profile_home).resolve() != get_hermes_home().resolve():
  169. home_token = set_hermes_home_override(str(profile_home))
  170. try:
  171. foreign_override = (get_hermes_home_override() is not None
  172. and get_hermes_home().resolve() != get_process_hermes_home().resolve())
  173. if home_token is not None or (foreign_override and get_terminal_scope() is None):
  174. scope_token = install_profile_terminal_scope(get_hermes_home())
  175. yield
  176. finally:
  177. if scope_token is not None:
  178. reset_terminal_scope(scope_token)
  179. if home_token is not None:
  180. reset_hermes_home_override(home_token)
  181. def _agent_container_path(
  182. raw: str, *, profile_home: Path | None = None, workspace_key: str = "", own_sandbox_only: bool = False,
  183. workspace_cwd: str = "",
  184. ) -> Path | None:
  185. """Map an agent-visible container path to its host bind mount, or None.
  186. Docker agents emit container paths (``/workspace/...``, ``/root/...``) in
  187. transcripts and MEDIA tags, while the dashboard fs routes stat the gateway
  188. HOST filesystem (#85238). Reuse the gateway's MEDIA volume translator inside
  189. ``_agent_path_scope(profile_home)``. When no terminal scope is bound even
  190. then (``serve --isolated`` after a failed early bridge), retry once under the
  191. current profile's complete terminal policy, never replacing an already-bound
  192. scope or refusal (retry from #104992).
  193. Runs on the raw string, before host normalization: on a Windows gateway
  194. ``Path("/workspace/x").resolve()`` anchors to the current drive and the
  195. container path is gone before translation sees it. ``..`` segments are never
  196. translated, so the managed routes keep refusing them.
  197. """
  198. if not raw.startswith("/") or raw.startswith("//") or ".." in raw.split("/"):
  199. return None
  200. try:
  201. from hermes_cli.config import get_hermes_home
  202. from tools.terminal_scope import (
  203. build_profile_terminal_scope, get_terminal_scope, reset_terminal_scope, set_terminal_scope,
  204. )
  205. candidate = Path(raw)
  206. with _agent_path_scope(profile_home):
  207. translated = _translate_agent_path(candidate, workspace_key, own_sandbox_only, workspace_cwd)
  208. if translated is not None or get_terminal_scope() is not None:
  209. return translated
  210. token = set_terminal_scope(build_profile_terminal_scope(get_hermes_home()))
  211. try:
  212. return _translate_agent_path(candidate, workspace_key, own_sandbox_only, workspace_cwd)
  213. finally:
  214. reset_terminal_scope(token)
  215. except HTTPException:
  216. raise # a Save refused in a fallback sandbox
  217. except Exception: # fail open: translation is additive, the host path still serves
  218. logger.debug("agent container path translation failed for %s", raw, exc_info=True)
  219. return None
  220. SANDBOX_NOT_FOUND = "File not found on the gateway host: the path may live inside the agent sandbox"
  221. def _agent_fs_path(
  222. raw_path: str, *, cwd: str | None = None, profile_home: Path | None = None,
  223. workspace_key: str = "", decode_fallback: bool = True, own_sandbox_only: bool = False,
  224. workspace_cwd: str = "",
  225. ) -> Path:
  226. """``_fs_path`` for agent-facing reads; container paths resolve to their host
  227. mount, so callers' boundary guards see the real host target. A session's Save passes
  228. ``own_sandbox_only``: a container path stays in the session's own sandbox (else 409).
  229. ``workspace_cwd`` is the host cwd ``workspace_key`` hashes, the session's cwd mount.
  230. POSIX: a readable host path wins, and translation only runs when the host
  231. lookup misses, so a root-run gateway can still browse its own ``/root``.
  232. Windows: a container-shaped path never names a host file (it would anchor to
  233. the current drive), so a translation miss is a 404 rather than a drive lookup.
  234. """
  235. raw = str(raw_path or "").strip()
  236. if os.name != "nt":
  237. host = _fs_path(raw_path, cwd=cwd, decode_fallback=decode_fallback)
  238. if os.access(host, os.R_OK):
  239. return host
  240. translated = _agent_container_path(
  241. _file_url_container_text(raw), profile_home=profile_home, workspace_key=workspace_key,
  242. own_sandbox_only=own_sandbox_only, workspace_cwd=workspace_cwd,
  243. )
  244. return translated if translated is not None else host
  245. translated = _agent_container_path(
  246. raw, profile_home=profile_home, workspace_key=workspace_key, own_sandbox_only=own_sandbox_only,
  247. workspace_cwd=workspace_cwd,
  248. )
  249. if translated is not None:
  250. return translated
  251. if _is_unmapped_container_path(raw, profile_home=profile_home):
  252. raise HTTPException(status_code=404, detail=SANDBOX_NOT_FOUND)
  253. return _fs_path(raw_path, cwd=cwd, decode_fallback=decode_fallback)
  254. def _file_url_container_text(raw: str) -> str:
  255. """The path a POSIX gateway's ``file:`` URL names (``file:///workspace/x`` -> ``/workspace/x``),
  256. so a container path spelled as a URL translates like the bare path. Any other text, and every
  257. URL on a Windows gateway, is returned unchanged; ``_fs_path`` already refused a bad URL."""
  258. if os.name == "nt" or not raw.lower().startswith("file:"):
  259. return raw
  260. try:
  261. return _file_url_path(raw)
  262. except ValueError:
  263. return raw
  264. def _is_unmapped_container_path(raw: str, *, profile_home: Path | None = None) -> bool:
  265. """A docker-backend container path (``/workspace``, ``/root`` or a configured
  266. volume target) rather than a host path or a typo elsewhere on the host. Reads
  267. the backend and volumes in the same profile scope translation used."""
  268. if not raw.startswith("/") or raw.startswith("//"):
  269. return False
  270. try:
  271. from gateway.platforms.base import _docker_env_active, _parse_docker_volume_mounts
  272. from tools.environments.local import _msys_to_windows_path
  273. with _agent_path_scope(profile_home):
  274. if not _docker_env_active() or _msys_to_windows_path(raw) != raw:
  275. return False
  276. roots = {"/workspace", "/root", *(c.as_posix() for _, c in _parse_docker_volume_mounts())}
  277. except Exception: # a refusal scope or import failure: just skip the hint
  278. logger.debug("container path classification failed for %s", raw, exc_info=True)
  279. return False
  280. return any(raw == r or raw.startswith(r.rstrip("/") + "/") for r in roots)
  281. def _canonical_path(path: Path, *, require_exists: bool = False) -> Path:
  282. try:
  283. return path.expanduser().resolve(strict=require_exists)
  284. except FileNotFoundError:
  285. if require_exists:
  286. raise HTTPException(status_code=404, detail="Path not found")
  287. raise
  288. except (OSError, RuntimeError):
  289. raise HTTPException(status_code=400, detail="Invalid path")
  290. def _ensure_managed_root(raw_path: str | Path) -> Path:
  291. root = Path(raw_path).expanduser()
  292. try:
  293. root.mkdir(parents=True, exist_ok=True)
  294. resolved = root.resolve()
  295. except (OSError, RuntimeError) as exc:
  296. raise HTTPException(status_code=500, detail=f"Managed files root is unavailable: {exc}")
  297. if not resolved.is_dir():
  298. raise HTTPException(status_code=500, detail="Managed files root is not a directory")
  299. return resolved
  300. def _path_is_under(root: Path, target: Path) -> bool:
  301. return target == root or root in target.parents
  302. def _path_text(raw_path: str | None) -> str:
  303. text = str(raw_path or "").strip()
  304. if "\x00" in text:
  305. raise HTTPException(status_code=400, detail="Invalid path")
  306. return text
  307. def _default_hermes_root_is_opt_data() -> bool:
  308. raw = os.environ.get("HERMES_HOME", "").strip()
  309. if not raw:
  310. return False
  311. try:
  312. from hermes_constants import get_default_hermes_root
  313. root = get_default_hermes_root().expanduser().resolve(strict=False)
  314. except (OSError, RuntimeError):
  315. root = Path(raw).expanduser().resolve(strict=False)
  316. return root == _HOSTED_MANAGED_FILES_ROOT
  317. def _dashboard_local_update_managed_externally() -> bool:
  318. """True when the dashboard should not offer ``hermes update``.
  319. Containerized dashboards are updated by the outer launcher/image — except a
  320. ``git`` install (bind-mounted checkout, e.g. the hermes-webui image), where
  321. the update button is the correct path. pip stays blocked in containers: its
  322. apply path mutates the running container filesystem.
  323. """
  324. from hermes_cli.web_server import PROJECT_ROOT
  325. from hermes_cli.config import detect_install_method
  326. if _default_hermes_root_is_opt_data():
  327. return True
  328. try:
  329. from hermes_constants import is_container
  330. if not is_container():
  331. return False
  332. except Exception:
  333. return False
  334. try:
  335. if detect_install_method(PROJECT_ROOT) == "git":
  336. return False
  337. except Exception:
  338. pass
  339. return True
  340. def _managed_files_policy(request: Optional[Request], *, create_root: bool = True) -> ManagedFilesPolicy:
  341. raw_forced_root = os.environ.get(_MANAGED_FILES_ROOT_ENV, "").strip()
  342. if raw_forced_root:
  343. root = _ensure_managed_root(raw_forced_root) if create_root else _canonical_path(Path(raw_forced_root))
  344. return ManagedFilesPolicy(default_path=root, locked_root=root, can_change_path=False)
  345. # Remote/OAuth access does not imply a hosted container (a gated macOS launchd
  346. # install still browses its home). Lock to /opt/data only when the Hermes
  347. # root actually IS /opt/data or HERMES_DASHBOARD_FILES_ROOT is set.
  348. if _default_hermes_root_is_opt_data():
  349. root = _ensure_managed_root(_HOSTED_MANAGED_FILES_ROOT) if create_root else _HOSTED_MANAGED_FILES_ROOT
  350. return ManagedFilesPolicy(default_path=root, locked_root=root, can_change_path=False)
  351. home = _canonical_path(Path.home())
  352. return ManagedFilesPolicy(default_path=home, locked_root=None, can_change_path=True)
  353. def _resolve_managed_path(
  354. raw_path: str | None, request: Request, *, for_write: bool = False, create_root: bool = True,
  355. for_agent_read: bool = False,
  356. ) -> tuple[ManagedFilesPolicy, Path, str]:
  357. policy = _managed_files_policy(request, create_root=create_root)
  358. text = _path_text(raw_path)
  359. root = policy.locked_root
  360. if for_agent_read and text and not text.startswith("file:") and (
  361. os.name == "nt" or not os.access(text, os.R_OK)):
  362. # Agent-emitted container paths (/workspace/...) resolve to their host
  363. # bind mount before the root checks, so the locked-root refusal below
  364. # still governs the translated target (#85238). A readable host path wins.
  365. translated = _agent_container_path(text)
  366. if translated is not None:
  367. text = str(translated)
  368. if root is not None and (not text or text in {".", "/"}):
  369. candidate = root
  370. elif not text:
  371. candidate = policy.default_path
  372. else:
  373. candidate = Path(text).expanduser()
  374. if root is not None and not candidate.is_absolute():
  375. if any(part == ".." for part in candidate.parts):
  376. raise HTTPException(status_code=400, detail="Path cannot contain '..'")
  377. candidate = root / candidate
  378. elif not candidate.is_absolute():
  379. raise HTTPException(status_code=400, detail="Path must be absolute")
  380. if ".." in candidate.parts:
  381. raise HTTPException(status_code=400, detail="Path cannot contain '..'")
  382. if for_write and not candidate.exists():
  383. parent = _canonical_path(candidate.parent)
  384. resolved = parent / candidate.name
  385. else:
  386. resolved = _canonical_path(candidate, require_exists=not for_write)
  387. if root is not None and not _path_is_under(root, resolved):
  388. raise HTTPException(status_code=403, detail="Path outside managed files root")
  389. return policy, resolved, str(resolved)
  390. def _managed_response_meta(policy: ManagedFilesPolicy) -> dict[str, Any]:
  391. locked_root = str(policy.locked_root) if policy.locked_root is not None else None
  392. return {"root": locked_root, "locked_root": locked_root, "can_change_path": policy.can_change_path}
  393. def _hosted_fs_path_allowed(root: Path, target: Path) -> bool:
  394. from hermes_cli.web_routers.files import _is_sensitive_path
  395. resolved = _canonical_path(target)
  396. return (_path_is_under(root, resolved)
  397. and not _is_sensitive_path(target) and not _is_sensitive_path(resolved))
  398. def _hosted_fs_read_guard(target: Path, request: Optional[Request] = None) -> Path | None:
  399. """Preview and Git reads share managed-file restrictions on locked deployments.
  400. ``request`` is unused (the policy is env/home driven) and optional so the
  401. route functions stay callable directly, e.g. from agent-side tests.
  402. """
  403. root = _managed_files_policy(request, create_root=False).locked_root
  404. if root is not None and not _hosted_fs_path_allowed(root, target):
  405. raise HTTPException(status_code=403, detail="Path is outside the managed read boundary")
  406. return root
  407. def _managed_file_entry(
  408. policy: ManagedFilesPolicy, target: Path, *, skip_missing: bool = False
  409. ) -> dict[str, Any] | None:
  410. """Describe an entry; listings may skip vanished files, while writes stay strict."""
  411. try:
  412. resolved = target.resolve()
  413. except (OSError, RuntimeError):
  414. raise HTTPException(status_code=400, detail="Invalid path")
  415. # A dangling symlink is still a directory entry even when its missing
  416. # target resolves outside the managed root. Classify only a definite
  417. # missing target before checking the resolved-target boundary so one safe
  418. # placeholder does not abort the whole listing. Permission and other I/O
  419. # errors still pass through the existing boundary/error handling below.
  420. st = None
  421. if target.is_symlink():
  422. try:
  423. st = resolved.stat()
  424. except FileNotFoundError:
  425. # A placeholder may describe only an entry inside the managed root,
  426. # even when the missing destination is outside it.
  427. if policy.locked_root is not None and not _path_is_under(
  428. policy.locked_root, target.parent.resolve() / target.name
  429. ):
  430. raise HTTPException(status_code=403, detail="Path outside managed files root")
  431. return {
  432. "name": target.name or resolved.name or str(resolved),
  433. "path": str(target),
  434. "is_directory": False,
  435. "broken_link": True,
  436. "size": None,
  437. "mtime": None,
  438. "mime_type": None,
  439. }
  440. except OSError:
  441. pass
  442. if policy.locked_root is not None and not _path_is_under(policy.locked_root, resolved):
  443. raise HTTPException(status_code=403, detail="Path outside managed files root")
  444. if st is None:
  445. try:
  446. st = resolved.stat()
  447. except FileNotFoundError as exc:
  448. if skip_missing:
  449. return None
  450. raise HTTPException(status_code=500, detail=f"Could not stat path: {exc}")
  451. except OSError as exc:
  452. raise HTTPException(status_code=500, detail=f"Could not stat path: {exc}")
  453. is_dir = stat.S_ISDIR(st.st_mode)
  454. mime_type = None if is_dir else (mimetypes.guess_type(resolved.name)[0] or "application/octet-stream")
  455. return {
  456. "name": target.name or resolved.name or str(resolved),
  457. "path": str(resolved),
  458. "is_directory": is_dir,
  459. "size": None if is_dir else st.st_size,
  460. "mtime": st.st_mtime,
  461. "mime_type": mime_type,
  462. }