MCPcopy Create free account
hub / github.com/Graphify-Labs/graphify / validate_graph_path

Function validate_graph_path

graphify/security.py:330–369  ·  view source on GitHub ↗

Resolve *path* and verify it stays inside *base*. *base* defaults to the `graphify-out` directory relative to CWD. Also requires the base directory to exist, so a caller cannot trick graphify into reading files before any graph has been built. Raises: ValueError - path esc

(path: str | Path, base: Path | None = None)

Source from the content-addressed store, hash-verified

328# ---------------------------------------------------------------------------
329
330def validate_graph_path(path: str | Path, base: Path | None = None) -> Path:
331 """Resolve *path* and verify it stays inside *base*.
332
333 *base* defaults to the `graphify-out` directory relative to CWD.
334 Also requires the base directory to exist, so a caller cannot
335 trick graphify into reading files before any graph has been built.
336
337 Raises:
338 ValueError - path escapes base, or base does not exist
339 FileNotFoundError - resolved path does not exist
340 """
341 if base is None:
342 resolved_hint = Path(path).resolve()
343 for candidate in [resolved_hint, *resolved_hint.parents]:
344 if candidate.name == GRAPHIFY_OUT_NAME:
345 base = candidate
346 break
347 if base is None:
348 base = Path(GRAPHIFY_OUT).resolve()
349
350 base = base.resolve()
351 if not base.exists():
352 raise ValueError(
353 f"Graph base directory does not exist: {base}. "
354 "Run /graphify first to build the graph."
355 )
356
357 resolved = Path(path).resolve()
358 try:
359 resolved.relative_to(base)
360 except ValueError:
361 raise ValueError(
362 f"Path {path!r} escapes the allowed directory {base}. "
363 "Only paths inside graphify-out/ are permitted."
364 )
365
366 if not resolved.exists():
367 raise FileNotFoundError(f"Graph file not found: {resolved}")
368
369 return resolved
370
371
372def check_graph_file_size_cap(path: Path) -> None:

Calls 1

resolveMethod · 0.45