Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(cache): HMAC-seal on-disk pickle caches before unpickling (#1439)

Felix-Ayush5d241416d813
diff --git a/packages/core/src/repowise/core/analysis/health/duplication/pair_index.py b/packages/core/src/repowise/core/analysis/health/duplication/pair_index.py
index d61b1f165..4141e32ae 100644
--- a/packages/core/src/repowise/core/analysis/health/duplication/pair_index.py
+++ b/packages/core/src/repowise/core/analysis/health/duplication/pair_index.py
@@ -29,15 +29,13 @@ cache next to it.
from __future__ import annotations
-import contextlib
-import os
-import pickle
-import tempfile
from dataclasses import dataclass, field
from pathlib import Path
import structlog
+from repowise.core.cache_seal import dump_sealed_pickle, load_sealed_pickle
+
from .limits import DuplicationLimits
log = structlog.get_logger(__name__)
@@ -95,8 +93,7 @@ def load_pair_index(
"""Load and validate the artifact; ``None`` on any mismatch/error."""
path = Path(cache_dir) / _INDEX_FILENAME
try:
- with path.open("rb") as fh:
- payload = pickle.load(fh)
+ payload = load_sealed_pickle(path, domain=_INDEX_FILENAME)
if (
payload.get("version") != _INDEX_VERSION
or payload.get("window_tokens") != window_tokens
@@ -116,7 +113,7 @@ def load_pair_index(
)
except FileNotFoundError:
return None
- except Exception as exc: # corrupt / unreadable -> full re-detect
+ except Exception as exc: # corrupt / unsigned / unreadable -> full re-detect
log.debug("duplication_pair_index_load_failed", error=str(exc))
return None
@@ -125,7 +122,6 @@ def save_pair_index(cache_dir: Path, index: DuplicationPairIndex) -> None:
"""Atomically persist *index*; failures degrade to a future full run."""
path = Path(cache_dir) / _INDEX_FILENAME
try:
- path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"version": _INDEX_VERSION,
"window_tokens": index.window_tokens,
@@ -138,14 +134,6 @@ def save_pair_index(cache_dir: Path, index: DuplicationPairIndex) -> None:
"window_budget_hit": index.window_budget_hit,
"timed_out": index.timed_out,
}
- fd, tmp_name = tempfile.mkstemp(dir=str(path.parent), prefix=_INDEX_FILENAME, suffix=".tmp")
- try:
- with os.fdopen(fd, "wb") as fh:
- pickle.dump(payload, fh, protocol=pickle.HIGHEST_PROTOCOL)
- os.replace(tmp_name, path)
- except BaseException:
- with contextlib.suppress(OSError):
- os.unlink(tmp_name)
- raise
+ dump_sealed_pickle(path, payload, domain=_INDEX_FILENAME)
except Exception as exc:
log.debug("duplication_pair_index_save_failed", error=str(exc))
diff --git a/packages/core/src/repowise/core/analysis/health/duplication/token_cache.py b/packages/core/src/repowise/core/analysis/health/duplication/token_cache.py
index fc6f4ce85..968e23ec2 100644
--- a/packages/core/src/repowise/core/analysis/health/duplication/token_cache.py
+++ b/packages/core/src/repowise/core/analysis/health/duplication/token_cache.py
@@ -21,15 +21,13 @@ each run, so deleted files age out naturally.
from __future__ import annotations
-import contextlib
-import os
-import pickle
import sys
-import tempfile
from pathlib import Path
import structlog
+from repowise.core.cache_seal import dump_sealed_pickle, load_sealed_pickle
+
log = structlog.get_logger(__name__)
_CACHE_VERSION = 1
@@ -51,8 +49,7 @@ class DuplicationTokenCache:
def load(self) -> None:
try:
- with self._path.open("rb") as fh:
- payload = pickle.load(fh)
+ payload = load_sealed_pickle(self._path, domain=_CACHE_FILENAME)
if (
payload.get("version") != _CACHE_VERSION
or payload.get("window_tokens") != self._window_tokens
@@ -61,29 +58,18 @@ class DuplicationTokenCache:
self._entries = payload.get("files", {})
except FileNotFoundError:
return
- except Exception as exc: # corrupt / unreadable cache -> full tokenize
+ except Exception as exc: # corrupt / unsigned / unreadable -> full tokenize
log.debug("duplication_cache_load_failed", error=str(exc))
def save(self) -> None:
"""Atomically persist the entries used or created this run."""
try:
- self._path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"version": _CACHE_VERSION,
"window_tokens": self._window_tokens,
"files": self._fresh,
}
- fd, tmp_name = tempfile.mkstemp(
- dir=str(self._path.parent), prefix=_CACHE_FILENAME, suffix=".tmp"
- )
- try:
- with os.fdopen(fd, "wb") as fh:
- pickle.dump(payload, fh, protocol=pickle.HIGHEST_PROTOCOL)
- os.replace(tmp_name, self._path)
- except BaseException:
- with contextlib.suppress(OSError):
- os.unlink(tmp_name)
- raise
+ dump_sealed_pickle(self._path, payload, domain=_CACHE_FILENAME)
except Exception as exc:
log.debug("duplication_cache_save_failed", error=str(exc))
diff --git a/packages/core/src/repowise/core/cache_seal.py b/packages/core/src/repowise/core/cache_seal.py
new file mode 100644
index 000000000..037930286
--- /dev/null
+++ b/packages/core/src/repowise/core/cache_seal.py
@@ -0,0 +1,254 @@
+"""HMAC seal for on-disk caches that live inside the indexed repo.
+
+Caches under ``.repowise/`` are attacker-writable: a published repo can
+``git add -f`` them despite the directory being gitignored. Loading those
+files with bare ``pickle.load`` is CWE-502 (deserialization of untrusted
+data) — the version / fingerprint checks run *after* unpickling, so a
+crafted ``__reduce__`` payload already ran.
+
+This module seals pickled bytes with a machine-local HMAC key that is
+never stored next to the cache. The MAC also binds a *domain* string
+(typically the cache filename) so a sealed file cannot be renamed or
+copied across cache kinds / repos on the same machine. Callers must
+verify before unpickling. Unsigned legacy files and forged payloads raise
+and degrade to a cache miss / full recompute.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import hashlib
+import hmac
+import os
+import pickle
+import secrets
+import tempfile
+from functools import lru_cache
+from pathlib import Path
+from typing import Any
+
+__all__ = [
+ "dump_sealed_pickle",
+ "load_sealed_pickle",
+ "reset_key_cache_for_tests",
+ "seal",
+ "unseal",
+]
+
+#: Format tag. Bump the trailing digit only when the envelope layout changes.
+_MAGIC = b"RWCH1"
+_MAC_LEN = 32 # sha256 digest
+_MIN_KEY_LEN = 16
+_STREAM_CHUNK = 1024 * 1024
+
+
+def _key_path() -> Path:
+ override = os.environ.get("REPOWISE_CACHE_KEY_PATH")
+ if override:
+ return Path(override)
+ xdg = os.environ.get("XDG_CONFIG_HOME")
+ base = Path(xdg) if xdg else Path.home() / ".config"
+ return base / "repowise" / "cache_hmac_key"
+
+
+def _read_valid_key(path: Path) -> bytes | None:
+ """Return the key file contents iff they are long enough, else ``None``.
+
+ Empty or truncated files (e.g. a crash mid-write under a prior non-atomic
+ path) must not be trusted — an empty HMAC key is a publicly known key.
+ """
+ try:
+ data = path.read_bytes()
+ except FileNotFoundError:
+ return None
+ except OSError:
+ return None
+ if len(data) < _MIN_KEY_LEN:
+ return None
+ return data
+
+
+def _write_key_atomic(path: Path, key: bytes) -> None:
+ """Persist *key* via temp file + ``os.replace`` so a crash cannot leave 0 bytes.
+
+ Mode ``0o600`` is best-effort: respected on POSIX, effectively ignored on
+ Windows (ACLs are separate). The HMAC key is still not stored next to the
+ cache either way.
+ """
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp_name = tempfile.mkstemp(
+ dir=str(path.parent), prefix=".cache_hmac_key.", suffix=".tmp"
+ )
+ try:
+ os.write(fd, key)
+ os.close(fd)
+ fd = -1
+ with contextlib.suppress(OSError):
+ os.chmod(tmp_name, 0o600)
+ os.replace(tmp_name, path)
+ except BaseException:
+ if fd >= 0:
+ with contextlib.suppress(OSError):
+ os.close(fd)
+ with contextlib.suppress(OSError):
+ os.unlink(tmp_name)
+ raise
+
+
+@lru_cache(maxsize=1)
+def _hmac_key() -> bytes:
+ """Return the machine-local HMAC key, creating it on first use.
+
+ Precedence:
+ 1. ``REPOWISE_CACHE_HMAC_KEY`` — hex-encoded key (tests / CI), min 16 bytes.
+ 2. File at ``REPOWISE_CACHE_KEY_PATH`` or ``$XDG_CONFIG_HOME/repowise/cache_hmac_key``.
+
+ Short / empty key files are ignored and replaced; the in-memory key is used
+ if the config dir is unwritable.
+ """
+ env_key = os.environ.get("REPOWISE_CACHE_HMAC_KEY")
+ if env_key:
+ try:
+ raw = bytes.fromhex(env_key.strip())
+ except ValueError as exc:
+ raise ValueError("REPOWISE_CACHE_HMAC_KEY must be a hex-encoded key") from exc
+ if len(raw) < _MIN_KEY_LEN:
+ raise ValueError("REPOWISE_CACHE_HMAC_KEY must be at least 16 bytes")
+ return raw
+
+ path = _key_path()
+ existing = _read_valid_key(path)
+ if existing is not None:
+ return existing
+
+ key = secrets.token_bytes(32)
+ try:
+ # Atomic replace so a crash cannot leave a 0-byte key file. If the
+ # file is missing or truncated we (re)write; a race with another
+ # first-time writer may overwrite once, then we re-read whatever
+ # landed so we never return b"".
+ _write_key_atomic(path, key)
+ except OSError:
+ # Unwritable home (ephemeral CI, read-only container): keep the
+ # in-memory key for this process. Caches won't survive a restart,
+ # which is the safe degradation.
+ return key
+ existing = _read_valid_key(path)
+ return existing if existing is not None else key
+
+
+def reset_key_cache_for_tests() -> None:
+ """Drop the cached key so tests can swap env / key path mid-run."""
+ _hmac_key.cache_clear()
+
+
+def _domain_prefix(domain: str) -> bytes:
+ return domain.encode("utf-8") + b"\x00"
+
+
+def seal(payload: bytes, *, domain: str = "") -> bytes:
+ """Return ``MAGIC || HMAC-SHA256(key, domain||NUL||payload) || payload``."""
+ mac = hmac.new(_hmac_key(), _domain_prefix(domain) + payload, hashlib.sha256).digest()
+ return _MAGIC + mac + payload
+
+
+def unseal(blob: bytes, *, domain: str = "") -> bytes:
+ """Verify and return the sealed payload, or raise ``ValueError``.
+
+ Raises on missing/unknown magic, truncated envelopes, or HMAC mismatch.
+ Never returns bytes that have not been authenticated — callers may
+ ``pickle.loads`` the result.
+ """
+ min_len = len(_MAGIC) + _MAC_LEN
+ if len(blob) < min_len or not blob.startswith(_MAGIC):
+ raise ValueError("unsigned or unsupported cache format")
+ mac = blob[len(_MAGIC) : len(_MAGIC) + _MAC_LEN]
+ payload = blob[len(_MAGIC) + _MAC_LEN :]
+ expected = hmac.new(
+ _hmac_key(), _domain_prefix(domain) + payload, hashlib.sha256
+ ).digest()
+ if not hmac.compare_digest(mac, expected):
+ raise ValueError("cache HMAC mismatch")
+ return payload
+
+
+def load_sealed_pickle(path: Path, *, domain: str) -> Any:
+ """Stream-verify a sealed pickle file, then ``pickle.load`` without an extra copy.
+
+ Reads magic + MAC, HMAC-updates over the payload in chunks, compares, seeks
+ back to the payload offset, and unpickles from the file handle — so peak
+ RAM stays close to the object graph alone (no full ``read_bytes()`` twin).
+ """
+ header = len(_MAGIC) + _MAC_LEN
+ with path.open("rb") as fh:
+ magic = fh.read(len(_MAGIC))
+ if magic != _MAGIC:
+ raise ValueError("unsigned or unsupported cache format")
+ mac = fh.read(_MAC_LEN)
+ if len(mac) != _MAC_LEN:
+ raise ValueError("unsigned or unsupported cache format")
+ h = hmac.new(_hmac_key(), _domain_prefix(domain), hashlib.sha256)
+ while True:
+ chunk = fh.read(_STREAM_CHUNK)
+ if not chunk:
+ break
+ h.update(chunk)
+ if not hmac.compare_digest(mac, h.digest()):
+ raise ValueError("cache HMAC mismatch")
+ fh.seek(header)
+ return pickle.load(fh)
+
+
+def dump_sealed_pickle(path: Path, obj: Any, *, domain: str) -> None:
+ """Atomically write *obj* as a domain-bound sealed pickle.
+
+ Pickles to a temp file first, streams the HMAC over it, then writes
+ ``MAGIC||MAC||payload`` via a second temp + ``os.replace`` — avoiding a
+ second full in-memory copy of the pickled bytes beside the object graph.
+ """
+ path = Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd_pkl, tmp_pkl = tempfile.mkstemp(
+ dir=str(path.parent), prefix=path.name, suffix=".pkltmp"
+ )
+ try:
+ with os.fdopen(fd_pkl, "wb") as fh:
+ fd_pkl = -1
+ pickle.dump(obj, fh, protocol=pickle.HIGHEST_PROTOCOL)
+
+ h = hmac.new(_hmac_key(), _domain_prefix(domain), hashlib.sha256)
+ with open(tmp_pkl, "rb") as src:
+ while True:
+ chunk = src.read(_STREAM_CHUNK)
+ if not chunk:
+ break
+ h.update(chunk)
+ mac = h.digest()
+
+ fd_out, tmp_out = tempfile.mkstemp(
+ dir=str(path.parent), prefix=path.name, suffix=".tmp"
+ )
+ try:
+ with os.fdopen(fd_out, "wb") as out, open(tmp_pkl, "rb") as src:
+ fd_out = -1
+ out.write(_MAGIC)
+ out.write(mac)
+ while True:
+ chunk = src.read(_STREAM_CHUNK)
+ if not chunk:
+ break
+ out.write(chunk)
+ os.replace(tmp_out, path)
+ except BaseException:
+ if fd_out >= 0:
+ with contextlib.suppress(OSError):
+ os.close(fd_out)
+ with contextlib.suppress(OSError):
+ os.unlink(tmp_out)
+ raise
+ finally:
+ if fd_pkl >= 0:
+ with contextlib.suppress(OSError):
+ os.close(fd_pkl)
+ with contextlib.suppress(OSError):
+ os.unlink(tmp_pkl)
diff --git a/packages/core/src/repowise/core/ingestion/graph/_centrality_cache.py b/packages/core/src/repowise/core/ingestion/graph/_centrality_cache.py
index 4eb1d2baa..2edf1d7b0 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_centrality_cache.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_centrality_cache.py
@@ -21,16 +21,14 @@ values — deterministic where the status quo was not.
from __future__ import annotations
-import contextlib
import hashlib
-import os
-import pickle
-import tempfile
import threading
from pathlib import Path
import structlog
+from repowise.core.cache_seal import dump_sealed_pickle, load_sealed_pickle
+
log = structlog.get_logger(__name__)
# Bumped to 2 when betweenness was made order-independent: the signature keys
@@ -90,14 +88,13 @@ class CentralityCache:
return
self._loaded = True
try:
- with self._path.open("rb") as fh:
- payload = pickle.load(fh)
+ payload = load_sealed_pickle(self._path, domain=_CACHE_FILENAME)
if payload.get("version") != _CACHE_VERSION:
return
self._entries = payload.get("entries", {})
except FileNotFoundError:
return
- except Exception as exc: # corrupt / unreadable cache -> recompute
+ except Exception as exc: # corrupt / unsigned / unreadable -> recompute
log.debug("centrality_cache_load_failed", error=str(exc))
def get(self, kind: str, signature: str) -> dict[str, float] | None:
@@ -114,18 +111,7 @@ class CentralityCache:
self._ensure_loaded()
self._entries[kind] = (signature, dict(values))
try:
- self._path.parent.mkdir(parents=True, exist_ok=True)
payload = {"version": _CACHE_VERSION, "entries": self._entries}
- fd, tmp_name = tempfile.mkstemp(
- dir=str(self._path.parent), prefix=_CACHE_FILENAME, suffix=".tmp"
- )
- try:
- with os.fdopen(fd, "wb") as fh:
- pickle.dump(payload, fh, protocol=pickle.HIGHEST_PROTOCOL)
- os.replace(tmp_name, self._path)
- except BaseException:
- with contextlib.suppress(OSError):
- os.unlink(tmp_name)
- raise
+ dump_sealed_pickle(self._path, payload, domain=_CACHE_FILENAME)
except Exception as exc:
log.debug("centrality_cache_save_failed", error=str(exc))
diff --git a/packages/core/src/repowise/core/ingestion/parse_cache.py b/packages/core/src/repowise/core/ingestion/parse_cache.py
index 21c53a923..136d6b5e9 100644
--- a/packages/core/src/repowise/core/ingestion/parse_cache.py
+++ b/packages/core/src/repowise/core/ingestion/parse_cache.py
@@ -24,18 +24,17 @@ so deleted files age out naturally.
from __future__ import annotations
-import contextlib
import dataclasses
import hashlib
-import os
import pickle
-import tempfile
from functools import lru_cache
from pathlib import Path
from typing import Any
import structlog
+from repowise.core.cache_seal import dump_sealed_pickle, load_sealed_pickle
+
from . import models
from .models import FileInfo, ParsedFile
@@ -127,8 +126,9 @@ class ParseCache:
def load(self) -> None:
try:
- with self._path.open("rb") as fh:
- payload = pickle.load(fh)
+ # HMAC-verify *before* unpickling — the cache lives inside the
+ # indexed repo and is attacker-writable (see cache_seal).
+ payload = load_sealed_pickle(self._path, domain=_CACHE_FILENAME)
if (
payload.get("version") != _CACHE_VERSION
or payload.get("fingerprint") != self._fingerprint
@@ -137,29 +137,18 @@ class ParseCache:
self._entries = payload.get("files", {})
except FileNotFoundError:
return
- except Exception as exc: # corrupt / unreadable cache -> full parse
+ except Exception as exc: # corrupt / unreadable / unsigned -> full parse
log.debug("parse_cache_load_failed", error=str(exc))
def save(self) -> None:
"""Atomically persist the entries used or created this run."""
try:
- self._path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"version": _CACHE_VERSION,
"fingerprint": self._fingerprint,
"files": self._fresh,
}
- fd, tmp_name = tempfile.mkstemp(
- dir=str(self._path.parent), prefix=_CACHE_FILENAME, suffix=".tmp"
- )
- try:
- with os.fdopen(fd, "wb") as fh:
- pickle.dump(payload, fh, protocol=pickle.HIGHEST_PROTOCOL)
- os.replace(tmp_name, self._path)
- except BaseException:
- with contextlib.suppress(OSError):
- os.unlink(tmp_name)
- raise
+ dump_sealed_pickle(self._path, payload, domain=_CACHE_FILENAME)
except Exception as exc:
log.debug("parse_cache_save_failed", error=str(exc))
diff --git a/tests/unit/ingestion/test_parse_cache.py b/tests/unit/ingestion/test_parse_cache.py
index 9b513ce99..384aeb7ba 100644
--- a/tests/unit/ingestion/test_parse_cache.py
+++ b/tests/unit/ingestion/test_parse_cache.py
@@ -15,9 +15,13 @@ import networkx as nx
import pytest
from repowise.cli.commands.update_cmd import _build_repo_graph
+from repowise.core.cache_seal import seal, unseal
from repowise.core.ingestion import compute_content_hash
from repowise.core.ingestion.parse_cache import ParseCache, parser_fingerprint
+_CACHE_DOMAIN = "parse_cache.pkl"
+
+
def _write_fixture(repo) -> None:
(repo / "util.py").write_text(
@@ -130,10 +134,10 @@ def test_corrupt_cache_falls_back_to_full_parse(repo):
def test_fingerprint_mismatch_invalidates(repo, tmp_path):
_build(repo)
cache_file = _cache_path(repo)
- payload = pickle.loads(cache_file.read_bytes())
+ payload = pickle.loads(unseal(cache_file.read_bytes(), domain=_CACHE_DOMAIN))
assert payload["fingerprint"] == parser_fingerprint()
payload["fingerprint"] = "stale-fingerprint"
- cache_file.write_bytes(pickle.dumps(payload))
+ cache_file.write_bytes(seal(pickle.dumps(payload), domain=_CACHE_DOMAIN))
cache = ParseCache(repo / ".repowise")
cache.load()
@@ -157,7 +161,10 @@ def test_dataclass_schema_change_invalidates_cache(repo, monkeypatch):
_build(repo) # populate the cache under the current fingerprint
cache_file = _cache_path(repo)
- assert pickle.loads(cache_file.read_bytes())["fingerprint"] == parser_fingerprint()
+ assert (
+ pickle.loads(unseal(cache_file.read_bytes(), domain=_CACHE_DOMAIN))["fingerprint"]
+ == parser_fingerprint()
+ )
# Simulate a release that adds a field to ParsedFile.
@dataclasses.dataclass
@@ -168,7 +175,12 @@ def test_dataclass_schema_change_invalidates_cache(repo, monkeypatch):
monkeypatch.setattr(models, "ParsedFile", _Evolved)
parse_cache.parser_fingerprint.cache_clear()
try:
- assert parser_fingerprint() != pickle.loads(cache_file.read_bytes())["fingerprint"]
+ assert (
+ parser_fingerprint()
+ != pickle.loads(unseal(cache_file.read_bytes(), domain=_CACHE_DOMAIN))[
+ "fingerprint"
+ ]
+ )
cache = ParseCache(repo / ".repowise")
cache.load()
@@ -228,12 +240,58 @@ def test_deleted_files_age_out_of_cache(repo):
_build(repo)
(repo / "other.py").unlink()
_build(repo) # rewrite keeps only entries touched this run
- payload = pickle.loads(_cache_path(repo).read_bytes())
+ payload = pickle.loads(unseal(_cache_path(repo).read_bytes(), domain=_CACHE_DOMAIN))
cached_paths = {path for path, _hash in payload["files"]}
assert "other.py" not in cached_paths
assert "main.py" in cached_paths
+def test_unsigned_legacy_pickle_is_ignored(repo, tmp_path):
+ """Unsigned pickle (the #1390 attack shape) must not be loaded.
+
+ Version / fingerprint checks used to run *after* pickle.load, so a
+ crafted ``__reduce__`` payload already executed. We now refuse anything
+ that is not HMAC-sealed with the machine-local key.
+ """
+ marker = tmp_path / "PWNED"
+
+ class Evil:
+ def __reduce__(self):
+ return (marker.write_text, ("pwned",))
+
+ # Legacy unsigned format — exactly what an attacker would ``git add -f``.
+ _cache_path(repo).write_bytes(
+ pickle.dumps(
+ {
+ "version": 1,
+ "fingerprint": parser_fingerprint(),
+ "files": {("main.py", "HASH"): Evil()},
+ }
+ )
+ )
+
+ cache = ParseCache(repo / ".repowise")
+ cache.load()
+ assert cache._entries == {}
+ assert not marker.exists()
+
+
+def test_forged_hmac_is_rejected(repo, monkeypatch, tmp_path):
+ """A sealed envelope with a MAC under a different key is a miss."""
+ from repowise.core import cache_seal
+
+ monkeypatch.setenv("REPOWISE_CACHE_HMAC_KEY", "aa" * 32)
+ cache_seal.reset_key_cache_for_tests()
+ _build(repo) # write under key A
+
+ monkeypatch.setenv("REPOWISE_CACHE_HMAC_KEY", "bb" * 32)
+ cache_seal.reset_key_cache_for_tests()
+ cache = ParseCache(repo / ".repowise")
+ cache.load()
+ assert cache._entries == {}
+ cache_seal.reset_key_cache_for_tests()
+
+
def test_cache_hit_stamps_content_hash(repo):
"""A hit must carry the raw-bytes hash even for entries pickled before
ParsedFile had the field — the cache key already proves byte identity,
diff --git a/tests/unit/test_cache_seal.py b/tests/unit/test_cache_seal.py
new file mode 100644
index 000000000..8da146d46
--- /dev/null
+++ b/tests/unit/test_cache_seal.py
@@ -0,0 +1,122 @@
+"""HMAC seal: refuse unsigned / forged / empty-key / cross-domain caches."""
+
+from __future__ import annotations
+
+import pickle
+
+import pytest
+
+from repowise.core.cache_seal import (
+ dump_sealed_pickle,
+ load_sealed_pickle,
+ reset_key_cache_for_tests,
+ seal,
+ unseal,
+)
+
+
[email protected](autouse=True)
+def _isolate_hmac_key(monkeypatch, tmp_path):
+ monkeypatch.setenv("REPOWISE_CACHE_HMAC_KEY", "ab" * 32)
+ monkeypatch.delenv("REPOWISE_CACHE_KEY_PATH", raising=False)
+ reset_key_cache_for_tests()
+ yield
+ reset_key_cache_for_tests()
+
+
+def test_seal_roundtrip():
+ payload = pickle.dumps({"version": 1, "files": {}})
+ assert unseal(seal(payload, domain="parse_cache.pkl"), domain="parse_cache.pkl") == payload
+
+
+def test_unseal_rejects_unsigned_pickle():
+ raw = pickle.dumps({"version": 1})
+ with pytest.raises(ValueError, match="unsigned"):
+ unseal(raw, domain="parse_cache.pkl")
+
+
+def test_unseal_rejects_tampered_payload():
+ sealed = bytearray(seal(b"hello", domain="x"))
+ sealed[-1] ^= 0xFF
+ with pytest.raises(ValueError, match="HMAC"):
+ unseal(bytes(sealed), domain="x")
+
+
+def test_unseal_rejects_wrong_key(monkeypatch):
+ sealed = seal(b"hello", domain="x")
+ monkeypatch.setenv("REPOWISE_CACHE_HMAC_KEY", "cd" * 32)
+ reset_key_cache_for_tests()
+ with pytest.raises(ValueError, match="HMAC"):
+ unseal(sealed, domain="x")
+
+
+def test_unseal_rejects_wrong_domain():
+ sealed = seal(b"hello", domain="parse_cache.pkl")
+ with pytest.raises(ValueError, match="HMAC"):
+ unseal(sealed, domain="centrality_cache.pkl")
+
+
+def test_evil_reduce_never_runs_through_unseal(tmp_path):
+ marker = tmp_path / "PWNED"
+
+ class Evil:
+ def __reduce__(self):
+ return (marker.write_text, ("pwned",))
+
+ blob = pickle.dumps(Evil())
+ with pytest.raises(ValueError, match="unsigned"):
+ unseal(blob, domain="parse_cache.pkl")
+ assert not marker.exists()
+
+
+def test_empty_key_file_is_replaced_not_trusted(monkeypatch, tmp_path):
+ """A 0-byte key file must not become the HMAC key (Raghav #1439 review)."""
+ from repowise.core import cache_seal
+
+ key_path = tmp_path / "cache_hmac_key"
+ key_path.write_bytes(b"") # crash mid-write leftover
+ monkeypatch.delenv("REPOWISE_CACHE_HMAC_KEY", raising=False)
+ monkeypatch.setenv("REPOWISE_CACHE_KEY_PATH", str(key_path))
+ reset_key_cache_for_tests()
+
+ key = cache_seal._hmac_key()
+ assert len(key) >= 16
+ assert key_path.read_bytes() == key
+
+ # Empty-key forgeries must not verify under the replaced key.
+ forged = (
+ b"RWCH1"
+ + __import__("hmac")
+ .new(b"", b"\x00" + b"payload", __import__("hashlib").sha256)
+ .digest()
+ + b"payload"
+ )
+ with pytest.raises(ValueError, match="HMAC"):
+ unseal(forged, domain="")
+
+
+def test_short_key_file_is_replaced(monkeypatch, tmp_path):
+ from repowise.core import cache_seal
+
+ key_path = tmp_path / "cache_hmac_key"
+ key_path.write_bytes(b"short")
+ monkeypatch.delenv("REPOWISE_CACHE_HMAC_KEY", raising=False)
+ monkeypatch.setenv("REPOWISE_CACHE_KEY_PATH", str(key_path))
+ reset_key_cache_for_tests()
+
+ key = cache_seal._hmac_key()
+ assert len(key) >= 16
+ assert key != b"short"
+
+
+def test_dump_and_load_sealed_pickle_roundtrip(tmp_path):
+ path = tmp_path / "parse_cache.pkl"
+ dump_sealed_pickle(path, {"version": 1, "files": {}}, domain="parse_cache.pkl")
+ assert load_sealed_pickle(path, domain="parse_cache.pkl") == {"version": 1, "files": {}}
+
+
+def test_load_sealed_pickle_rejects_cross_domain(tmp_path):
+ path = tmp_path / "parse_cache.pkl"
+ dump_sealed_pickle(path, {"ok": True}, domain="parse_cache.pkl")
+ with pytest.raises(ValueError, match="HMAC"):
+ load_sealed_pickle(path, domain="centrality_cache.pkl")