Skip to content

Paths & safety

Path traversal guards and untrusted-pack warnings (W10).

resolve_under

resolve_under(
    root: Path | str,
    user_path: Path | str,
    *,
    must_exist: bool = False,
) -> Path

Resolve user_path and require it stays under root.

Relative paths are joined to root. Absolute paths must still resolve inside root after Path.resolve().

Source code in bnn/paths.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def resolve_under(root: Path | str, user_path: Path | str, *, must_exist: bool = False) -> Path:
    """Resolve ``user_path`` and require it stays under ``root``.

    Relative paths are joined to ``root``. Absolute paths must still resolve
    inside ``root`` after ``Path.resolve()``.
    """
    root_r = Path(root).resolve()
    p = Path(user_path)
    candidate = (root_r / p).resolve() if not p.is_absolute() else p.resolve()
    try:
        candidate.relative_to(root_r)
    except ValueError as exc:
        raise PathSecurityError(
            f"Path {user_path!s} escapes allowed root {root_r}"
        ) from exc
    if must_exist and not candidate.exists():
        raise FileNotFoundError(candidate)
    return candidate

PathSecurityError

Bases: ValueError

Raised when a user path escapes an allowed root.

Source code in bnn/paths.py
15
16
class PathSecurityError(ValueError):
    """Raised when a user path escapes an allowed root."""

data_path

data_path(*parts: str, create: bool = False) -> Path

Return a path under <repo>/data (created optionally).

Source code in bnn/paths.py
39
40
41
42
43
44
45
46
def data_path(*parts: str, create: bool = False) -> Path:
    """Return a path under ``<repo>/data`` (created optionally)."""
    base = REPO_ROOT / "data"
    if create:
        base.mkdir(parents=True, exist_ok=True)
    if not parts:
        return base
    return resolve_under(base, Path(*parts))

results_path

results_path(*parts: str) -> Path

Return a path under <repo>/results.

Source code in bnn/paths.py
49
50
51
52
53
54
def results_path(*parts: str) -> Path:
    """Return a path under ``<repo>/results``."""
    base = REPO_ROOT / "results"
    if not parts:
        return base
    return resolve_under(base, Path(*parts))

repo_relative

repo_relative(path: Path | str) -> str

Path as a POSIX string relative to the repo root, for committed JSON.

Committed results are read on other people's machines and diffed across them, so an absolute path is both non-portable and a needless disclosure of the author's home directory. Falls back to the bare filename when the path lies outside the repo.

Source code in bnn/paths.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def repo_relative(path: Path | str) -> str:
    """Path as a POSIX string relative to the repo root, for committed JSON.

    Committed results are read on other people's machines and diffed across
    them, so an absolute path is both non-portable and a needless disclosure of
    the author's home directory. Falls back to the bare filename when the path
    lies outside the repo.
    """
    p = Path(path)
    try:
        resolved = p.resolve()
    except OSError:
        return p.name
    try:
        return resolved.relative_to(REPO_ROOT).as_posix()
    except ValueError:
        return p.name

is_under_repo_trusted_pack_root

is_under_repo_trusted_pack_root(path: Path | str) -> bool

True when path resolves under repo results/, checkpoints/, or data/.

Source code in bnn/paths.py
76
77
78
79
80
81
82
83
84
def is_under_repo_trusted_pack_root(path: Path | str) -> bool:
    """True when ``path`` resolves under repo ``results/``, ``checkpoints/``, or ``data/``."""
    try:
        resolved = Path(path).resolve()
        rel = resolved.relative_to(REPO_ROOT.resolve())
    except (OSError, ValueError):
        return False
    parts = rel.parts
    return bool(parts) and parts[0] in _TRUSTED_PACK_ROOTS

warn_untrusted_pack

warn_untrusted_pack(
    path: Path | str, *, kind: str = ".bnnpack"
) -> bool

Emit a soft warning when loading a pack/checkpoint from outside lab roots.

Returns True if a warning was emitted. Does not block the load — load_bnnpack still enforces weights_only=True (no pickle fallback).

Source code in bnn/paths.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def warn_untrusted_pack(path: Path | str, *, kind: str = ".bnnpack") -> bool:
    """Emit a soft warning when loading a pack/checkpoint from outside lab roots.

    Returns True if a warning was emitted. Does **not** block the load —
    ``load_bnnpack`` still enforces ``weights_only=True`` (no pickle fallback).
    """
    p = Path(path)
    if is_under_repo_trusted_pack_root(p):
        return False
    warn(
        f"loading {kind} from outside lab results/checkpoints/data — "
        "treat as untrusted; refuse files you did not produce",
        path=str(p),
    )
    return True

save_checkpoint

save_checkpoint(
    model: Module,
    path: Path | str,
    *,
    meta: dict[str, Any] | None = None,
) -> Path
Source code in bnn/export.py
22
23
24
25
26
27
28
29
30
31
def save_checkpoint(
    model: nn.Module,
    path: Path | str,
    *,
    meta: dict[str, Any] | None = None,
) -> Path:
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    torch.save({"state_dict": model.state_dict(), "meta": meta or {}}, path)
    return path

load_checkpoint

load_checkpoint(
    model: Module,
    path: Path | str,
    *,
    map_location: str | device = "cpu",
) -> dict[str, Any]
Source code in bnn/export.py
49
50
51
52
53
54
55
56
57
58
59
60
def load_checkpoint(
    model: nn.Module,
    path: Path | str,
    *,
    map_location: str | torch.device = "cpu",
) -> dict[str, Any]:
    payload = _torch_load(Path(path), map_location=map_location)
    if not isinstance(payload, dict) or "state_dict" not in payload:
        raise ValueError(f"Checkpoint {path} missing state_dict")
    model.load_state_dict(payload["state_dict"])
    meta = payload.get("meta", {})
    return meta if isinstance(meta, dict) else {}