ensure_within_root (paths)

ClawTeam-OpenClaw · dev-tools, path-traversal-protection, path-validation, sandbox, files

Joins path parts under a root directory and rejects any resulting path that escapes outside the root, ensuring safe file access.

def ensure_within_root(root: Path, *parts: str) -> Path:
    """Join *parts* under *root* and reject escapes outside the root."""
    base = root.resolve()
    candidate = root.joinpath(*parts)
    resolved = candidate.resolve(strict=False)
    try:
        resolved.relative_to(base)
    except ValueError as exc:
        raise ValueError("Resolved path escapes the configured data directory") from exc
    return candidate

See the full source, get the GitHub permalink, and search 40K more like it.

Get a free API key