Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/google/adk/sessions/_restricted_pickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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."""
Expand Down
21 changes: 21 additions & 0 deletions tests/unittests/sessions/test_dynamic_pickle_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()