diff --git a/sdk/python/agentic/langgraph.py b/sdk/python/agentic/langgraph.py index 9e919368..8eb782ff 100644 --- a/sdk/python/agentic/langgraph.py +++ b/sdk/python/agentic/langgraph.py @@ -91,7 +91,9 @@ def __init__( super().__init__() self.client = client or AgenticClient.default() self.repo = Path(repo) - self.serde = JsonPlusSerializer() + # Strict: checkpoints are on-disk, branch-writable input, so only + # langgraph's built-in safe types may be reconstructed from msgpack. + self.serde = JsonPlusSerializer(allowed_msgpack_modules=None) # ------------------------------------------------------------------ put @@ -105,7 +107,9 @@ def put( thread_id = _require_thread_id(config) branch = _branch_for_thread(thread_id) - envelope = _serialise_envelope(cast(JsonPlusSerializer, self.serde), checkpoint, metadata, thread_id) + envelope = _serialise_envelope( + cast(JsonPlusSerializer, self.serde), checkpoint, metadata, thread_id + ) blob_path = _checkpoint_blob_path(thread_id) envelope_json = json.dumps(envelope, separators=(",", ":")) @@ -349,6 +353,17 @@ def _serialise_envelope( } +# The only ``type`` tags ``JsonPlusSerializer.dumps_typed`` emits without +# ``pickle_fallback``. Anything else (``pickle``, ``json``) is attacker-chosen. +_ALLOWED_ENVELOPE_TYPES = frozenset({"msgpack", "null", "bytes", "bytearray"}) + + +def _loads_typed(serde: JsonPlusSerializer, part: dict[str, Any]) -> Any: + if part["type"] not in _ALLOWED_ENVELOPE_TYPES: + raise ValueError(f"unsupported checkpoint serialisation type: {part['type']!r}") + return serde.loads_typed((part["type"], base64.b64decode(part["data_b64"]))) + + def _deserialise_envelope( serde: JsonPlusSerializer, envelope: dict[str, Any], @@ -358,12 +373,7 @@ def _deserialise_envelope( f"unsupported langgraph envelope version: {envelope.get('v')!r} " f"(expected {ENVELOPE_VERSION})" ) - ckpt = envelope["checkpoint"] - meta = envelope["metadata"] - checkpoint = serde.loads_typed( - (ckpt["type"], base64.b64decode(ckpt["data_b64"])) - ) - metadata = serde.loads_typed( - (meta["type"], base64.b64decode(meta["data_b64"])) + return ( + _loads_typed(serde, envelope["checkpoint"]), + _loads_typed(serde, envelope["metadata"]), ) - return checkpoint, metadata diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml index 0453640b..8592feac 100644 --- a/sdk/python/pyproject.toml +++ b/sdk/python/pyproject.toml @@ -18,7 +18,7 @@ dependencies = [ ] [project.optional-dependencies] -langgraph = ["langgraph>=0.1"] +langgraph = ["langgraph>=1.1", "langgraph-checkpoint>=4.0.1"] dev = ["pytest>=8.0", "pytest-asyncio>=0.23", "ruff>=0.4", "mypy>=1.10"] [tool.hatch.build.targets.wheel] diff --git a/sdk/python/tests/test_langgraph.py b/sdk/python/tests/test_langgraph.py index 17db4990..ae32d4e6 100644 --- a/sdk/python/tests/test_langgraph.py +++ b/sdk/python/tests/test_langgraph.py @@ -11,6 +11,7 @@ same thread, asserts the second sees the first's state. """ +import base64 import os import shutil import subprocess @@ -19,8 +20,11 @@ from operator import add from pathlib import Path from typing import Annotated, Any, TypedDict +from unittest.mock import MagicMock +import ormsgpack import pytest +from langchain_core.messages import AIMessage, HumanMessage from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer from agentic import AgenticClient @@ -95,6 +99,73 @@ def test_envelope_rejects_unknown_version(): _deserialise_envelope(serde, bogus) +class _Marker: + """Harmless stand-in for an attacker-chosen importable type.""" + + def __init__(self, value: Any) -> None: + self.value = value + + +def _strict_serde() -> JsonPlusSerializer: + return AgenticCheckpointer(client=MagicMock()).serde # type: ignore[return-value] + + +def _b64(raw: bytes) -> str: + return base64.b64encode(raw).decode("ascii") + + +def _envelope(ckpt: tuple[str, bytes], meta: tuple[str, bytes]) -> dict[str, Any]: + return { + "v": 1, + "thread_id": "x", + "checkpoint": {"type": ckpt[0], "data_b64": _b64(ckpt[1])}, + "metadata": {"type": meta[0], "data_b64": _b64(meta[1])}, + } + + +@pytest.mark.parametrize("bad_type", ["pickle", "json"]) +def test_envelope_rejects_unsafe_serialisation_type(bad_type: str): + env = _envelope((bad_type, b"{}"), ("null", b"")) + with pytest.raises(ValueError, match="unsupported checkpoint serialisation type"): + _deserialise_envelope(_strict_serde(), env) + env = _envelope(("null", b""), (bad_type, b"{}")) + with pytest.raises(ValueError, match="unsupported checkpoint serialisation type"): + _deserialise_envelope(_strict_serde(), env) + + +def test_checkpointer_does_not_reconstruct_unlisted_types(): + # msgpack ext 0 = constructor(module, name, arg): importable type naming + # a class outside langgraph's safe-type allowlist. + ext = ormsgpack.Ext(0, ormsgpack.packb((__name__, _Marker.__name__, "payload"))) + payload = ormsgpack.packb({"x": ext}, option=ormsgpack.OPT_NON_STR_KEYS) + env = _envelope(("msgpack", payload), ("null", b"")) + + ckpt, _ = _deserialise_envelope(_strict_serde(), env) + assert not isinstance(ckpt["x"], _Marker) + assert ckpt["x"] == "payload" # strict mode degrades to the raw argument + + # Control: the library's permissive default would have built the object. + permissive, _ = _deserialise_envelope(JsonPlusSerializer(allowed_msgpack_modules=True), env) + assert isinstance(permissive["x"], _Marker) + + +def test_envelope_roundtrip_langchain_messages(): + serde = _strict_serde() + ckpt = { + "v": 4, + "id": "c0", + "ts": "2026-05-20T00:00:00Z", + "channel_values": {"messages": [HumanMessage(content="hi"), AIMessage(content="hello")]}, + "channel_versions": {"messages": "1"}, + "versions_seen": {}, + "updated_channels": ["messages"], + } + env = _serialise_envelope(serde, ckpt, {"step": 0}, "u1") + ckpt2, meta2 = _deserialise_envelope(serde, env) + assert ckpt2["channel_values"]["messages"] == ckpt["channel_values"]["messages"] + assert meta2 == {"step": 0} + + # ===================================================== integration: daemon