From a95fe785a2ccf89599a1bdb174dbe1c332f43d98 Mon Sep 17 00:00:00 2001 From: Aljes Date: Fri, 4 Dec 2026 10:12:58 +0000 Subject: [PATCH 1/5] Check a Zarr store's codecs when it is opened zarr decodes a chunk with whatever codecs its array's metadata names, and numcodecs' pickle codec unpickles it. A Zarr v2 store naming it for a text array ran its author's code on the first read of that array: convert, subset, split, concat, recast and export dataframe did, with exit 0, and subset to Zarr carried the codec into its output. - storage.check_zarr_contents walks every array's metadata through the handle that reads its chunks (the consolidated index when zarr reads through one) and refuses a codec outside ZARR_V2_CODECS or ZARR_V3_CODECS, naming the array and the codec, before any chunk is read. open_store runs it for every mode but a fresh write. - copy_path checks both the hierarchy on disk and the consolidated index before it copies a store, and import's precheck checks the source it opens. - The v2 list is every numcodecs codec whose decode only compresses or transforms bytes, numbers or length-prefixed text: not pickle, nor json2 and msgpack2, which build Python objects in a shape the chunk names. The v3 list is zarr's own codecs and numcodecs' wrappers. - tests/test_zarr_safety.py: every command refuses a store whose payload would leave a marker; the codec as compressor or filter, in either metadata, or nested in a shard; anndata's v2 and sharded v3 stores still open; the check fetches metadata only. - Docs: Codecs read on the Zarr spec page, the refusal in troubleshooting, the new test file in the testing map. Co-Authored-By: Claude Opus 5.5 --- docs/reference/spec-zarr.md | 28 +++ docs/reference/testing.md | 1 + docs/troubleshooting.md | 14 ++ src/adata/commands/import_data.py | 12 +- src/adata/storage/__init__.py | 113 ++++++++++++ tests/test_zarr_safety.py | 287 ++++++++++++++++++++++++++++++ 6 files changed, 453 insertions(+), 2 deletions(-) create mode 100644 tests/test_zarr_safety.py diff --git a/docs/reference/spec-zarr.md b/docs/reference/spec-zarr.md index a7b8f21..5225ade 100644 --- a/docs/reference/spec-zarr.md +++ b/docs/reference/spec-zarr.md @@ -398,6 +398,34 @@ produces) and `FixedLengthUTF32` (what ` Iterator[Any]: if detect_backend(file) == "zarr": import zarr - yield zarr.open_group(str(file), mode="r", use_consolidated=False) + root = zarr.open_group(str(file), mode="r", use_consolidated=False) + check_zarr_contents(root, file) + yield root return with h5py.File(file, "r") as handle: yield handle diff --git a/src/adata/storage/__init__.py b/src/adata/storage/__init__.py index e5d78c4..2fe4dbd 100644 --- a/src/adata/storage/__init__.py +++ b/src/adata/storage/__init__.py @@ -274,6 +274,10 @@ def open_store( target = str(path) root = zarr.open_group(target, mode=mode, **kwargs) + if mode not in ("w", "w-", "x"): + # Anything opened for its contents, read or appended to: checked + # through the metadata this handle reads chunks with. + check_zarr_contents(root, path) if writable: ensure_anndata_root_attrs(root) elif require_anndata: @@ -464,6 +468,114 @@ def check_hdf5_inputs(path: Path) -> None: check_hdf5_file(file) +class ZarrCodecError(ValueError): + """A Zarr store names a codec this tool does not decode.""" + + +#: The Zarr v2 codec ids a store may name, as its compressor or a filter. +#: Each only transforms bytes or numbers, or reads length-prefixed text. +#: numcodecs registers three more: `pickle` unpickles every chunk it decodes, +#: which runs whatever the store's author put in it, and `json2` and +#: `msgpack2` build Python objects in a shape the chunk itself names. +#: anndata writes none of them, so a store naming one is refused. +ZARR_V2_CODECS = frozenset({ + "adler32", "astype", "base64", "bitround", "blosc", "bz2", "categorize", + "crc32", "crc32c", "delta", "fixedscaleoffset", "fletcher32", "gzip", + "jenkins_lookup3", "lz4", "lzma", "packbits", "pcodec", "quantize", + "shuffle", "vlen-array", "vlen-bytes", "vlen-utf8", "zfpy", "zlib", "zstd", +}) + +#: The Zarr v3 codec names a store may name: zarr's own, and numcodecs' +#: wrappers of the codecs above. zarr resolves no codec for v3 that runs code; +#: the list keeps a plugin from adding one. +ZARR_V3_CODECS = frozenset({ + "blosc", "bytes", "cast_value", "crc32c", "endian", "gzip", "scale_offset", + "sharding_indexed", "transpose", "vlen-bytes", "vlen-utf8", "zstd", + "numcodecs.adler32", "numcodecs.astype", "numcodecs.bitround", + "numcodecs.blosc", "numcodecs.bz2", "numcodecs.crc32", "numcodecs.crc32c", + "numcodecs.delta", "numcodecs.fixedscaleoffset", "numcodecs.fletcher32", + "numcodecs.gzip", "numcodecs.jenkins_lookup3", "numcodecs.lz4", + "numcodecs.lzma", "numcodecs.packbits", "numcodecs.pcodec", + "numcodecs.quantize", "numcodecs.shuffle", "numcodecs.zfpy", + "numcodecs.zlib", "numcodecs.zstd", +}) + + +def _codec_name(codec: Any, key: str) -> str: + """A codec's name as its metadata spells it: `id` in v2, `name` in v3. + + Anything else, such as a codec with no name, comes back as its repr, + which no list holds, so it is refused. + """ + if isinstance(codec, str): + return codec + name = codec.get(key) if isinstance(codec, dict) else None + return name if isinstance(name, str) else repr(codec) + + +def _v3_codec_names(codecs: Any) -> Iterator[str]: + """Every codec a v3 array names, with the codecs a shard nests.""" + for codec in codecs or (): + yield _codec_name(codec, "name") + config = codec.get("configuration") if isinstance(codec, dict) else None + if isinstance(config, dict): + yield from _v3_codec_names(config.get("codecs")) + yield from _v3_codec_names(config.get("index_codecs")) + + +def _codecs_of(array: Any) -> tuple: + """The codec names an array's metadata gives, and the list they must be on.""" + meta = array.metadata.to_dict() + if meta.get("zarr_format") == 2: + codecs = [meta.get("compressor")] if meta.get("compressor") is not None else [] + codecs.extend(meta.get("filters") or ()) + return [_codec_name(c, "id") for c in codecs], ZARR_V2_CODECS + return list(_v3_codec_names(meta.get("codecs"))), ZARR_V3_CODECS + + +def check_zarr_contents(group: Any, path: Any = None) -> None: + """Refuse a Zarr store that names a codec this tool does not decode. + + zarr decodes a chunk with whatever codecs its array's metadata names, + and numcodecs' `pickle` codec unpickles it: a store naming it runs its + author's code on the first read of that array, in any reader. Every + array below `group` is looked at once, through the metadata this handle + reads chunks with (the consolidated index when it reads through one), + and nothing is read from a chunk. A codec outside `ZARR_V2_CODECS` or + `ZARR_V3_CODECS` refuses the store, so none is ever decoded or copied + into an output. + """ + for name, node in group.members(max_depth=None): + if not is_zarr_array(node): + continue + names, allowed = _codecs_of(node) + for codec in names: + if codec in allowed: + continue + if codec == "pickle": + reason = "names the 'pickle' codec, which runs code when a chunk is decoded" + else: + reason = f"names the codec {codec!r}, which adata does not decode" + source = f"'{path}'" if path is not None else "The input" + raise ZarrCodecError( + f"{source} is refused: {name} {reason}. adata reads only Zarr " + "codecs that compress or transform bytes, numbers and text." + ) + + +def check_zarr_store(path: Path) -> None: + """`check_zarr_contents` for a store copied as files. + + A copy carries both the hierarchy on disk and the consolidated index, + and a reader of the copy may use either, so both are checked. + """ + _require_zarr() + for consolidated in (False, None): + check_zarr_contents( + zarr.open_group(str(path), mode="r", use_consolidated=consolidated), path + ) + + def zarr_format_of(obj: Any) -> Optional[int]: """The Zarr spec version (2 or 3) backing `obj`, or None for HDF5.""" return getattr(getattr(obj, "metadata", None), "zarr_format", None) @@ -1780,6 +1892,7 @@ def copy_path(src: Path, dst: Path) -> None: if is_zarr_path(src): if dst.exists(): raise FileExistsError(f"Destination '{dst}' already exists.") + check_zarr_store(src) shutil.copytree(src, dst) return shutil.copy2(src, dst) diff --git a/tests/test_zarr_safety.py b/tests/test_zarr_safety.py new file mode 100644 index 0000000..02034b9 --- /dev/null +++ b/tests/test_zarr_safety.py @@ -0,0 +1,287 @@ +"""Zarr stores that name a codec adata does not decode are refused. + +zarr decodes a chunk with whatever codecs its array's metadata names, and +numcodecs' `pickle` codec unpickles it, so a Zarr v2 store naming it ran its +author's code on the first read of that array. These stores carry a payload +that only creates a marker file and returns the bytes the next codec +expects: the marker is the oracle. Every store anndata writes must still +open. +""" + +from __future__ import annotations + +import json +import pickle +import re +from pathlib import Path + +import numpy as np +import pytest +from typer.testing import CliRunner + +from adata.cli import app +from adata.storage import ( + ZARR_V2_CODECS, + ZarrCodecError, + check_zarr_store, + copy_path, + open_store, +) + +zarr = pytest.importorskip("zarr") +ad = pytest.importorskip("anndata") + +runner = CliRunner() + +NAMES = ["c0", "c1", "c2", "c3"] + + +def _out(result) -> str: + text = result.stdout + (result.stderr or "") + return " ".join(re.sub(r"\x1b\[[0-9;]*[a-zA-Z]", "", text).split()) + + +class _Payload: + """Unpickled by zarr in place of a chunk: creates `marker`, then returns + the obs names as the vlen-utf8 filter after it expects them.""" + + def __init__(self, marker: Path): + self.marker = str(marker) + + def __reduce__(self): + code = ( + f"(__import__('pathlib').Path({self.marker!r}).touch()," + "__import__('numcodecs').VLenUTF8().encode(" + f"__import__('numpy').array({NAMES!r}, dtype=object)))[1]" + ) + return (eval, (code,)) + + +def _anndata_v2(path: Path) -> Path: + a = ad.AnnData(X=np.arange(12, dtype="float32").reshape(4, 3)) + a.obs_names = NAMES + a.var_names = ["g0", "g1", "g2"] + a.obs["grp"] = ["a", "a", "b", "b"] + with ad.settings.override(zarr_write_format=2): + a.write_zarr(path) + return path + + +def _index_array(store: Path) -> Path: + """obs's index array: `obs/_index`, or its `values` where anndata 0.13 + writes a nullable string array.""" + target = store / "obs" / "_index" + return target if (target / ".zarray").exists() else target / "values" + + +def _set_codecs(store: Path, compressor, filters, *, files: str = "both") -> Path: + """Give obs's index array these codecs, in its .zarray, the consolidated + index, or both (`files` is "zarray", "zmetadata" or "both").""" + target = _index_array(store) + meta = json.loads((target / ".zarray").read_text()) + meta["chunks"] = [len(NAMES)] + meta["compressor"] = compressor + meta["filters"] = filters + if files in ("both", "zarray"): + (target / ".zarray").write_text(json.dumps(meta)) + if files in ("both", "zmetadata"): + index = json.loads((store / ".zmetadata").read_text()) + index["metadata"][f"{target.relative_to(store).as_posix()}/.zarray"] = meta + (store / ".zmetadata").write_text(json.dumps(index)) + return store + + +def _poison(store: Path, marker: Path, *, where: str = "compressor", + files: str = "both") -> Path: + """Make obs's index name the pickle codec and hold the payload, with the + codec as the compressor or a filter.""" + target = _index_array(store) + for f in target.iterdir(): + if not f.name.startswith("."): + f.unlink() + (target / "0").write_bytes(pickle.dumps(_Payload(marker))) + pickled = {"id": "pickle", "protocol": 5} + if where == "compressor": + return _set_codecs(store, pickled, [{"id": "vlen-utf8"}], files=files) + return _set_codecs(store, None, [{"id": "vlen-utf8"}, pickled], files=files) + + +@pytest.fixture +def marker(tmp_path): + path = tmp_path / "MARKER_code_ran" + yield path + assert not path.exists(), "the store's payload ran" + + +@pytest.mark.parametrize("where", ["compressor", "filter"]) +def test_a_store_naming_the_pickle_codec_is_refused_on_opening(tmp_path, marker, where): + """F165: a Zarr v2 store whose array named numcodecs' pickle codec was + opened like any other, and its first read ran the payload.""" + store = _poison(_anndata_v2(tmp_path / "evil.zarr"), marker, where=where) + for mode in ("r", "r+", "a"): + with pytest.raises(ZarrCodecError, match=r"obs/_index\S* names the 'pickle' codec"): + open_store(store, mode) + + +def test_each_handle_is_checked_through_the_metadata_it_reads_with(tmp_path, marker): + """F165: a read goes through the consolidated index, a write through the + hierarchy on disk, and a copy carries both: a codec hidden in either is + refused where it would be used.""" + only_disk = _poison(_anndata_v2(tmp_path / "disk.zarr"), marker, files="zarray") + with open_store(only_disk, "r") as s: + # The index names the codecs anndata wrote: they cannot decode a + # pickle, so the read fails, and nothing runs. + with pytest.raises(Exception): + s.root[_index_array(only_disk).relative_to(only_disk).as_posix()][...] + with pytest.raises(ZarrCodecError): + open_store(only_disk, "a") + with pytest.raises(ZarrCodecError): + check_zarr_store(only_disk) + + only_index = _poison(_anndata_v2(tmp_path / "index.zarr"), marker, files="zmetadata") + with pytest.raises(ZarrCodecError): + open_store(only_index, "r") + with pytest.raises(ZarrCodecError): + check_zarr_store(only_index) + + +def test_a_store_without_a_consolidated_index_is_checked_on_disk(tmp_path, marker): + store = _poison(_anndata_v2(tmp_path / "plain.zarr"), marker, files="zarray") + (store / ".zmetadata").unlink() + with pytest.raises(ZarrCodecError): + open_store(store, "r") + + +COMMANDS = { + "ls": ["ls", "{src}"], + "view": ["view", "{src}"], + "convert-h5ad": ["convert", "{src}", "-o", "{tmp}/out.h5ad"], + "convert-zarr": ["convert", "{src}", "-o", "{tmp}/out.zarr"], + "subset": ["subset", "{src}", "--obs", "{tmp}/keep.txt", "-o", "{tmp}/out.zarr"], + "split": ["split", "{src}", "--by", "grp", "-o", "{tmp}/out"], + "concat": ["concat", "{src}", "{src2}", "-o", "{tmp}/out.zarr"], + "recast": ["recast", "{src}", "X", "--dtype", "float64", "-o", "{tmp}/out.zarr"], + "export-dataframe": ["export", "dataframe", "{src}", "obs", "-o", "{tmp}/out.csv"], + "export-array": ["export", "array", "{src}", "X", "-o", "{tmp}/out.npy"], + "import-dict": ["import", "dict", "{src}", "uns/extra", "{tmp}/extra.json", "-o", "{tmp}/out.zarr"], + "import-array": ["import", "array", "{src}", "obs/score", "{tmp}/score.npy", "-o", "{tmp}/out.zarr"], +} + + +@pytest.mark.parametrize("command", list(COMMANDS.values()), ids=list(COMMANDS)) +def test_every_command_refuses_a_store_naming_the_pickle_codec(tmp_path, marker, command): + """F165: convert, subset, split, concat, recast and export dataframe ran + the payload with exit 0, and subset to Zarr carried the pickle codec + into its output.""" + src = _poison(_anndata_v2(tmp_path / "evil.zarr"), marker) + src2 = _anndata_v2(tmp_path / "other.zarr") + (tmp_path / "keep.txt").write_text("c1\nc2\n") + (tmp_path / "extra.json").write_text('{"a": 1}') + np.save(tmp_path / "score.npy", np.arange(4, dtype="float64")) + result = runner.invoke(app, [a.format(src=src, src2=src2, tmp=tmp_path) for a in command]) + assert result.exit_code == 1, _out(result) + assert "is refused" in _out(result) and "'pickle' codec" in _out(result) + assert not list(tmp_path.glob("out*")), "a refused store left an output" + + +def test_a_refused_store_is_never_copied(tmp_path, marker): + store = _poison(_anndata_v2(tmp_path / "evil.zarr"), marker) + with pytest.raises(ZarrCodecError): + copy_path(store, tmp_path / "copy.zarr") + assert not (tmp_path / "copy.zarr").exists() + + +def test_json2_is_named_in_the_refusal(tmp_path): + """json2 runs no code, but builds Python objects in a shape the chunk + names, and anndata never writes it.""" + store = _set_codecs(_anndata_v2(tmp_path / "s.zarr"), {"id": "json2"}, [{"id": "vlen-utf8"}]) + with pytest.raises(ZarrCodecError, match=r"obs/_index\S* names the codec 'json2', which adata does not decode"): + open_store(store, "r") + + +@pytest.mark.parametrize("codec", ["msgpack2", "a-codec-nobody-registered"]) +def test_a_codec_zarr_cannot_resolve_ends_in_one_error_line(tmp_path, codec): + """zarr refuses an id it cannot resolve while it reads the metadata, + before the check sees it (msgpack2 is registered only where msgpack is + installed, and then the check refuses it).""" + store = _set_codecs(_anndata_v2(tmp_path / "s.zarr"), {"id": codec}, [{"id": "vlen-utf8"}]) + result = runner.invoke(app, ["view", str(store)]) + assert result.exit_code == 1, _out(result) + assert _out(result).startswith("Error:") and "Traceback" not in _out(result) + + +@pytest.mark.parametrize("dropped", ["zstd", "crc32c"]) +def test_the_v3_walk_reaches_the_codecs_a_shard_nests(tmp_path, monkeypatch, dropped): + """zarr resolves no v3 codec that runs code; the list keeps a plugin + from adding one, and the walk reaches a shard's inner and index codecs.""" + import adata.storage as storage + + path = tmp_path / "s.zarr" + root = zarr.open_group(str(path), mode="w", zarr_format=3) + root.create_array( + "X", shape=(8, 8), chunks=(4, 4), shards=(8, 8), dtype="float32", + compressors=zarr.codecs.ZstdCodec(), + ) + assert [c["name"] for c in root["X"].metadata.to_dict()["codecs"]] == ["sharding_indexed"] + open_store(path, "r", require_anndata=False).close() + monkeypatch.setattr(storage, "ZARR_V3_CODECS", storage.ZARR_V3_CODECS - {dropped}) + with pytest.raises(ZarrCodecError, match=f"X names the codec '{dropped}'"): + open_store(path, "r", require_anndata=False) + + +@pytest.mark.parametrize("fmt", ["zarr2", "zarr3"]) +def test_every_store_anndata_writes_opens(tmp_path, fmt): + """The lists hold every codec anndata writes, for every kind of element.""" + import pandas as pd + from scipy import sparse + + from tests.perf_fixtures import write_anndata + + a = ad.AnnData( + X=sparse.random(20, 6, density=0.3, format="csr", dtype="float32", random_state=0), + obs=pd.DataFrame( + { + "cat": pd.Categorical(list("ab") * 10), + "num": np.arange(20.0), + "text": [f"t{i}" for i in range(20)], + "flag": [True, False] * 10, + "nullable": pd.array([1, None] * 10, dtype="Int64"), + }, + index=[f"c{i}" for i in range(20)], + ), + layers={"dense": np.ones((20, 6), dtype="int32")}, + obsm={"pca": np.zeros((20, 2))}, + uns={"names": np.array(["x", "y"], dtype=object), "nested": {"k": 1.5}}, + ) + store = write_anndata(a, tmp_path / f"s.{fmt}.zarr", fmt) + for mode in ("r", "a"): + open_store(store, mode).close() + check_zarr_store(store) + + +def test_the_check_reads_metadata_only(tmp_path, monkeypatch): + """The check walks metadata: a chunk read before the store is accepted + is the very read it exists to prevent.""" + from zarr.storage import LocalStore + + store = _anndata_v2(tmp_path / "s.zarr") + (store / ".zmetadata").unlink() # so the walk fetches every .zarray + fetched = [] + original = LocalStore.get + + async def get(self, key, *args, **kwargs): + fetched.append(key) + return await original(self, key, *args, **kwargs) + + monkeypatch.setattr(LocalStore, "get", get) + open_store(store, "r").close() + check_zarr_store(store) + names = {Path(k).name for k in fetched} + assert names <= {".zarray", ".zattrs", ".zgroup", ".zmetadata", "zarr.json"}, names + assert ".zarray" in names + + +def test_the_v2_list_names_no_codec_that_builds_objects(): + """pickle runs code; json2 and msgpack2 build objects in a shape the + chunk names. Letting one in must be a deliberate change here.""" + assert not {"pickle", "json2", "msgpack2"} & ZARR_V2_CODECS From ba187ceba2c5d1892e3af4a37dcbfbc6a7ce230e Mon Sep 17 00:00:00 2001 From: Aljes Date: Fri, 4 Dec 2026 10:12:58 +0000 Subject: [PATCH 2/5] Release 0.17.9 A Zarr store naming a codec adata does not decode is refused when it is opened; numcodecs' pickle codec ran a crafted store's code on read. - pyproject.toml and uv.lock at 0.17.9. - docs/changelog.md: a 0.17.9 section (Fixed). - STATUS.md: 0.17.9 released; the December audit in progress, its epic to follow the release; the Zarr hardening follow-up narrowed to what remains. Co-Authored-By: Claude Opus 5.5 --- STATUS.md | 16 ++++++++++------ docs/changelog.md | 29 +++++++++++++++++++++++++++++ pyproject.toml | 2 +- uv.lock | 2 +- 4 files changed, 41 insertions(+), 8 deletions(-) diff --git a/STATUS.md b/STATUS.md index 68a6c42..964ac1a 100644 --- a/STATUS.md +++ b/STATUS.md @@ -7,6 +7,7 @@ moves; the plan of record for the current item is in the section below. | Version | What | Issues | |---|---|---| +| 0.17.9 | A Zarr store naming a codec adata does not decode is refused when opened: numcodecs' `pickle`, which a v2 store could name for any text array, ran its author's code on the first read | #PR | | 0.17.8 | Sparse matrices read at least 32 MiB at a time (`subset` of a narrow matrix on Lustre in a quarter of the time); no numpy huge pages, which stalled writes on nodes with fragmented memory; Performance on cluster storage page and the `benchmarks/lustre/` probe | #129, #130 | | 0.17.7 | `import dataframe --categorical` keeps numeric-looking labels (leiden's 0, 1, 10) as categoricals of their text; `convert --feature-type` / `--split-feature-types` take a 10x input with no feature types (Cell Ranger 2) as gene expression; every tag gets its GitHub release from the changelog | #124, #127, #114 | | 0.17.6 | Audit fixes, waves 3 and 4 (streaming): reads and writes follow the source's chunks and Zarr v3 shards, each shard written once; `recast` checks and converts in `--chunk` blocks; `split`'s memory no longer grows with its groups; pickle arrays checked before use; 16-bit images export as they are; plain-line logs and names printed as stored; h5py >= 3.16 | #96, #97, #101, #103 | @@ -28,10 +29,13 @@ The conversion epic's sub-issues (#21–#30) are all done and ticked in #20. ## In progress -Nothing. The fixes from the October 2026 audit (epic #87, 164 findings in 16 -batches) finished with 0.17.6; the sub-issues (#88–#103) are all done and -ticked in #87. The batch names in the follow-ups below (B1 to B10) are -theirs. +The December 2026 audit of 0.17.8 (85 findings). Its hotfix, B0, is 0.17.9; +the epic with the other batches is filed once 0.17.9 is out, and the +follow-ups it covers move there. + +The fixes from the October 2026 audit (epic #87, 164 findings in 16 batches) +finished with 0.17.6; the sub-issues (#88–#103) are all done and ticked in +#87. The batch names in the follow-ups below (B1 to B10) are theirs. ## Follow-ups noticed @@ -110,8 +114,8 @@ theirs. base image to Debian trixie; a Codecov token (B9). - Repository settings: the default workflow token can write, and the `pypi` environment has no protection rules (B9). - - Zarr stores need a counterpart to the HDF5 hardening in 0.17.5, outside - that fix's scope (B5). + - Zarr stores: their codecs are checked since 0.17.9; the rest of the + counterpart to the HDF5 hardening in 0.17.5 is in the December audit. - Flex's `target_sets` group is not carried, and `--make-unique` names export with their suffixes (B8a). - `formats/textio.py` does not unquote a field that starts with `"`, as diff --git a/docs/changelog.md b/docs/changelog.md index b7d9e5c..5d23ec8 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -8,6 +8,35 @@ nav_order: 7 Notable changes to `adata-cli`. Versions are `MAJOR.MINOR.PATCH`; tags carry no `v` prefix. +## 0.17.9 + +A security fix: upgrade if you open Zarr stores that someone else wrote. A +Zarr v2 store can tell zarr to decode any text array with numcodecs' +`pickle` codec, which unpickles each chunk and so runs whatever code the +store's author put there. `subset`, `split`, `concat`, `recast`, `convert` +and `export` read such a store as asked and ran that code, and `subset` to +Zarr carried the codec into its output. Every release that reads Zarr did. +A store is now checked when it is opened, and one naming a codec `adata` +does not decode is refused before any chunk is read. + +### Fixed + +- **A Zarr store naming the `pickle` codec, or any codec adata does not + decode, is refused** ([#PR](https://github.com/cellgeni/adata-cli/pull/PR)). + zarr decodes a chunk with whatever codecs its array's metadata names, and + zarr-python and anndata run a pickled chunk the same way. Each store is + checked through the metadata a read uses: the consolidated index when it + is read through one, the hierarchy on disk when it is written to, and both + when it is copied as files. A codec outside the list of those that + compress or transform bytes, numbers and text refuses the store, naming + the array and the codec, before anything is read or copied. `json2` and + `msgpack2`, which build Python objects in a shape the chunk names, are + refused too; anndata writes none of them. The + [Zarr specification](https://cellgeni.github.io/adata-cli/reference/spec-zarr/#codecs-read) + lists the codecs read, and + [troubleshooting](https://cellgeni.github.io/adata-cli/troubleshooting/) + what to do with a store that is refused. + ## 0.17.8 Faster on a cluster's shared filesystem. A sparse matrix is read at least diff --git a/pyproject.toml b/pyproject.toml index b860dd9..261c250 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,7 @@ # so the distribution is published as `pyadata-cli`. The import package # and the command are both still `adata`. name = "pyadata-cli" -version = "0.17.8" +version = "0.17.9" description = "Streaming CLI for exploring and editing large AnnData .h5ad and .zarr stores" readme = "README.md" requires-python = ">=3.12" diff --git a/uv.lock b/uv.lock index 5f29776..ae8ad01 100644 --- a/uv.lock +++ b/uv.lock @@ -570,7 +570,7 @@ wheels = [ [[package]] name = "pyadata-cli" -version = "0.17.8" +version = "0.17.9" source = { editable = "." } dependencies = [ { name = "h5py" }, From 76cf1926d9b949712679da9288c61a67767f5819 Mon Sep 17 00:00:00 2001 From: Aljes Date: Fri, 4 Dec 2026 10:51:02 +0000 Subject: [PATCH 3/5] Review fixes: zarr cannot build a codec off the lists The walk at opening saw only the arrays zarr lists, and zarr reads more: a path looked up in one go reached an array below a folder with no group metadata, or one hidden by an index a group's metadata embeds, and `export array` and `concat` ran the payload that way with exit 0; metadata re-read after the check was decoded as it then said; and a copy could carry a codec only the files on disk named. - restrict_zarr_codecs, run when adata.storage is imported: every codec id off the lists resolves, in numcodecs' registry and zarr's, to a class that refuses to be built, and numcodecs' get_codec and zarr's get_codec_class (with the name zarr's v3 parser imported) refuse such an id even if it is registered later. This is the layer that holds. - open_store keeps its walk for the message, and when zarr refuses while parsing, reads the store's metadata files to name the array. - check_zarr_store reads every metadata file a copy would carry as JSON (the arrays' own, the consolidated index, any index a group's metadata embeds), through linked folders as the copy goes; one that is not JSON is refused. - The walk no longer prints zarr's warning about a stray file. - Tests: an array no listing shows, two ways; metadata changed after opening; each metadata file a copy carries; the registries refuse and a second run changes nothing; a refusal is one Error: line. - AGENTS.md and developers.md: the rule; the spec, troubleshooting and changelog describe both layers. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 11 +- docs/changelog.md | 13 +- docs/developers.md | 12 +- docs/reference/spec-zarr.md | 26 ++-- docs/reference/testing.md | 2 +- docs/troubleshooting.md | 6 +- src/adata/storage/__init__.py | 246 ++++++++++++++++++++++++++++------ tests/test_zarr_safety.py | 222 +++++++++++++++++++++++++----- 8 files changed, 442 insertions(+), 96 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 095e1b8..7830f26 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -122,7 +122,8 @@ uses `elements/` (the spec, `strings`, and the readers and writers that `docs/reference/spec-zarr.md`. - **`storage/`**: hides whether a store is h5py or zarr. - `open_store(path, mode, zarr_format=...)` detects the backend from the - path and returns a `Store`. + path and returns a `Store`. It refuses an HDF5 file reading data from + elsewhere and a Zarr store naming a codec off the lists, before reading. - On close, a writable Zarr `Store` rewrites the consolidated metadata. Without that, anndata reads a stale index and new members look missing. - Use the `is_group`/`is_dataset`/`create_dataset`/`copy_tree` helpers here @@ -197,6 +198,14 @@ These are easy to break without any test noticing straight away: incomplete store, so it must reach staging, which then discards it. Only a close made while another exception propagates (`__exit__`) stays quiet. Never catch and drop an error from closing a store you wrote. +- **zarr builds only the codecs on the lists.** Importing `adata.storage` + runs `restrict_zarr_codecs`, which keeps numcodecs and zarr, in this + process, from building a codec outside `ZARR_V2_CODECS` or + `ZARR_V3_CODECS`: numcodecs' `pickle` codec unpickles each chunk, which + runs whatever code the store's author put there. That is the layer that + holds; `open_store` and `copy_path` also refuse such a store up front, so + the message can name the array. Widen a list only after reading the + codec's `decode()`, and never for one that builds Python objects. - **Check the output before opening anything**, with `util/path.output_target` (commands with `--inplace`) or `check_output`. They refuse an output that is the input under any alias (`same_path` asks diff --git a/docs/changelog.md b/docs/changelog.md index 5d23ec8..6b346f0 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -24,12 +24,13 @@ does not decode is refused before any chunk is read. - **A Zarr store naming the `pickle` codec, or any codec adata does not decode, is refused** ([#PR](https://github.com/cellgeni/adata-cli/pull/PR)). zarr decodes a chunk with whatever codecs its array's metadata names, and - zarr-python and anndata run a pickled chunk the same way. Each store is - checked through the metadata a read uses: the consolidated index when it - is read through one, the hierarchy on disk when it is written to, and both - when it is copied as files. A codec outside the list of those that - compress or transform bytes, numbers and text refuses the store, naming - the array and the codec, before anything is read or copied. `json2` and + zarr-python and anndata run a pickled chunk the same way. `adata` now + keeps numcodecs and zarr from building any codec outside a list of those + that compress or transform bytes, numbers and text, whatever metadata + names it and whenever it is read. A store is also checked when it is + opened, through the metadata each read uses, and every metadata file in it + before it is copied, and one naming such a codec is refused before + anything is read or copied, naming the array and the codec. `json2` and `msgpack2`, which build Python objects in a shape the chunk names, are refused too; anndata writes none of them. The [Zarr specification](https://cellgeni.github.io/adata-cli/reference/spec-zarr/#codecs-read) diff --git a/docs/developers.md b/docs/developers.md index 259a020..81f2abd 100644 --- a/docs/developers.md +++ b/docs/developers.md @@ -85,8 +85,10 @@ element faithfully). `write.py` always writes the current one; `strings.py` reconciles how HDF5 and Zarr spell text. - **`storage/`** hides the backend. `open_store(path, mode, zarr_format=...)` - returns a `Store`; use its `is_group`, `is_dataset`, `create_dataset` and - `copy_tree` rather than branching on h5py or zarr. + returns a `Store`, refusing an HDF5 file that reads data from elsewhere and + a Zarr store that names a codec off the lists; use its `is_group`, + `is_dataset`, `create_dataset` and `copy_tree` rather than branching on + h5py or zarr. ### Adding a format to `convert` @@ -129,6 +131,12 @@ before changing anything that writes: - **`Store.close` raises.** A failed HDF5 flush or Zarr consolidation leaves an incomplete store; raising it is what lets staging discard it. It stays quiet only while another exception propagates. +- **zarr builds only the codecs on the lists.** Importing `adata.storage` + keeps numcodecs and zarr from building any codec outside `ZARR_V2_CODECS` + or `ZARR_V3_CODECS` in the process (`restrict_zarr_codecs`): numcodecs' + `pickle` codec runs whatever code a store's author put in a chunk. + `open_store` and `copy_path` refuse such a store up front too, naming the + array. Widen a list only after reading the codec's `decode()`. - **Check the output before opening anything**, with `util/path.output_target` (for commands with `--inplace`) or `check_output`. One check for every writer: the output may not be the diff --git a/docs/reference/spec-zarr.md b/docs/reference/spec-zarr.md index 5225ade..bbaeae8 100644 --- a/docs/reference/spec-zarr.md +++ b/docs/reference/spec-zarr.md @@ -404,10 +404,24 @@ zarr decodes a chunk with whatever codecs its array's metadata names. One of the codecs numcodecs registers for v2, `pickle`, unpickles each chunk, and unpickling runs whatever code the store's author put there: reading such a store with zarr-python, or with anndata, runs it. So this tool decodes only -codecs that compress or transform bytes, numbers and text, and a store -naming any other is refused when it is opened, naming the array and the -codec, before any chunk is read. A store refused this way is never copied -either, so no output carries the codec on. +codecs that compress or transform bytes, numbers and text, and keeps to +that at two levels: + +- **Whenever a codec is built.** Once `adata` starts, numcodecs and zarr + cannot build any other codec in its process, whatever metadata names it + and whenever it is read: an array zarr reaches without listing it (a path + looked up in one go, an index a group's metadata embeds) or metadata + changed after the store was opened is refused as it is read, as `A Zarr + store is refused: one of its arrays names ...`. +- **When a store is opened or copied.** Every array zarr lists is checked + through the metadata that read uses (the consolidated index when it reads + through one, the hierarchy on disk when it writes), and a store copied as + files has every metadata file in it read first: the arrays' own, the + consolidated index, and any index a group's metadata embeds. A store + naming another codec is refused before any chunk is read, naming the + array and the codec, so no output carries the codec on. + +The codecs read: - **v2** (`compressor` and `filters`): `adler32`, `astype`, `base64`, `bitround`, `blosc`, `bz2`, `categorize`, `crc32`, `crc32c`, `delta`, @@ -422,10 +436,6 @@ either, so no output carries the codec on. numcodecs' `numcodecs.*` wrappers of the v2 codecs above. zarr resolves no v3 codec that runs code; the list keeps a plugin from adding one. -The metadata checked is the metadata each read uses: the consolidated index -when the store is read through one, the hierarchy on disk when it is written -to, and both when it is copied as files. - ## Sources - AnnData “on-disk format” prose docs (modern, ≥0.8): https://anndata.readthedocs.io/en/stable/fileformat-prose.html diff --git a/docs/reference/testing.md b/docs/reference/testing.md index 5b3b3f9..1dcd98e 100644 --- a/docs/reference/testing.md +++ b/docs/reference/testing.md @@ -59,7 +59,7 @@ inside every release before PyPI has it. |---|---| | `test_elements.py` | The element layer — encodings, string dtypes, readers and writers — run against HDF5, Zarr v2 and Zarr v3 | | `test_storage.py` | Backend detection, copying, Zarr versions, consolidated metadata | -| `test_zarr_safety.py` | Zarr stores naming a codec adata does not decode refused by every command before any chunk is read, whichever metadata names it (the consolidated index, the hierarchy on disk, a shard's nested codecs); numcodecs' `pickle` codec, whose stores carry a payload that leaves a marker if it runs; every store anndata writes still opens | +| `test_zarr_safety.py` | Zarr stores naming a codec adata does not decode, refused before the payload can run (it leaves a marker if it does): by every command when the store is opened, when an array no listing shows is read, when its metadata changes after opening, and before a copy, whichever metadata file names it; numcodecs and zarr unable to build such a codec once `adata.storage` is imported; every store anndata writes still opens | | `test_storage_root_attrs.py` | The root's AnnData attributes: written when a store is opened for writing, and a warning on reading a store that lacks them, though not for anndata 0.7's layout, which never had them | | `test_staging.py` | `util/staging.py` on its own: write beside and rename into place, several outputs together, a failed swap put back, leftovers refused rather than deleted | | `test_write_safety.py` | Every way a command used to destroy or corrupt a store while reporting success, or leave a half-written one: outputs that alias the input, failed selections, `--inplace`, failed closes, a full disk, two runs on one output, SIGTERM | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 51f1781..0b927b3 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -319,8 +319,10 @@ codec, and unpickling a chunk runs whatever code its author put there. anndata never writes it. Do not open the store with zarr-python or anndata either: they decode it as asked. A codec named `json2`, `msgpack2` or one adata does not know is refused the same way, as `... names the codec -'json2', which adata does not decode`. The codecs adata reads are listed in -the [Zarr specification](reference/spec-zarr.md#codecs-read). +'json2', which adata does not decode`. An array zarr reaches without +listing it is refused only when it is read, and the message cannot name it: +`A Zarr store is refused: one of its arrays names ...`. The codecs adata +reads are listed in the [Zarr specification](reference/spec-zarr.md#codecs-read). If the store is your own, from a pipeline that once wrote text with that codec, rewrite the array with `numcodecs.VLenUTF8()` in Python, where you diff --git a/src/adata/storage/__init__.py b/src/adata/storage/__init__.py index 2fe4dbd..a560fa4 100644 --- a/src/adata/storage/__init__.py +++ b/src/adata/storage/__init__.py @@ -2,6 +2,7 @@ from dataclasses import dataclass from pathlib import Path +from collections.abc import Mapping from typing import Any, Iterable, Iterator, Optional, Sequence import shutil import warnings @@ -273,11 +274,22 @@ def open_store( else: target = str(path) - root = zarr.open_group(target, mode=mode, **kwargs) - if mode not in ("w", "w-", "x"): - # Anything opened for its contents, read or appended to: checked - # through the metadata this handle reads chunks with. - check_zarr_contents(root, path) + try: + root = zarr.open_group(target, mode=mode, **kwargs) + if mode not in ("w", "w-", "x"): + # Anything opened for its contents, read or appended to: + # every array zarr lists, through the metadata this handle + # reads chunks with, before any chunk is read. + check_zarr_contents(root, path) + except ZarrCodecError as error: + # zarr refuses a codec off the lists while it parses metadata + # (restrict_zarr_codecs), before the walk can name the array: + # the store's metadata files say which one it is. + if path.is_dir(): + check_zarr_store(path) + raise _codec_error( + f"'{path}'", "one of its arrays", getattr(error, "codec", "?") + ) from error if writable: ensure_anndata_root_attrs(root) elif require_anndata: @@ -501,6 +513,25 @@ class ZarrCodecError(ValueError): }) +#: The files a Zarr store keeps metadata in: an array's own, the +#: consolidated index, a group's own (which can embed an index of the +#: members below it), and v3's for every node. +ZARR_METADATA_FILES = frozenset({".zarray", ".zgroup", ".zmetadata", "zarr.json"}) + + +def _codec_error(source: str, where: str, codec: str) -> ZarrCodecError: + if codec == "pickle": + reason = "names the 'pickle' codec, which runs code when a chunk is decoded" + else: + reason = f"names the codec {codec!r}, which adata does not decode" + error = ZarrCodecError( + f"{source} is refused: {where} {reason}. adata reads only Zarr codecs " + "that compress or transform bytes, numbers and text." + ) + error.codec = codec # type: ignore[attr-defined] + return error + + def _codec_name(codec: Any, key: str) -> str: """A codec's name as its metadata spells it: `id` in v2, `name` in v3. @@ -523,57 +554,194 @@ def _v3_codec_names(codecs: Any) -> Iterator[str]: yield from _v3_codec_names(config.get("index_codecs")) -def _codecs_of(array: Any) -> tuple: - """The codec names an array's metadata gives, and the list they must be on.""" - meta = array.metadata.to_dict() - if meta.get("zarr_format") == 2: - codecs = [meta.get("compressor")] if meta.get("compressor") is not None else [] +def _off_the_list(meta: dict, zarr_format: int) -> Optional[str]: + """The first codec one array's metadata names that is not on its list.""" + if zarr_format == 2: + codecs = [meta["compressor"]] if meta.get("compressor") is not None else [] codecs.extend(meta.get("filters") or ()) - return [_codec_name(c, "id") for c in codecs], ZARR_V2_CODECS - return list(_v3_codec_names(meta.get("codecs"))), ZARR_V3_CODECS + names, allowed = [_codec_name(c, "id") for c in codecs], ZARR_V2_CODECS + else: + names, allowed = list(_v3_codec_names(meta.get("codecs"))), ZARR_V3_CODECS + return next((name for name in names if name not in allowed), None) + + +def _arrays_in(document: Any, key: str = "") -> Iterator[tuple]: + """Every array's metadata in a metadata file, with its Zarr version and + the key an index in the file lists it under: the file's own (key ""), + and the ones an index in it holds, at any depth.""" + if isinstance(document, dict): + if document.get("node_type") == "array": + yield document, 3, key + elif "chunks" in document and "dtype" in document and ( + "compressor" in document or "filters" in document + ): + yield document, 2, key + for name, value in document.items(): + yield from _arrays_in(value, name if isinstance(value, dict) else key) + elif isinstance(document, list): + for value in document: + yield from _arrays_in(value, key) def check_zarr_contents(group: Any, path: Any = None) -> None: - """Refuse a Zarr store that names a codec this tool does not decode. + """Refuse a Zarr store that names a codec this tool does not decode, + naming the array. zarr decodes a chunk with whatever codecs its array's metadata names, and numcodecs' `pickle` codec unpickles it: a store naming it runs its author's code on the first read of that array, in any reader. Every - array below `group` is looked at once, through the metadata this handle - reads chunks with (the consolidated index when it reads through one), - and nothing is read from a chunk. A codec outside `ZARR_V2_CODECS` or - `ZARR_V3_CODECS` refuses the store, so none is ever decoded or copied - into an output. + array zarr lists below `group` is looked at once, through the metadata + this handle reads chunks with (the consolidated index when it reads + through one), and nothing is read from a chunk. + + zarr reads more than it lists, so this is for the message: + `restrict_zarr_codecs` is what refuses a codec on an array this walk + cannot see. """ - for name, node in group.members(max_depth=None): + with warnings.catch_warnings(): + # Listing warns about a file that is not part of the hierarchy (a + # .DS_Store), which says nothing about the codecs. + warnings.simplefilter("ignore") + members = tuple(group.members(max_depth=None)) + for name, node in members: if not is_zarr_array(node): continue - names, allowed = _codecs_of(node) - for codec in names: - if codec in allowed: - continue - if codec == "pickle": - reason = "names the 'pickle' codec, which runs code when a chunk is decoded" - else: - reason = f"names the codec {codec!r}, which adata does not decode" + meta = node.metadata.to_dict() + codec = _off_the_list(meta, 2 if meta.get("zarr_format") == 2 else 3) + if codec is not None: source = f"'{path}'" if path is not None else "The input" - raise ZarrCodecError( - f"{source} is refused: {name} {reason}. adata reads only Zarr " - "codecs that compress or transform bytes, numbers and text." - ) + raise _codec_error(source, name, codec) def check_zarr_store(path: Path) -> None: - """`check_zarr_contents` for a store copied as files. + """Refuse a store about to be copied as files if any of its metadata + names a codec this tool does not decode. + + A copy carries every file, and a reader of the copy may use any of + them: an array's own metadata, the consolidated index, an index a + group's metadata embeds. So every metadata file is read as JSON, + through linked folders as the copy goes through them, and each array's + metadata in it is checked. A metadata file that is not JSON is refused + too: no reader could use it either. + """ + import json + import os + import posixpath + + path = Path(path) + seen = set() + for folder, subfolders, names in os.walk(path, followlinks=True): + real = os.path.realpath(folder) + if real in seen: + subfolders[:] = [] + continue + seen.add(real) + here = Path(folder).relative_to(path).as_posix() + for name in sorted(n for n in names if n in ZARR_METADATA_FILES): + file = posixpath.normpath(posixpath.join(here, name)) + try: + document = json.loads(Path(folder, name).read_bytes()) + except (ValueError, RecursionError) as error: + raise ZarrCodecError( + f"'{path}' is refused: {file} is not valid JSON ({error})." + ) from error + for meta, zarr_format, key in _arrays_in(document): + codec = _off_the_list(meta, zarr_format) + if codec is None: + continue + if key: + for suffix in ("/.zarray", "/zarr.json"): + key = key.removesuffix(suffix) + member = posixpath.normpath(posixpath.join(here, key)) + where = f"{member}, as {file} lists it," + else: + where = here if here != "." else "the root array" + raise _codec_error(f"'{path}'", where, codec) + + +def _refused_codec(codec: str) -> type: + """What a codec off the lists resolves to once `restrict_zarr_codecs` + has run: a class that refuses to be built, by numcodecs or by zarr.""" + + def refuse(*args: Any, **kwargs: Any) -> None: + raise _codec_error("A Zarr store", "one of its arrays", codec) + + return type( + f"Refused[{codec}]", + (), + { + "codec_id": codec, + "__init__": refuse, + "from_config": staticmethod(refuse), + "from_dict": staticmethod(refuse), + }, + ) + + +def restrict_zarr_codecs() -> None: + """Keep zarr from building a codec off the lists, in this process. - A copy carries both the hierarchy on disk and the consolidated index, - and a reader of the copy may use either, so both are checked. + `check_zarr_contents` sees only the arrays zarr lists, and zarr reads + more than it lists: a path looked up in one go reaches an array below a + folder with no group metadata, a group's metadata can embed an index + that stands in for the files below it, and metadata read again later + may have changed in the meantime. Every chunk is decoded by codecs + built from metadata through numcodecs' registry (v2) or zarr's (v3), so + each id off the lists is replaced there by a class that refuses to be + built, and the functions that build them refuse an id off the lists + even if it is registered later. Run once, when this module is imported; + running it again changes nothing. """ - _require_zarr() - for consolidated in (False, None): - check_zarr_contents( - zarr.open_group(str(path), mode="r", use_consolidated=consolidated), path - ) + try: + import numcodecs + import numcodecs.registry as v2 + except Exception: # pragma: no cover - zarr installs numcodecs + return + allowed_v2, allowed_v3 = ZARR_V2_CODECS, ZARR_V3_CODECS + entries = getattr(v2, "entries", {}) # the codecs other packages declare + for codec in set(v2.codec_registry) | set(entries): + if codec not in allowed_v2: + entries.pop(codec, None) + v2.codec_registry[codec] = _refused_codec(codec) + build = v2.get_codec + if not getattr(build, "adata_restricted", False): + + def get_codec(config: Any) -> Any: + codec = config.get("id") if isinstance(config, Mapping) else None + if codec not in allowed_v2: + raise _codec_error("A Zarr store", "one of its arrays", str(codec)) + return build(config) + + get_codec.adata_restricted = True # type: ignore[attr-defined] + v2.get_codec = numcodecs.get_codec = get_codec + if zarr is None: # pragma: no cover - zarr is a dependency + return + from zarr import registry as v3 + + for name, codecs in list(getattr(v3, "_codec_registries", {}).items()): + if name not in allowed_v3: + codecs.clear() + getattr(codecs, "lazy_load_list", []).clear() + codecs[f"adata.refused.{name}"] = _refused_codec(name) + resolve = getattr(v3, "get_codec_class", None) + if resolve is not None and not getattr(resolve, "adata_restricted", False): + + def get_codec_class(key: str, *args: Any, **kwargs: Any) -> Any: + if key not in allowed_v3: + raise _codec_error("A Zarr store", "one of its arrays", str(key)) + return resolve(key, *args, **kwargs) + + get_codec_class.adata_restricted = True # type: ignore[attr-defined] + v3.get_codec_class = get_codec_class + try: + from zarr.core.metadata import v3 as metadata_v3 + except Exception: # pragma: no cover - a zarr laid out otherwise + metadata_v3 = None + if getattr(metadata_v3, "get_codec_class", None) is resolve: + metadata_v3.get_codec_class = get_codec_class + + +restrict_zarr_codecs() def zarr_format_of(obj: Any) -> Optional[int]: diff --git a/tests/test_zarr_safety.py b/tests/test_zarr_safety.py index 02034b9..52b4abc 100644 --- a/tests/test_zarr_safety.py +++ b/tests/test_zarr_safety.py @@ -2,10 +2,13 @@ zarr decodes a chunk with whatever codecs its array's metadata names, and numcodecs' `pickle` codec unpickles it, so a Zarr v2 store naming it ran its -author's code on the first read of that array. These stores carry a payload -that only creates a marker file and returns the bytes the next codec -expects: the marker is the oracle. Every store anndata writes must still -open. +author's code on the first read of that array. Two layers keep it out: +importing `adata.storage` stops zarr from building any codec off the lists, +whatever metadata names it and whenever it is read; and `open_store` and +`copy_path` refuse such a store up front, naming the array. The crafted +stores carry a payload that only creates a marker file and returns the +bytes the next codec expects: the marker is the oracle. Every store anndata +writes must still open. """ from __future__ import annotations @@ -26,6 +29,7 @@ check_zarr_store, copy_path, open_store, + restrict_zarr_codecs, ) zarr = pytest.importorskip("zarr") @@ -34,6 +38,8 @@ runner = CliRunner() NAMES = ["c0", "c1", "c2", "c3"] +PICKLE = {"id": "pickle", "protocol": 5} +REFUSED = r"names the 'pickle' codec, which runs code when a chunk is decoded" def _out(result) -> str: @@ -41,18 +47,25 @@ def _out(result) -> str: return " ".join(re.sub(r"\x1b\[[0-9;]*[a-zA-Z]", "", text).split()) +def _error_lines(result) -> list: + """The non-blank lines on stderr: a refusal is one `Error:` line.""" + text = re.sub(r"\x1b\[[0-9;]*[a-zA-Z]", "", result.stderr or "") + return [line for line in text.splitlines() if line.strip()] + + class _Payload: """Unpickled by zarr in place of a chunk: creates `marker`, then returns - the obs names as the vlen-utf8 filter after it expects them.""" + `values` as the vlen-utf8 filter after it expects them.""" - def __init__(self, marker: Path): + def __init__(self, marker: Path, values): self.marker = str(marker) + self.values = list(values) def __reduce__(self): code = ( f"(__import__('pathlib').Path({self.marker!r}).touch()," "__import__('numcodecs').VLenUTF8().encode(" - f"__import__('numpy').array({NAMES!r}, dtype=object)))[1]" + f"__import__('numpy').array({self.values!r}, dtype=object)))[1]" ) return (eval, (code,)) @@ -67,19 +80,25 @@ def _anndata_v2(path: Path) -> Path: return path -def _index_array(store: Path) -> Path: - """obs's index array: `obs/_index`, or its `values` where anndata 0.13 - writes a nullable string array.""" - target = store / "obs" / "_index" +def _text_array(store: Path, element: str) -> Path: + """A text element's array: the element itself, or its `values` where + anndata 0.13 writes a nullable string array.""" + target = store / element return target if (target / ".zarray").exists() else target / "values" -def _set_codecs(store: Path, compressor, filters, *, files: str = "both") -> Path: - """Give obs's index array these codecs, in its .zarray, the consolidated - index, or both (`files` is "zarray", "zmetadata" or "both").""" - target = _index_array(store) +def _index_array(store: Path) -> Path: + return _text_array(store, "obs/_index") + + +def _set_codecs(store: Path, compressor, filters, *, files: str = "both", + array: Path = None) -> Path: + """Give a text array (obs's index by default) these codecs, in its + .zarray, the consolidated index, or both (`files` is "zarray", + "zmetadata" or "both").""" + target = array or _index_array(store) meta = json.loads((target / ".zarray").read_text()) - meta["chunks"] = [len(NAMES)] + meta["chunks"] = list(meta["shape"]) meta["compressor"] = compressor meta["filters"] = filters if files in ("both", "zarray"): @@ -92,18 +111,17 @@ def _set_codecs(store: Path, compressor, filters, *, files: str = "both") -> Pat def _poison(store: Path, marker: Path, *, where: str = "compressor", - files: str = "both") -> Path: - """Make obs's index name the pickle codec and hold the payload, with the - codec as the compressor or a filter.""" - target = _index_array(store) + files: str = "both", element: str = "obs/_index", values=NAMES) -> Path: + """Make a text array name the pickle codec and hold the payload, with + the codec as the compressor or a filter.""" + target = _text_array(store, element) for f in target.iterdir(): if not f.name.startswith("."): f.unlink() - (target / "0").write_bytes(pickle.dumps(_Payload(marker))) - pickled = {"id": "pickle", "protocol": 5} + (target / "0").write_bytes(pickle.dumps(_Payload(marker, values))) if where == "compressor": - return _set_codecs(store, pickled, [{"id": "vlen-utf8"}], files=files) - return _set_codecs(store, None, [{"id": "vlen-utf8"}, pickled], files=files) + return _set_codecs(store, PICKLE, [{"id": "vlen-utf8"}], files=files, array=target) + return _set_codecs(store, None, [{"id": "vlen-utf8"}, PICKLE], files=files, array=target) @pytest.fixture @@ -119,7 +137,7 @@ def test_a_store_naming_the_pickle_codec_is_refused_on_opening(tmp_path, marker, opened like any other, and its first read ran the payload.""" store = _poison(_anndata_v2(tmp_path / "evil.zarr"), marker, where=where) for mode in ("r", "r+", "a"): - with pytest.raises(ZarrCodecError, match=r"obs/_index\S* names the 'pickle' codec"): + with pytest.raises(ZarrCodecError, match=r"obs/_index\S*(, as \S+ lists it,)? " + REFUSED): open_store(store, mode) @@ -131,17 +149,17 @@ def test_each_handle_is_checked_through_the_metadata_it_reads_with(tmp_path, mar with open_store(only_disk, "r") as s: # The index names the codecs anndata wrote: they cannot decode a # pickle, so the read fails, and nothing runs. - with pytest.raises(Exception): + with pytest.raises(RuntimeError, match="blosc"): s.root[_index_array(only_disk).relative_to(only_disk).as_posix()][...] with pytest.raises(ZarrCodecError): open_store(only_disk, "a") - with pytest.raises(ZarrCodecError): + with pytest.raises(ZarrCodecError, match=r"obs/_index\S* " + REFUSED): check_zarr_store(only_disk) only_index = _poison(_anndata_v2(tmp_path / "index.zarr"), marker, files="zmetadata") with pytest.raises(ZarrCodecError): open_store(only_index, "r") - with pytest.raises(ZarrCodecError): + with pytest.raises(ZarrCodecError, match=r"obs/_index\S*, as \.zmetadata lists it, " + REFUSED): check_zarr_store(only_index) @@ -180,10 +198,90 @@ def test_every_command_refuses_a_store_naming_the_pickle_codec(tmp_path, marker, np.save(tmp_path / "score.npy", np.arange(4, dtype="float64")) result = runner.invoke(app, [a.format(src=src, src2=src2, tmp=tmp_path) for a in command]) assert result.exit_code == 1, _out(result) - assert "is refused" in _out(result) and "'pickle' codec" in _out(result) + lines = _error_lines(result) + assert len(lines) == 1 and lines[0].startswith("Error:"), lines + assert "is refused" in lines[0] and "'pickle' codec" in lines[0] assert not list(tmp_path.glob("out*")), "a refused store left an output" +def _hide_categories(store: Path, marker: Path, how: str) -> Path: + """Poison obs/grp's categories where no listing of the store shows it: + with no consolidated index, and obs/grp either without its group + metadata (zarr skips the folder when it lists obs) or with group + metadata that embeds an index naming the codecs anndata wrote.""" + (store / ".zmetadata").unlink() + group = store / "obs" / "grp" + benign = { + child.name: {**json.loads((child / ".zarray").read_text()), "attributes": {}} + for child in group.iterdir() if (child / ".zarray").exists() + } + _poison(store, marker, element="obs/grp/categories", values=["a", "b"], files="zarray") + if how == "no-group-metadata": + (group / ".zgroup").unlink() + (group / ".zattrs").unlink() + else: + meta = json.loads((group / ".zgroup").read_text()) + meta["consolidated_metadata"] = {"kind": "inline", "must_understand": False, "metadata": benign} + (group / ".zgroup").write_text(json.dumps(meta)) + return store + + +@pytest.mark.parametrize("how", ["no-group-metadata", "embedded-index"]) +def test_an_array_no_listing_shows_is_refused_when_it_is_read(tmp_path, marker, how): + """F165: zarr reads more than it lists. A path looked up in one go + reached an array the opening walk never saw, and export ran the + payload with exit 0.""" + store = _hide_categories(_anndata_v2(tmp_path / "evil.zarr"), marker, how) + out = tmp_path / "out.npy" + result = runner.invoke(app, ["export", "array", str(store), "obs/grp/categories", "-o", str(out)]) + assert result.exit_code == 1, _out(result) + assert re.search(REFUSED, _out(result)), _out(result) + assert not out.exists() + + +def test_metadata_changed_after_the_check_is_refused_when_it_is_read(tmp_path, marker): + """F165: without a consolidated index zarr reads an array's metadata + again on each access, so a file changed after the store was opened + would have been decoded as it then said.""" + store = _anndata_v2(tmp_path / "s.zarr") + (store / ".zmetadata").unlink() + with open_store(store, "r") as s: + _poison(store, marker, element="obs/grp/categories", values=["a", "b"], files="zarray") + with pytest.raises(ZarrCodecError, match=REFUSED): + s.root["obs/grp/categories"][...] + + +@pytest.mark.parametrize("where", ["array-only", "embedded-index-only", "both"]) +def test_a_copy_checks_every_metadata_file_it_would_carry(tmp_path, marker, where): + """F165: a copy carries every file, and the check before it read only + what zarr listed. A group's metadata embedding an index of harmless + codecs hid an array's own .zarray naming pickle, and the reverse, so + `import -o` wrote a store that would run the payload in any reader.""" + store = _anndata_v2(tmp_path / "evil.zarr") + (store / ".zmetadata").unlink() + target = _index_array(store) + benign = json.loads((target / ".zarray").read_text()) + poisoned = {**benign, "compressor": PICKLE, "filters": [{"id": "vlen-utf8"}]} + if where in ("array-only", "both"): + _poison(store, marker, files="zarray") + key = target.relative_to(store).as_posix() + embedded = poisoned if where in ("embedded-index-only", "both") else benign + root = json.loads((store / ".zgroup").read_text()) + root["consolidated_metadata"] = { + "kind": "inline", "must_understand": False, + "metadata": {key: {**embedded, "attributes": {}}}, + } + (store / ".zgroup").write_text(json.dumps(root)) + (tmp_path / "extra.json").write_text('{"a": 1}') + out = tmp_path / "out.zarr" + result = runner.invoke( + app, ["import", "dict", str(store), "uns/extra", str(tmp_path / "extra.json"), "-o", str(out)] + ) + assert result.exit_code == 1, _out(result) + assert re.search(r"obs/_index\S*(, as \.zgroup lists it,)? " + REFUSED, _out(result)), _out(result) + assert not out.exists() + + def test_a_refused_store_is_never_copied(tmp_path, marker): store = _poison(_anndata_v2(tmp_path / "evil.zarr"), marker) with pytest.raises(ZarrCodecError): @@ -191,29 +289,67 @@ def test_a_refused_store_is_never_copied(tmp_path, marker): assert not (tmp_path / "copy.zarr").exists() +def test_a_metadata_file_that_is_not_json_refuses_a_copy(tmp_path): + store = _anndata_v2(tmp_path / "s.zarr") + (_index_array(store) / ".zarray").write_text("{not json") + with pytest.raises(ZarrCodecError, match=r"obs/_index\S*/\.zarray is not valid JSON"): + check_zarr_store(store) + + +def test_zarr_cannot_build_a_codec_off_the_lists(): + """The layer under every read: whatever metadata zarr parses, and + whenever, a codec off the lists is refused as it is built, by each + function that builds one.""" + import numcodecs + import numcodecs.registry + from zarr.core.metadata import v3 as metadata_v3 + from zarr.registry import get_codec_class, get_numcodec + + for build in (get_numcodec, numcodecs.get_codec, numcodecs.registry.get_codec): + for codec in ("pickle", "json2"): + with pytest.raises(ZarrCodecError, match=f"names the {'' if codec == 'pickle' else 'codec '}'{codec}'"): + build({"id": codec}) + assert build({"id": "zlib"}).codec_id == "zlib" + with pytest.raises(ZarrCodecError): + numcodecs.registry.codec_registry["pickle"].from_config({}) + for resolve in (get_codec_class, metadata_v3.get_codec_class): + with pytest.raises(ZarrCodecError, match="names the codec 'numcodecs.pickle'"): + resolve("numcodecs.pickle") + assert resolve("zstd").__name__ == "ZstdCodec" + before = numcodecs.registry.get_codec + restrict_zarr_codecs() + assert numcodecs.registry.get_codec is before, "a second run wrapped the wrapper" + + def test_json2_is_named_in_the_refusal(tmp_path): """json2 runs no code, but builds Python objects in a shape the chunk names, and anndata never writes it.""" store = _set_codecs(_anndata_v2(tmp_path / "s.zarr"), {"id": "json2"}, [{"id": "vlen-utf8"}]) - with pytest.raises(ZarrCodecError, match=r"obs/_index\S* names the codec 'json2', which adata does not decode"): + with pytest.raises( + ZarrCodecError, + match=r"obs/_index\S*(, as \S+ lists it,)? names the codec 'json2', which adata does not decode", + ): open_store(store, "r") @pytest.mark.parametrize("codec", ["msgpack2", "a-codec-nobody-registered"]) def test_a_codec_zarr_cannot_resolve_ends_in_one_error_line(tmp_path, codec): - """zarr refuses an id it cannot resolve while it reads the metadata, - before the check sees it (msgpack2 is registered only where msgpack is - installed, and then the check refuses it).""" + """zarr refuses an id that nothing registered while it reads the + metadata, in its own words. msgpack2 is registered only where msgpack + is installed, and is then refused as off the list.""" store = _set_codecs(_anndata_v2(tmp_path / "s.zarr"), {"id": codec}, [{"id": "vlen-utf8"}]) result = runner.invoke(app, ["view", str(store)]) assert result.exit_code == 1, _out(result) - assert _out(result).startswith("Error:") and "Traceback" not in _out(result) + lines = _error_lines(result) + assert len(lines) == 1 and lines[0].startswith("Error:"), lines @pytest.mark.parametrize("dropped", ["zstd", "crc32c"]) def test_the_v3_walk_reaches_the_codecs_a_shard_nests(tmp_path, monkeypatch, dropped): - """zarr resolves no v3 codec that runs code; the list keeps a plugin - from adding one, and the walk reaches a shard's inner and index codecs.""" + """The opening walk reaches a shard's inner and index codecs. (zarr + resolves no v3 codec that runs code; the v3 list keeps a plugin from + adding one.) The walk reads the list when it runs, so narrowing it here + tests the walk alone: the layer under it kept the list it started with.""" import adata.storage as storage path = tmp_path / "s.zarr" @@ -275,12 +411,24 @@ async def get(self, key, *args, **kwargs): monkeypatch.setattr(LocalStore, "get", get) open_store(store, "r").close() - check_zarr_store(store) names = {Path(k).name for k in fetched} assert names <= {".zarray", ".zattrs", ".zgroup", ".zmetadata", "zarr.json"}, names assert ".zarray" in names +def test_a_stray_file_in_a_store_prints_nothing(tmp_path): + """Opening a store to write walks the hierarchy on disk, where zarr + warns about any file that is not part of it (a .DS_Store).""" + store = _anndata_v2(tmp_path / "s.zarr") + (store / ".DS_Store").write_bytes(b"\0") + (tmp_path / "extra.json").write_text('{"a": 1}') + result = runner.invoke( + app, ["import", "dict", str(store), "uns/extra", str(tmp_path / "extra.json"), "--inplace"] + ) + assert result.exit_code == 0, _out(result) + assert "DS_Store" not in _out(result) + + def test_the_v2_list_names_no_codec_that_builds_objects(): """pickle runs code; json2 and msgpack2 build objects in a shape the chunk names. Letting one in must be a deliberate change here.""" From d7ffd5398f1a86fd183fb7b287701bb1e9bf77b7 Mon Sep 17 00:00:00 2001 From: Aljes Date: Fri, 4 Dec 2026 11:01:02 +0000 Subject: [PATCH 4/5] Changelog and STATUS link the release PR Co-Authored-By: Claude Opus 5.5 --- STATUS.md | 2 +- docs/changelog.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/STATUS.md b/STATUS.md index 964ac1a..0645930 100644 --- a/STATUS.md +++ b/STATUS.md @@ -7,7 +7,7 @@ moves; the plan of record for the current item is in the section below. | Version | What | Issues | |---|---|---| -| 0.17.9 | A Zarr store naming a codec adata does not decode is refused when opened: numcodecs' `pickle`, which a v2 store could name for any text array, ran its author's code on the first read | #PR | +| 0.17.9 | A Zarr store naming a codec adata does not decode is refused when opened: numcodecs' `pickle`, which a v2 store could name for any text array, ran its author's code on the first read | #132 | | 0.17.8 | Sparse matrices read at least 32 MiB at a time (`subset` of a narrow matrix on Lustre in a quarter of the time); no numpy huge pages, which stalled writes on nodes with fragmented memory; Performance on cluster storage page and the `benchmarks/lustre/` probe | #129, #130 | | 0.17.7 | `import dataframe --categorical` keeps numeric-looking labels (leiden's 0, 1, 10) as categoricals of their text; `convert --feature-type` / `--split-feature-types` take a 10x input with no feature types (Cell Ranger 2) as gene expression; every tag gets its GitHub release from the changelog | #124, #127, #114 | | 0.17.6 | Audit fixes, waves 3 and 4 (streaming): reads and writes follow the source's chunks and Zarr v3 shards, each shard written once; `recast` checks and converts in `--chunk` blocks; `split`'s memory no longer grows with its groups; pickle arrays checked before use; 16-bit images export as they are; plain-line logs and names printed as stored; h5py >= 3.16 | #96, #97, #101, #103 | diff --git a/docs/changelog.md b/docs/changelog.md index 6b346f0..4f26020 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -22,7 +22,7 @@ does not decode is refused before any chunk is read. ### Fixed - **A Zarr store naming the `pickle` codec, or any codec adata does not - decode, is refused** ([#PR](https://github.com/cellgeni/adata-cli/pull/PR)). + decode, is refused** ([#132](https://github.com/cellgeni/adata-cli/pull/132)). zarr decodes a chunk with whatever codecs its array's metadata names, and zarr-python and anndata run a pickled chunk the same way. `adata` now keeps numcodecs and zarr from building any codec outside a list of those From 7f8e33966ea8eff35eb9857312f91c040d93aa57 Mon Sep 17 00:00:00 2001 From: Aljes Date: Fri, 4 Dec 2026 11:29:30 +0000 Subject: [PATCH 5/5] Review fixes: the copy scan reads metadata as zarr does The scan before a copy matched file names exactly and took an array's word for its version, so a `.zarray` saying `"node_type": "array"` had its compressor skipped, and on a case-insensitive filesystem `.ZARRAY` (which zarr opens as `.zarray`) was not read at all. With the array where no listing of the copy shows it, `import -o` wrote a store that runs the payload in any reader; adata itself never decoded it. - In each folder the four metadata names are opened through the filesystem, as zarr opens them. - Every mapping holding a compressor, filters or codecs is checked, whatever it says it is; a codec's own configuration (lzma's filter chain) and attributes are not looked into. - copy_path checks the copy again once it is made, and removes it if it is refused: the source may change between the check and the copy. - restrict_zarr_codecs says that importing adata.storage restricts zarr for whatever else the process does. Co-Authored-By: Claude Opus 5.5 --- src/adata/storage/__init__.py | 80 +++++++++++++++++++++----------- tests/test_zarr_safety.py | 86 +++++++++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+), 26 deletions(-) diff --git a/src/adata/storage/__init__.py b/src/adata/storage/__init__.py index a560fa4..a431b4d 100644 --- a/src/adata/storage/__init__.py +++ b/src/adata/storage/__init__.py @@ -565,22 +565,37 @@ def _off_the_list(meta: dict, zarr_format: int) -> Optional[str]: return next((name for name in names if name not in allowed), None) -def _arrays_in(document: Any, key: str = "") -> Iterator[tuple]: - """Every array's metadata in a metadata file, with its Zarr version and - the key an index in the file lists it under: the file's own (key ""), - and the ones an index in it holds, at any depth.""" +#: Keys whose values hold no metadata zarr reads codecs from: codecs' own +#: configurations (handled where they are named) and attributes. +_NO_CODECS_BELOW = frozenset({"codecs", "index_codecs", "compressor", "filters", "attributes"}) + + +def _codecs_in(document: Any, key: str = "") -> Iterator[tuple]: + """Every codec a metadata file names, with the list it must be on and the + key an index in the file lists its array under ("" for the file's own). + + Every mapping holding a v2 compressor or filters, or v3 codecs, counts, + whatever else it says it is: zarr reads a `.zarray` as v2 and a + `zarr.json` as v3 whatever keys they hold. A codec's own configuration + (a mapping with an `id` or a `name`) and attributes are not looked into. + """ if isinstance(document, dict): - if document.get("node_type") == "array": - yield document, 3, key - elif "chunks" in document and "dtype" in document and ( - "compressor" in document or "filters" in document - ): - yield document, 2, key + if "id" not in document and ("compressor" in document or "filters" in document): + compressor = document.get("compressor") + codecs = [compressor] if compressor is not None else [] + codecs.extend(document.get("filters") or ()) + for codec in codecs: + yield _codec_name(codec, "id"), ZARR_V2_CODECS, key + if "name" not in document and "codecs" in document: + for name in _v3_codec_names(document.get("codecs")): + yield name, ZARR_V3_CODECS, key for name, value in document.items(): - yield from _arrays_in(value, name if isinstance(value, dict) else key) + if name in _NO_CODECS_BELOW or str(name).endswith(".zattrs"): + continue + yield from _codecs_in(value, name if isinstance(value, dict) else key) elif isinstance(document, list): for value in document: - yield from _arrays_in(value, key) + yield from _codecs_in(value, key) def check_zarr_contents(group: Any, path: Any = None) -> None: @@ -614,15 +629,17 @@ def check_zarr_contents(group: Any, path: Any = None) -> None: def check_zarr_store(path: Path) -> None: - """Refuse a store about to be copied as files if any of its metadata - names a codec this tool does not decode. + """Refuse a store copied as files if any of its metadata names a codec + this tool does not decode. A copy carries every file, and a reader of the copy may use any of them: an array's own metadata, the consolidated index, an index a - group's metadata embeds. So every metadata file is read as JSON, - through linked folders as the copy goes through them, and each array's - metadata in it is checked. A metadata file that is not JSON is refused - too: no reader could use it either. + group's metadata embeds. So in every folder, through linked folders as + a copy goes through them, each metadata file zarr would open is read as + JSON and every codec in it checked. The files are opened by their names + through the filesystem, as zarr opens them, so a case-insensitive one + finds `.ZARRAY` for `.zarray` here as it does there. A metadata file + that is not JSON is refused too: no reader could use it either. """ import json import os @@ -630,24 +647,26 @@ def check_zarr_store(path: Path) -> None: path = Path(path) seen = set() - for folder, subfolders, names in os.walk(path, followlinks=True): + for folder, subfolders, _ in os.walk(path, followlinks=True): real = os.path.realpath(folder) if real in seen: subfolders[:] = [] continue seen.add(real) here = Path(folder).relative_to(path).as_posix() - for name in sorted(n for n in names if n in ZARR_METADATA_FILES): + for name in sorted(ZARR_METADATA_FILES): + source = Path(folder, name) + if not source.is_file(): + continue file = posixpath.normpath(posixpath.join(here, name)) try: - document = json.loads(Path(folder, name).read_bytes()) + document = json.loads(source.read_bytes()) except (ValueError, RecursionError) as error: raise ZarrCodecError( f"'{path}' is refused: {file} is not valid JSON ({error})." ) from error - for meta, zarr_format, key in _arrays_in(document): - codec = _off_the_list(meta, zarr_format) - if codec is None: + for codec, allowed, key in _codecs_in(document): + if codec in allowed: continue if key: for suffix in ("/.zarray", "/zarr.json"): @@ -689,8 +708,10 @@ def restrict_zarr_codecs() -> None: built from metadata through numcodecs' registry (v2) or zarr's (v3), so each id off the lists is replaced there by a class that refuses to be built, and the functions that build them refuse an id off the lists - even if it is registered later. Run once, when this module is imported; - running it again changes nothing. + even if it is registered later. Run once, when this module is imported, + so anything that imports `adata.storage` (a notebook, a test harness) + loses those codecs for its own use of zarr too; running it again + changes nothing. """ try: import numcodecs @@ -2062,5 +2083,12 @@ def copy_path(src: Path, dst: Path) -> None: raise FileExistsError(f"Destination '{dst}' already exists.") check_zarr_store(src) shutil.copytree(src, dst) + try: + # What was copied, which no one else writes: the source may + # have changed between the check and the copy. + check_zarr_store(dst) + except ZarrCodecError: + shutil.rmtree(dst, ignore_errors=True) + raise return shutil.copy2(src, dst) diff --git a/tests/test_zarr_safety.py b/tests/test_zarr_safety.py index 52b4abc..a125970 100644 --- a/tests/test_zarr_safety.py +++ b/tests/test_zarr_safety.py @@ -282,6 +282,92 @@ def test_a_copy_checks_every_metadata_file_it_would_carry(tmp_path, marker, wher assert not out.exists() +def _case_insensitive(directory: Path) -> bool: + probe = directory / "CaseProbe" + probe.write_text("") + try: + return (directory / "caseprobe").exists() + finally: + probe.unlink() + + +@pytest.mark.parametrize("trick", ["node-type", "upper-case-name"]) +def test_a_copy_reads_metadata_as_zarr_does(tmp_path, marker, trick): + """F165: the scan before a copy matched file names exactly and took an + array's word for its version: a `.zarray` saying `"node_type": "array"` + had its compressor skipped as v3, and on a case-insensitive filesystem + zarr opens `.ZARRAY` as `.zarray`. With the array where no listing of + the copy shows it, `import -o` wrote a store that runs the payload in + any reader.""" + if trick == "upper-case-name" and not _case_insensitive(tmp_path): + pytest.skip("zarr opens `.ZARRAY` as `.zarray` only on a case-insensitive filesystem") + store = _anndata_v2(tmp_path / "evil.zarr") + (store / ".zmetadata").unlink() + group = store / "obs" / "grp" + _poison(store, marker, element="obs/grp/categories", values=["a", "b"], files="zarray") + (group / ".zgroup").unlink() + (group / ".zattrs").unlink() + zarray = group / "categories" / ".zarray" + if trick == "node-type": + zarray.write_text(json.dumps({**json.loads(zarray.read_text()), "node_type": "array"})) + else: + zarray.rename(zarray.with_name(".ZARRAY")) + (tmp_path / "extra.json").write_text('{"a": 1}') + out = tmp_path / "out.zarr" + result = runner.invoke( + app, ["import", "dict", str(store), "uns/extra", str(tmp_path / "extra.json"), "-o", str(out)] + ) + assert result.exit_code == 1, _out(result) + assert re.search(r"obs/grp/categories " + REFUSED, _out(result)), _out(result) + assert not out.exists() + + +def test_a_copy_is_checked_again_once_it_is_made(tmp_path, marker, monkeypatch): + """The source may change between the check and the copy; the copy, which + no one else writes, is checked too, and removed if it is refused.""" + import shutil + + store = _anndata_v2(tmp_path / "s.zarr") + copy = tmp_path / "copy.zarr" + copytree = shutil.copytree + + def copy_then_change(src, dst, *args, **kwargs): + # shutil recurses through the module's name, so this sees every + # folder: the store changes once, when the whole copy is made. + result = copytree(src, dst, *args, **kwargs) + if Path(dst) == copy: + _poison(copy, marker) + return result + + monkeypatch.setattr(shutil, "copytree", copy_then_change) + with pytest.raises(ZarrCodecError, match=REFUSED): + copy_path(store, copy) + assert not copy.exists() + + +def test_a_codec_s_own_filters_and_attributes_are_not_taken_for_codecs(tmp_path): + """lzma keeps a filter chain of its own, with numbers for ids, in its + configuration, and attributes may hold any keys at all: neither is + metadata zarr builds a codec from.""" + import lzma + + import numcodecs + + path = tmp_path / "s.zarr" + root = zarr.open_group(str(path), mode="w", zarr_format=2) + chain = [{"id": lzma.FILTER_DELTA, "dist": 4}, {"id": lzma.FILTER_LZMA2, "preset": 1}] + root.create_array( + "X", shape=(4, 3), chunks=(4, 3), dtype="float32", + compressors=numcodecs.LZMA(format=lzma.FORMAT_RAW, filters=chain), + ) + root["X"][:] = 1.0 + root.attrs["settings"] = {"compressor": "lzf", "filters": ["x"], "codecs": ["y"]} + zarr.consolidate_metadata(str(path)) + check_zarr_store(path) + with open_store(path, "r", require_anndata=False) as s: + assert float(s.root["X"][...].sum()) == 12.0 + + def test_a_refused_store_is_never_copied(tmp_path, marker): store = _poison(_anndata_v2(tmp_path / "evil.zarr"), marker) with pytest.raises(ZarrCodecError):