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/STATUS.md b/STATUS.md index 68a6c42..0645930 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 | #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 | @@ -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..4f26020 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -8,6 +8,36 @@ 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** ([#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 + 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) + 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/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 a7b8f21..bbaeae8 100644 --- a/docs/reference/spec-zarr.md +++ b/docs/reference/spec-zarr.md @@ -398,6 +398,44 @@ 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..a431b4d 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,7 +274,22 @@ def open_store( else: target = str(path) - root = zarr.open_group(target, mode=mode, **kwargs) + 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: @@ -464,6 +480,291 @@ 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", +}) + + +#: 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. + + 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 _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 ()) + 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) + + +#: 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 "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(): + 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 _codecs_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, + 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 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. + """ + 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 + 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 _codec_error(source, name, codec) + + +def check_zarr_store(path: Path) -> None: + """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 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 + import posixpath + + path = Path(path) + seen = set() + 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(ZARR_METADATA_FILES): + source = Path(folder, name) + if not source.is_file(): + continue + file = posixpath.normpath(posixpath.join(here, name)) + try: + 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 codec, allowed, key in _codecs_in(document): + if codec in allowed: + 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. + + `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, + 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 + 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]: """The Zarr spec version (2 or 3) backing `obj`, or None for HDF5.""" return getattr(getattr(obj, "metadata", None), "zarr_format", None) @@ -1780,6 +2081,14 @@ 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) + 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 new file mode 100644 index 0000000..a125970 --- /dev/null +++ b/tests/test_zarr_safety.py @@ -0,0 +1,521 @@ +"""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. 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 + +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, + restrict_zarr_codecs, +) + +zarr = pytest.importorskip("zarr") +ad = pytest.importorskip("anndata") + +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: + text = result.stdout + (result.stderr or "") + 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 + `values` as the vlen-utf8 filter after it expects them.""" + + 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({self.values!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 _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 _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"] = list(meta["shape"]) + 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", 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, values))) + if where == "compressor": + 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 +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*(, as \S+ lists it,)? " + REFUSED): + 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(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, 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, match=r"obs/_index\S*, as \.zmetadata lists it, " + REFUSED): + 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) + 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 _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): + copy_path(store, tmp_path / "copy.zarr") + 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*(, 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 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) + 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): + """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" + 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() + 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.""" + assert not {"pickle", "json2", "msgpack2"} & ZARR_V2_CODECS 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" },