Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix: use safe serialization for SQLite cache

Sameer Kadamb92a94f15ec9
diff --git a/semantica/semantic_extract/cache.py b/semantica/semantic_extract/cache.py
index a07653e0..23283a1e 100644
--- a/semantica/semantic_extract/cache.py
+++ b/semantica/semantic_extract/cache.py
@@ -25,12 +25,12 @@ License: MIT
"""
import copy
+import dataclasses
import os
import stat
import time
import hashlib
import json
-import pickle
import sqlite3
import threading
from abc import ABC, abstractmethod
@@ -46,6 +46,88 @@ from ..utils.logging import get_logger
NAMESPACES = ("entities", "relations", "triplets")
+# ---------------------------------------------------------------------------
+# Default SQLite serialization codec (JSON-based, safe)
+#
+# The codec handles the three concrete value types stored by ExtractionCache:
+# List[Entity], List[Relation], List[Triplet]
+#
+# Each dataclass is encoded as a plain JSON object tagged with a ``__type__``
+# key so the decoder can reconstruct the correct Python type unambiguously.
+# All field values (str, int, float, bool, None, dict-of-primitives) are
+# JSON-native, so no Python-specific serialisation is required.
+#
+# Values that are not one of the known tagged types (e.g. raw dicts or
+# primitives stored by tests) are round-tripped as-is. Unknown ``__type__``
+# tags are returned as plain dicts so forward-compatibility is preserved.
+# ---------------------------------------------------------------------------
+
+def _encode_value(value: Any) -> Any:
+ """Recursively encode *value* to a JSON-safe representation.
+
+ Dataclass instances are represented as ``{"__type__": "<ClassName>",
+ **fields}``. Lists are encoded element-wise. Everything else is
+ returned unchanged (it must already be JSON-serialisable; callers that
+ pass non-serialisable values will get a ``TypeError`` from
+ ``json.dumps``, which ``SqliteCacheBackend.set`` already handles).
+ """
+ if isinstance(value, list):
+ return [_encode_value(item) for item in value]
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
+ # Build the tagged envelope manually (rather than dataclasses.asdict)
+ # so that nested dataclasses are also tagged, which the decoder needs.
+ encoded: Dict[str, Any] = {"__type__": type(value).__name__}
+ for f in dataclasses.fields(value):
+ encoded[f.name] = _encode_value(getattr(value, f.name))
+ return encoded
+ # Primitive or dict — returned as-is; json.dumps will catch anything
+ # non-serialisable and SqliteCacheBackend.set treats that as a skip.
+ return value
+
+
+def _decode_value(raw: Any) -> Any:
+ """Reconstruct Python objects from the JSON-decoded representation.
+
+ Tagged dicts (``__type__`` key) are converted back to the corresponding
+ dataclass. Lists are decoded element-wise. Everything else is returned
+ unchanged.
+ """
+ # Import here to avoid a circular import; types.py has no deps on cache.py.
+ from .types import Entity, Relation, Triplet # noqa: PLC0415
+
+ if isinstance(raw, list):
+ return [_decode_value(item) for item in raw]
+ if isinstance(raw, dict) and "__type__" in raw:
+ type_tag = raw["__type__"]
+ fields = {k: _decode_value(v) for k, v in raw.items() if k != "__type__"}
+ if type_tag == "Entity":
+ return Entity(**fields)
+ if type_tag == "Relation":
+ return Relation(**fields)
+ if type_tag == "Triplet":
+ return Triplet(**fields)
+ # Unknown tag — return the original dict unchanged (forward-compat).
+ # Do NOT return fields: that would silently drop the ``__type__`` key.
+ return raw
+ # Primitive, plain dict without a type tag, etc.
+ return raw
+
+
+def _cache_serialize(value: Any) -> bytes:
+ """Default SQLite cache serializer. Converts *value* to UTF-8 JSON bytes.
+
+ Safe to deserialize from an untrusted file because ``json.loads`` does
+ not execute arbitrary code.
+ """
+ return json.dumps(_encode_value(value), ensure_ascii=False).encode("utf-8")
+
+
+def _cache_deserialize(data: bytes) -> Any:
+ """Default SQLite cache deserializer. Reconstructs Python objects from
+ the UTF-8 JSON bytes produced by :func:`_cache_serialize`."""
+ return _decode_value(json.loads(data.decode("utf-8")))
+
+
class CacheItem:
"""Container for cached data with metadata.
@@ -202,21 +284,24 @@ class SqliteCacheBackend(CacheBackend):
fresh process (CI job, notebook kernel, batch worker, extraction
subprocess) reuses previous results instead of re-paying every LLM call.
- **Trust model (read before enabling).** The database file is deserialized
- back into this process on every read, and the default ``serializer`` is
- ``pickle`` — so a cache file an attacker can influence is a code-execution
- vector. Therefore:
-
- - ``db_path`` MUST point at a **trusted, per-user, private** location.
- - The file may hold **sensitive extraction results** in the clear.
- - The default ``pickle`` serializer must only be used with a trusted file;
- pass ``serializer`` / ``deserializer`` (e.g. ``json``) for untrusted or
- shared locations.
-
- To enforce this the backend creates the file **atomically** with ``0o600``
- (``O_CREAT | O_EXCL``, no validate-then-open window) and, when reusing an
- existing file, rejects symlinks, non-regular files, and files owned by
- another user — raising so the caller falls back to the in-memory backend.
+ **Default serialization.** Values are stored as UTF-8 JSON with a thin
+ tagged-envelope codec that reconstructs :class:`~semantica.semantic_extract.types.Entity`,
+ :class:`~semantica.semantic_extract.types.Relation`, and
+ :class:`~semantica.semantic_extract.types.Triplet` instances transparently.
+ JSON is not executable, so a tampered cache file cannot achieve arbitrary
+ code execution through the default deserializer.
+
+ **Custom serializer/deserializer.** Pass explicit ``serializer`` and
+ ``deserializer`` callables to override the default codec. If you supply
+ ``pickle.dumps`` / ``pickle.loads`` you accept full responsibility for the
+ trust model: ``pickle`` deserializes arbitrary Python objects and a
+ file an attacker can write is a remote-code-execution vector.
+
+ **File security.** The backend creates the database file **atomically**
+ with ``0o600`` (``O_CREAT | O_EXCL``, no validate-then-open window) and,
+ when reusing an existing file, rejects symlinks, non-regular files, and
+ files owned by another user — raising so the caller falls back to the
+ in-memory backend.
Concurrency/reliability: TTL and LRU (by last access) mirror
:class:`InMemoryBackend`. A ``busy_timeout`` plus bounded retry handles
@@ -236,8 +321,8 @@ class SqliteCacheBackend(CacheBackend):
self,
db_path: str,
max_size: int = 1000,
- serializer: Callable[[Any], bytes] = pickle.dumps,
- deserializer: Callable[[bytes], Any] = pickle.loads,
+ serializer: Callable[[Any], bytes] = _cache_serialize,
+ deserializer: Callable[[bytes], Any] = _cache_deserialize,
busy_timeout: float = 5.0,
max_retries: int = 3,
retry_backoff: float = 0.05,
diff --git a/tests/semantic_extract/test_cache_backends.py b/tests/semantic_extract/test_cache_backends.py
index aa635640..8d797120 100644
--- a/tests/semantic_extract/test_cache_backends.py
+++ b/tests/semantic_extract/test_cache_backends.py
@@ -18,6 +18,7 @@ from semantica.semantic_extract import (
InMemoryBackend,
SqliteCacheBackend,
)
+from semantica.semantic_extract.types import Entity, Relation, Triplet
# ---------------------------------------------------------------------------
@@ -365,3 +366,381 @@ def test_configure_cache_switches_backend(tmp_path):
# (configure_cache closes the sqlite backend and mutates in place).
methods.config.set_optimization(cache_path=None)
methods.configure_cache(backend="memory")
+
+
+# ---------------------------------------------------------------------------
+# Security regression tests — issue #1668
+# (safe default serialization: JSON codec, not pickle)
+# ---------------------------------------------------------------------------
+
+
+def _make_entity(
+ text: str = "Apple Inc.",
+ label: str = "ORG",
+ start_char: int = 0,
+ end_char: int = 10,
+ confidence: float = 0.9,
+ metadata: "dict | None" = None,
+) -> Entity:
+ return Entity(
+ text=text,
+ label=label,
+ start_char=start_char,
+ end_char=end_char,
+ confidence=confidence,
+ metadata=metadata if metadata is not None else {},
+ )
+
+
+def test_default_serializer_is_not_pickle(tmp_path):
+ """The default SqliteCacheBackend must not use pickle.dumps / pickle.loads."""
+ import pickle as _pickle
+
+ backend = SqliteCacheBackend(_db(tmp_path))
+ assert backend._serialize is not _pickle.dumps, (
+ "default serializer must not be pickle.dumps"
+ )
+ assert backend._deserialize is not _pickle.loads, (
+ "default deserializer must not be pickle.loads"
+ )
+ backend.close()
+
+
+def test_sqlite_roundtrip_entity(tmp_path):
+ """List[Entity] including None confidence and non-empty metadata survives a
+ serialize → store → reload → deserialize cycle with the default codec."""
+ backend = SqliteCacheBackend(_db(tmp_path))
+
+ entities = [
+ _make_entity(
+ text="OpenAI",
+ label="ORG",
+ start_char=0,
+ end_char=6,
+ confidence=0.95,
+ metadata={"provider": "openai", "extraction_method": "llm_typed"},
+ ),
+ _make_entity(
+ text="Sam Altman",
+ label="PERSON",
+ start_char=10,
+ end_char=20,
+ confidence=None, # explicitly absent confidence
+ metadata={"confidence_source": "unavailable"},
+ ),
+ ]
+
+ backend.set("entities", "k", entities, ttl=None)
+ result = backend.get("entities", "k")
+
+ assert result is not None
+ assert len(result) == 2
+
+ e0 = result[0]
+ assert isinstance(e0, Entity)
+ assert e0.text == "OpenAI"
+ assert e0.label == "ORG"
+ assert e0.start_char == 0
+ assert e0.end_char == 6
+ assert e0.confidence == 0.95
+ assert e0.metadata == {"provider": "openai", "extraction_method": "llm_typed"}
+
+ e1 = result[1]
+ assert isinstance(e1, Entity)
+ assert e1.text == "Sam Altman"
+ assert e1.confidence is None # None must round-trip, not become 0.0
+ assert e1.metadata == {"confidence_source": "unavailable"}
+
+ backend.close()
+
+
+def test_sqlite_roundtrip_relation_with_nested_entities(tmp_path):
+ """List[Relation] with nested Entity subject/object and temporal metadata
+ survives the full codec round-trip including nested dataclass reconstruction."""
+ backend = SqliteCacheBackend(_db(tmp_path))
+
+ subj = _make_entity("Apple", "ORG", 0, 5, 0.9)
+ obj = _make_entity("Beats", "ORG", 10, 15, 0.85)
+ relations = [
+ Relation(
+ subject=subj,
+ predicate="acquired",
+ object=obj,
+ confidence=0.97,
+ context="Apple acquired Beats.",
+ metadata={
+ "provider": "openai",
+ "model": "gpt-4",
+ "extraction_method": "llm_typed",
+ "valid_from": "2014-05-01",
+ "valid_until": None,
+ "temporal_confidence": 0.9,
+ "temporal_source_text": "May 2014",
+ },
+ )
+ ]
+
+ backend.set("relations", "k", relations, ttl=None)
+ result = backend.get("relations", "k")
+
+ assert result is not None
+ assert len(result) == 1
+
+ r = result[0]
+ assert isinstance(r, Relation)
+ assert r.predicate == "acquired"
+ assert r.confidence == 0.97
+ assert r.context == "Apple acquired Beats."
+
+ # Nested Entity reconstruction
+ assert isinstance(r.subject, Entity)
+ assert r.subject.text == "Apple"
+ assert r.subject.label == "ORG"
+ assert r.subject.confidence == 0.9
+
+ assert isinstance(r.object, Entity)
+ assert r.object.text == "Beats"
+ assert r.object.confidence == 0.85
+
+ # Temporal metadata (str, None, float values)
+ assert r.metadata["valid_from"] == "2014-05-01"
+ assert r.metadata["valid_until"] is None
+ assert r.metadata["temporal_confidence"] == 0.9
+
+ backend.close()
+
+
+def test_sqlite_roundtrip_triplet(tmp_path):
+ """List[Triplet] survives the default codec round-trip."""
+ backend = SqliteCacheBackend(_db(tmp_path))
+
+ triplets = [
+ Triplet(
+ subject="Apple",
+ predicate="founded_by",
+ object="Steve Jobs",
+ confidence=0.99,
+ metadata={
+ "provider": "openai",
+ "model": "gpt-4",
+ "extraction_method": "llm_typed",
+ },
+ )
+ ]
+
+ backend.set("triplets", "k", triplets, ttl=None)
+ result = backend.get("triplets", "k")
+
+ assert result is not None
+ assert len(result) == 1
+
+ t = result[0]
+ assert isinstance(t, Triplet)
+ assert t.subject == "Apple"
+ assert t.predicate == "founded_by"
+ assert t.object == "Steve Jobs"
+ assert t.confidence == 0.99
+ assert t.metadata["extraction_method"] == "llm_typed"
+
+ backend.close()
+
+
+def test_sqlite_persists_entity_across_backend_instances(tmp_path):
+ """Entity dataclass fields must survive close() + re-open (persistence
+ regression for the new JSON codec)."""
+ path = _db(tmp_path)
+
+ entities = [
+ _make_entity(
+ text="Google",
+ label="ORG",
+ start_char=0,
+ end_char=6,
+ confidence=0.88,
+ metadata={"extraction_method": "llm_typed", "synthetic": False},
+ )
+ ]
+
+ first = SqliteCacheBackend(path)
+ first.set("entities", "persist_key", entities, ttl=None)
+ first.close()
+
+ second = SqliteCacheBackend(path)
+ result = second.get("entities", "persist_key")
+ second.close()
+
+ assert result is not None
+ assert len(result) == 1
+ e = result[0]
+ assert isinstance(e, Entity)
+ assert e.text == "Google"
+ assert e.label == "ORG"
+ assert e.confidence == 0.88
+ assert e.metadata["synthetic"] is False
+
+
+def test_legacy_pickle_row_is_treated_as_miss(tmp_path):
+ """A BLOB written by pickle.dumps (legacy format) must be treated as a
+ cache miss by the new default JSON deserializer. It must NOT be passed
+ to pickle.loads and must NOT raise — the row must be silently evicted."""
+ import pickle as _pickle
+
+ path = _db(tmp_path)
+
+ # Use the new-default backend to create the schema.
+ setup = SqliteCacheBackend(path)
+ setup.close()
+
+ # Bypass the backend and inject a pickle-serialized value directly.
+ legacy_blob = _pickle.dumps({"x": 1})
+ conn = sqlite3.connect(path)
+ conn.execute(
+ "INSERT OR REPLACE INTO cache"
+ " (namespace, key, value, expires_at, last_access)"
+ " VALUES (?, ?, ?, NULL, 0.0)",
+ ("entities", "legacy_key", legacy_blob),
+ )
+ conn.commit()
+ conn.close()
+
+ # Re-open with the new default backend — must return None, not crash.
+ backend = SqliteCacheBackend(path)
+ result = backend.get("entities", "legacy_key")
+ assert result is None, "legacy pickle row must be a miss, not an exception"
+ # The corrupt row must be evicted, not left in the table.
+ assert backend.size("entities") == 0, "legacy pickle row must be evicted"
+ backend.close()
+
+
+def test_malicious_pickle_payload_does_not_execute(tmp_path):
+ """A crafted pickle payload injected directly into the DB BLOB must NOT
+ execute through the default deserializer.
+
+ The payload's __reduce__ would create a sentinel file if pickle.loads were
+ called on it. We assert the sentinel does NOT exist after backend.get(),
+ confirming the JSON decoder never handed the bytes to pickle.
+ """
+ import pickle as _pickle
+
+ sentinel = tmp_path / "PWNED"
+
+ class _MaliciousPayload:
+ """Pickle payload that creates a sentinel file on deserialization."""
+
+ def __reduce__(self):
+ # Would execute: open(str(sentinel), "w").close()
+ return (open, (str(sentinel), "w"))
+
+ path = _db(tmp_path)
+
+ # Create the schema via the safe backend.
+ setup = SqliteCacheBackend(path)
+ setup.close()
+
+ # Inject the malicious pickle bytes directly into the BLOB column.
+ malicious_blob = _pickle.dumps(_MaliciousPayload())
+ conn = sqlite3.connect(path)
+ conn.execute(
+ "INSERT OR REPLACE INTO cache"
+ " (namespace, key, value, expires_at, last_access)"
+ " VALUES (?, ?, ?, NULL, 0.0)",
+ ("entities", "evil_key", malicious_blob),
+ )
+ conn.commit()
+ conn.close()
+
+ # Re-open with the new default backend and attempt to read the row.
+ backend = SqliteCacheBackend(path)
+ result = backend.get("entities", "evil_key")
+ backend.close()
+
+ # The sentinel must NOT have been created — payload was never executed.
+ assert not sentinel.exists(), (
+ "Malicious pickle payload executed through the default deserializer "
+ "(sentinel file was created). pickle.loads must not be in the default path."
+ )
+ # The result must be a miss (JSON decode failed cleanly).
+ assert result is None, "malicious row must be returned as a miss"
+
+
+def test_custom_pickle_serializer_escape_hatch(tmp_path):
+ """Users who explicitly supply pickle.dumps / pickle.loads as the
+ serializer/deserializer must still get correct round-trip behaviour.
+ The escape hatch must not be broken by this security fix."""
+ import pickle as _pickle
+
+ backend = SqliteCacheBackend(
+ _db(tmp_path),
+ serializer=_pickle.dumps,
+ deserializer=_pickle.loads,
+ )
+
+ entities = [
+ _make_entity(
+ text="Microsoft",
+ label="ORG",
+ start_char=0,
+ end_char=9,
+ confidence=0.92,
+ metadata={"extraction_method": "llm_typed"},
+ )
+ ]
+
+ backend.set("entities", "k", entities, ttl=None)
+ result = backend.get("entities", "k")
+
+ assert result is not None
+ assert len(result) == 1
+ assert isinstance(result[0], Entity)
+ assert result[0].text == "Microsoft"
+ assert result[0].confidence == 0.92
+ backend.close()
+
+
+def test_metadata_dict_with_dunder_type_key_is_not_misreconstructed(tmp_path):
+ """A metadata dict that happens to contain a ``__type__`` key must NOT be
+ reconstructed as an Entity, Relation, or Triplet — it must round-trip as
+ a plain dict.
+
+ This guards against the codec accidentally treating user-supplied metadata
+ values as tagged envelopes.
+ """
+ backend = SqliteCacheBackend(_db(tmp_path))
+
+ # An Entity whose metadata dict contains a "__type__" key with an unknown
+ # tag name. The metadata must survive unchanged as a plain dict.
+ entities = [
+ _make_entity(
+ text="TestOrg",
+ label="ORG",
+ start_char=0,
+ end_char=7,
+ confidence=0.8,
+ metadata={
+ # Unknown __type__ tag inside metadata.
+ # Must NOT cause metadata to be reconstructed as a dataclass.
+ "__type__": "SomeExternalModel",
+ "schema_version": 2,
+ },
+ )
+ ]
+
+ backend.set("entities", "k", entities, ttl=None)
+ result = backend.get("entities", "k")
+ backend.close()
+
+ assert result is not None
+ assert len(result) == 1
+
+ e = result[0]
+ # The outer value must be reconstructed correctly as an Entity.
+ assert isinstance(e, Entity), "outer value must be reconstructed as Entity"
+ assert e.text == "TestOrg"
+
+ # The metadata dict must come back as a plain dict, not a dataclass.
+ assert isinstance(e.metadata, dict), "metadata must remain a plain dict"
+ # The __type__ key inside metadata must be preserved exactly — not stripped.
+ assert e.metadata["__type__"] == "SomeExternalModel", (
+ "__type__ key inside metadata must be preserved, not stripped"
+ )
+ assert e.metadata["schema_version"] == 2