diff --git a/src/google/adk/sessions/_restricted_pickle.py b/src/google/adk/sessions/_restricted_pickle.py index 5dcaae39e0f..24c60125551 100644 --- a/src/google/adk/sessions/_restricted_pickle.py +++ b/src/google/adk/sessions/_restricted_pickle.py @@ -163,9 +163,11 @@ def _allowed_globals() -> frozenset[tuple[str, str]]: return _STATIC_ALLOWED_GLOBALS | frozenset(derived) -class _RestrictedUnpickler(pickle.Unpickler): +class _RestrictedUnpickler(pickle._Unpickler): """Unpickler that only resolves the types `EventActions` can hold.""" + dispatch = pickle._Unpickler.dispatch.copy() + def find_class(self, module: str, name: str) -> Any: # noqa: ANN001 if (module, name) in _allowed_globals(): return super().find_class(module, name) @@ -179,6 +181,17 @@ def find_class(self, module: str, name: str) -> Any: # noqa: ANN001 " off the pickled schema." ) + def load_build(self) -> None: + if len(self.stack) >= 2 and isinstance(self.stack[-2], type): + target = self.stack[-2] + raise pickle.UnpicklingError( + f"Refusing to apply BUILD to class {target.__module__}." + f"{target.__qualname__} from a legacy pickled `events.actions` value." + ) + super().load_build() + + dispatch[pickle.BUILD[0]] = load_build + def loads(data: bytes | bytearray) -> Any: """Loads a pickle payload using the restricted unpickler.""" diff --git a/tests/unittests/sessions/test_dynamic_pickle_type.py b/tests/unittests/sessions/test_dynamic_pickle_type.py index 3742566c1cd..08aec76401d 100644 --- a/tests/unittests/sessions/test_dynamic_pickle_type.py +++ b/tests/unittests/sessions/test_dynamic_pickle_type.py @@ -688,3 +688,24 @@ def test_defaultdict_factory_must_itself_be_allowlisted(): """A `defaultdict` carries a callable, which the allowlist must cover too.""" with pytest.raises(pickle.UnpicklingError): _restricted_pickle.loads(pickle.dumps(collections.defaultdict(os.system))) + + +def test_build_opcode_cannot_mutate_allowlisted_class_attributes(): + """A crafted BUILD opcode targeting an allowlisted class must be refused.""" + # Protocol 4 payload: push pathlib.PurePosixPath onto the stack, then push + # (None, {"is_absolute": int}) and apply BUILD ('b') directly to the class. + payload = ( + b"\x80\x04" + b"\x8c\x07pathlib\x8c\rPurePosixPath\x93" + b"N}" + b"\x8c\x0bis_absolute\x8c\x08builtins\x8c\x03int\x93s" + b"\x86b." + ) + original_is_absolute = pathlib.PurePosixPath.is_absolute + + with pytest.raises(pickle.UnpicklingError, match="Refusing to apply BUILD"): + _restricted_pickle.loads(payload) + + assert pathlib.PurePosixPath.is_absolute is original_is_absolute + assert not pathlib.PurePosixPath("relative/path.txt").is_absolute() +