bridge.utils.safe_pickle#

Module Contents#

Classes#

_RestrictedUnpickler

Unpickler that only allows safe built-in types to prevent arbitrary code execution.

_NumpyRestrictedUnpickler

Unpickler that allows safe builtins and the narrow set of numpy types needed for object array reconstruction.

Functions#

safe_pickle_load

Deserialize from a file using a restricted unpickler that only allows safe types.

safe_pickle_loads

Deserialize pickle data using a restricted unpickler that only allows safe types.

safe_load_npy

Load a .npy file from raw bytes without enabling unrestricted pickle.

Data#

API#

bridge.utils.safe_pickle._BUILTIN_SAFE_TYPES#

‘frozenset(…)’

class bridge.utils.safe_pickle._RestrictedUnpickler#

Bases: pickle.Unpickler

Unpickler that only allows safe built-in types to prevent arbitrary code execution.

Initialization

Initialize self. See help(type(self)) for accurate signature.

_SAFE_MODULES#

‘MappingProxyType(…)’

find_class(module: str, name: str) type#
class bridge.utils.safe_pickle._NumpyRestrictedUnpickler#

Bases: pickle.Unpickler

Unpickler that allows safe builtins and the narrow set of numpy types needed for object array reconstruction.

NumPy object arrays (dtype=’O’) are serialized via pickle inside .npy files. The pickle stream references numpy.core.multiarray._reconstruct, numpy.ndarray, and numpy.dtype to rebuild the array container, while the elements (dicts, lists, ints, …) use only standard builtins.

This unpickler permits exactly those types and nothing else — in particular, os, subprocess, builtins.eval, etc. are blocked, preventing arbitrary-code-execution attacks via crafted .npy files.

Initialization

Initialize self. See help(type(self)) for accurate signature.

_SAFE_MODULES#

‘MappingProxyType(…)’

find_class(module: str, name: str) type#
bridge.utils.safe_pickle.safe_pickle_load(fp) object#

Deserialize from a file using a restricted unpickler that only allows safe types.

bridge.utils.safe_pickle.safe_pickle_loads(data: bytes) object#

Deserialize pickle data using a restricted unpickler that only allows safe types.

bridge.utils.safe_pickle.safe_load_npy(data: bytes)#

Load a .npy file from raw bytes without enabling unrestricted pickle.

For numeric arrays the fast allow_pickle=False path is used. For object arrays (packed datasets storing dicts of variable-length lists) the pickle payload is deserialized through :class:_NumpyRestrictedUnpickler, which blocks dangerous modules like os and subprocess.

Parameters:

data – Raw bytes of a .npy file.

Returns:

numpy.ndarray loaded from the file.