|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import gzip |
| 4 | +import json |
| 5 | +import os |
| 6 | +import pickle |
| 7 | +from pathlib import Path |
| 8 | +from typing import Any, Iterable |
| 9 | + |
| 10 | + |
| 11 | +class DeserializationSecurityError(RuntimeError): |
| 12 | + """Raised when deserialization is blocked by policy.""" |
| 13 | + |
| 14 | + |
| 15 | +_ALLOW_UNSAFE_ENV = "CATPRED_ALLOW_UNSAFE_DESERIALIZATION" |
| 16 | +_TRUSTED_ROOTS_ENV = "CATPRED_TRUSTED_DESERIALIZATION_ROOTS" |
| 17 | + |
| 18 | + |
| 19 | +def _env_flag(name: str, default: bool = False) -> bool: |
| 20 | + raw = os.environ.get(name) |
| 21 | + if raw is None: |
| 22 | + return default |
| 23 | + return raw.strip().lower() in {"1", "true", "yes", "y", "on"} |
| 24 | + |
| 25 | + |
| 26 | +def _dedupe_paths(paths: list[Path]) -> list[Path]: |
| 27 | + unique: list[Path] = [] |
| 28 | + seen = set() |
| 29 | + for path in paths: |
| 30 | + resolved = path.resolve() |
| 31 | + key = str(resolved) |
| 32 | + if key not in seen: |
| 33 | + unique.append(resolved) |
| 34 | + seen.add(key) |
| 35 | + return unique |
| 36 | + |
| 37 | + |
| 38 | +def _default_trusted_roots() -> list[Path]: |
| 39 | + raw = os.environ.get(_TRUSTED_ROOTS_ENV) |
| 40 | + if raw: |
| 41 | + candidates = [Path(item) for item in raw.split(os.pathsep) if item.strip()] |
| 42 | + else: |
| 43 | + cwd = Path.cwd().resolve() |
| 44 | + candidates = [cwd, cwd.parent] |
| 45 | + return _dedupe_paths(candidates) |
| 46 | + |
| 47 | + |
| 48 | +def trusted_roots(extra_roots: Iterable[str | Path] | None = None) -> list[Path]: |
| 49 | + roots = _default_trusted_roots() |
| 50 | + if extra_roots: |
| 51 | + roots.extend(Path(path) for path in extra_roots) |
| 52 | + return _dedupe_paths(roots) |
| 53 | + |
| 54 | + |
| 55 | +def is_trusted_path(path: str | Path, roots: Iterable[str | Path] | None = None) -> bool: |
| 56 | + resolved = Path(path).resolve() |
| 57 | + candidate_roots = trusted_roots(roots) |
| 58 | + for root in candidate_roots: |
| 59 | + try: |
| 60 | + resolved.relative_to(root) |
| 61 | + return True |
| 62 | + except ValueError: |
| 63 | + continue |
| 64 | + return False |
| 65 | + |
| 66 | + |
| 67 | +def ensure_trusted_path( |
| 68 | + path: str | Path, |
| 69 | + *, |
| 70 | + purpose: str, |
| 71 | + roots: Iterable[str | Path] | None = None, |
| 72 | +) -> Path: |
| 73 | + resolved = Path(path).resolve() |
| 74 | + candidate_roots = trusted_roots(roots) |
| 75 | + if is_trusted_path(resolved, candidate_roots): |
| 76 | + return resolved |
| 77 | + roots_display = ", ".join(str(item) for item in candidate_roots) |
| 78 | + raise DeserializationSecurityError( |
| 79 | + f'Refusing to load untrusted {purpose} from "{resolved}". ' |
| 80 | + f"Allowed roots: {roots_display}. " |
| 81 | + f"Use {_TRUSTED_ROOTS_ENV} to expand trusted roots." |
| 82 | + ) |
| 83 | + |
| 84 | + |
| 85 | +def unsafe_deserialization_enabled(default: bool = True) -> bool: |
| 86 | + return _env_flag(_ALLOW_UNSAFE_ENV, default=default) |
| 87 | + |
| 88 | + |
| 89 | +def load_pickle_artifact( |
| 90 | + path: str | Path, |
| 91 | + *, |
| 92 | + purpose: str, |
| 93 | + roots: Iterable[str | Path] | None = None, |
| 94 | + allow_unsafe: bool | None = None, |
| 95 | + encoding: str | None = None, |
| 96 | +) -> Any: |
| 97 | + resolved = ensure_trusted_path(path, purpose=purpose, roots=roots) |
| 98 | + unsafe = unsafe_deserialization_enabled() if allow_unsafe is None else allow_unsafe |
| 99 | + if not unsafe: |
| 100 | + raise DeserializationSecurityError( |
| 101 | + f"Pickle deserialization is disabled for {purpose}. " |
| 102 | + f"Set {_ALLOW_UNSAFE_ENV}=1 only for trusted artifacts." |
| 103 | + ) |
| 104 | + |
| 105 | + with resolved.open("rb") as handle: |
| 106 | + if encoding is None: |
| 107 | + try: |
| 108 | + return pickle.load(handle) |
| 109 | + except UnicodeDecodeError: |
| 110 | + handle.seek(0) |
| 111 | + return pickle.load(handle, encoding="latin1") |
| 112 | + return pickle.load(handle, encoding=encoding) |
| 113 | + |
| 114 | + |
| 115 | +def load_index_artifact( |
| 116 | + path: str | Path, |
| 117 | + *, |
| 118 | + purpose: str, |
| 119 | + roots: Iterable[str | Path] | None = None, |
| 120 | + allow_unsafe: bool | None = None, |
| 121 | +) -> Any: |
| 122 | + resolved = ensure_trusted_path(path, purpose=purpose, roots=roots) |
| 123 | + suffixes = tuple(s.lower() for s in resolved.suffixes) |
| 124 | + if suffixes and suffixes[-1] == ".json": |
| 125 | + with resolved.open("rt", encoding="utf-8") as handle: |
| 126 | + return json.load(handle) |
| 127 | + if suffixes[-2:] == (".json", ".gz"): |
| 128 | + with gzip.open(resolved, "rt", encoding="utf-8") as handle: |
| 129 | + return json.load(handle) |
| 130 | + return load_pickle_artifact( |
| 131 | + resolved, |
| 132 | + purpose=purpose, |
| 133 | + roots=roots, |
| 134 | + allow_unsafe=allow_unsafe, |
| 135 | + ) |
| 136 | + |
| 137 | + |
| 138 | +def load_torch_artifact( |
| 139 | + path: str | Path, |
| 140 | + *, |
| 141 | + purpose: str, |
| 142 | + map_location=None, |
| 143 | + roots: Iterable[str | Path] | None = None, |
| 144 | + allow_unsafe: bool | None = None, |
| 145 | +) -> Any: |
| 146 | + resolved = ensure_trusted_path(path, purpose=purpose, roots=roots) |
| 147 | + unsafe = unsafe_deserialization_enabled() if allow_unsafe is None else allow_unsafe |
| 148 | + |
| 149 | + import torch |
| 150 | + |
| 151 | + if unsafe: |
| 152 | + try: |
| 153 | + return torch.load(str(resolved), map_location=map_location, weights_only=False) |
| 154 | + except TypeError: |
| 155 | + return torch.load(str(resolved), map_location=map_location) |
| 156 | + |
| 157 | + try: |
| 158 | + return torch.load(str(resolved), map_location=map_location, weights_only=True) |
| 159 | + except TypeError as exc: |
| 160 | + raise DeserializationSecurityError( |
| 161 | + "Safe torch deserialization requires a torch version that supports weights_only loading. " |
| 162 | + f"Set {_ALLOW_UNSAFE_ENV}=1 for trusted legacy checkpoints." |
| 163 | + ) from exc |
| 164 | + except Exception as exc: |
| 165 | + raise DeserializationSecurityError( |
| 166 | + f"Safe torch deserialization rejected {purpose}. " |
| 167 | + f"If this checkpoint is trusted, set {_ALLOW_UNSAFE_ENV}=1." |
| 168 | + ) from exc |
0 commit comments