From b8ee7f07896e55a09c1af52e854f4596645e0a4f Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Sat, 17 Oct 2026 18:39:24 -0500 Subject: [PATCH 01/37] build: make the database drivers optional extras pymysql was a core dependency, so every install of datajoint pulled in the MySQL driver whether or not it was used, while the PostgreSQL driver was already the optional postgres extra. Both drivers are now extras: pip install "datajoint[postgres]" installs psycopg2-binary, and pip install "datajoint[mysql]" installs pymysql, with the same >=0.7.2 floor as before. A bare pip install datajoint installs no database driver. import datajoint no longer imports a driver. Each adapter imports its driver when it is created, which happens when a connection is made, through a new helper, import_driver, in adapters/base.py. When the driver is missing, connecting raises a DataJointError that names the extra, for example: The MySQL backend requires the pymysql driver, which is not installed. Install it with: pip install "datajoint[mysql]". The PostgreSQL adapter raised ImportError for its missing driver; it now raises the same DataJointError. The adapter imports the psycopg2 module, which both the psycopg2 and the psycopg2-binary distributions provide, so either one satisfies it. The test dependency group and the test and dev extras install both drivers. The README install line, CONTRIBUTING.md, the development Docker image (it now installs both extras), and the conda-forge notes in RELEASE_MEMO.md (conda has no extras, so the recipe lists both drivers) are updated to match. Migration: an environment that connects to MySQL needs pip install "datajoint[mysql]", or pymysql installed some other way; one that connects to PostgreSQL needs pip install "datajoint[postgres]". An upgrade in place keeps a pymysql that is already installed, but a fresh install from a requirements file that lists only datajoint gets no driver. Code that caught ImportError from PostgreSQLAdapter() should catch DataJointError instead. Tests: test_lazy_imports.py checks, in a fresh interpreter, that import datajoint loads neither pymysql nor psycopg2. test_adapters.py blocks each driver in sys.modules and checks that get_adapter and Connection raise a DataJointError naming the right extra before any server is contacted, and that each backend needs only its own driver. --- CONTRIBUTING.md | 5 ++-- Dockerfile | 2 +- README.md | 5 +++- RELEASE_MEMO.md | 5 +++- pyproject.toml | 8 +++++- src/datajoint/__init__.py | 2 +- src/datajoint/adapters/base.py | 39 ++++++++++++++++++++++++++ src/datajoint/adapters/mysql.py | 24 ++++++++++++---- src/datajoint/adapters/postgres.py | 29 +++++++++++--------- tests/unit/test_adapters.py | 44 ++++++++++++++++++++++++++++++ tests/unit/test_lazy_imports.py | 21 +++++++++++++- 11 files changed, 157 insertions(+), 27 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 64ad3f6ab..9b725a90d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -54,12 +54,13 @@ pixi run -e test pytest -m postgresql # PostgreSQL tests only export DOCKER_HOST=unix://$HOME/.docker/run/docker.sock ``` -### PostgreSQL Backend +### Database Backends -DataJoint supports MySQL 8.0.13+ and PostgreSQL 15+ as production database backends. To install the PostgreSQL driver: +DataJoint supports PostgreSQL 15+ and MySQL 8.0.13+ as production database backends. Each database driver is an optional extra, and the `test` and `dev` extras install both: ```bash pip install -e ".[postgres]" # Installs psycopg2-binary +pip install -e ".[mysql]" # Installs pymysql ``` Tests automatically spin up both MySQL and PostgreSQL containers via testcontainers. Backend-parameterized tests (those using the `backend` fixture in `tests/conftest.py`) run against both backends to ensure feature parity. diff --git a/Dockerfile b/Dockerfile index 88c046345..28c94f18a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -19,6 +19,6 @@ USER root RUN \ chown -R ${HOST_UID:-1000}:mambauser /main && \ chown -R ${HOST_UID:-1000}:mambauser /src && \ - ${CONDA_BIN} run -n base pip install -q --no-cache-dir /main && \ + ${CONDA_BIN} run -n base pip install -q --no-cache-dir "/main[postgres,mysql]" && \ rm -r /main/* USER ${MAMBA_USER} diff --git a/README.md b/README.md index 7b68d185b..099864cc3 100644 --- a/README.md +++ b/README.md @@ -57,8 +57,11 @@ The **DataJoint Library** is a framework for scientific data pipelines based on ## Installation +Install DataJoint with the driver for your database: + ```bash -pip install datajoint +pip install "datajoint[postgres]" # PostgreSQL +pip install "datajoint[mysql]" # MySQL ``` or with Conda: diff --git a/RELEASE_MEMO.md b/RELEASE_MEMO.md index 1a3623330..951efde55 100644 --- a/RELEASE_MEMO.md +++ b/RELEASE_MEMO.md @@ -143,7 +143,9 @@ If the bot doesn't create a PR, manually update the feedstock: curl -sL https://pypi.org/pypi/datajoint/2.1.0/json | jq -r '.urls[] | select(.packagetype=="sdist") | .digests.sha256' ``` -4. **Check dependencies** match `pyproject.toml`: +4. **Check dependencies** match `pyproject.toml`. conda has no extras, so `run` + also lists the database drivers that `pyproject.toml` keeps in the `mysql` and + `postgres` extras: ```yaml requirements: host: @@ -154,6 +156,7 @@ If the bot doesn't create a PR, manually update the feedstock: - python >={{ python_min }} - numpy - pymysql >=0.7.2 + - psycopg2 >=2.9.0 - deepdiff - pyparsing - pandas diff --git a/pyproject.toml b/pyproject.toml index 050bde152..358299189 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,6 @@ name = "datajoint" dynamic = ["version"] dependencies = [ "numpy", - "pymysql>=0.7.2", "deepdiff", "pyparsing", "pandas", @@ -93,6 +92,8 @@ test = [ "ipython", "graphviz", "testcontainers[mysql,minio,postgres]>=4.0", + "pymysql>=0.7.2", + "psycopg2-binary>=2.9.0", "polars>=0.20.0", "pyarrow>=14.0.0", ] @@ -101,7 +102,9 @@ test = [ s3 = ["s3fs>=2023.1.0"] gcs = ["gcsfs>=2023.1.0"] azure = ["adlfs>=2023.1.0"] +# Database drivers: install the extra for each backend in use. postgres = ["psycopg2-binary>=2.9.0"] +mysql = ["pymysql>=0.7.2"] polars = ["polars>=0.20.0"] arrow = ["pyarrow>=14.0.0"] viz = ["matplotlib", "ipython"] @@ -114,6 +117,7 @@ test = [ "ipython", "s3fs>=2023.1.0", "testcontainers[mysql,minio,postgres]>=4.0", + "pymysql>=0.7.2", "psycopg2-binary>=2.9.0", "polars>=0.20.0", "pyarrow>=14.0.0", @@ -125,6 +129,8 @@ dev = [ # including test "pytest", "pytest-cov", + "pymysql>=0.7.2", + "psycopg2-binary>=2.9.0", "polars>=0.20.0", "pyarrow>=14.0.0", ] diff --git a/src/datajoint/__init__.py b/src/datajoint/__init__.py index 69c6df269..e6b0c6f66 100644 --- a/src/datajoint/__init__.py +++ b/src/datajoint/__init__.py @@ -278,7 +278,7 @@ def FreeTable(conn_or_name, full_table_name: str | None = None) -> _FreeTable: # ============================================================================= # Lazy imports — heavy dependencies loaded on first access # ============================================================================= -# These modules import heavy dependencies (networkx, matplotlib, click, pymysql) +# These modules import heavy dependencies (networkx, matplotlib, click) # that slow down `import datajoint`. They are loaded on demand. _lazy_modules = { diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 5b4a7ab72..0c4e8e94d 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -7,9 +7,48 @@ from __future__ import annotations +import importlib from abc import ABC, abstractmethod +from types import ModuleType from typing import Any +from ..errors import DataJointError + + +def import_driver(module: str, backend: str, extra: str) -> ModuleType: + """ + Import a database driver, or name the extra that installs it. + + Database drivers are optional extras, so adapters import them when they are + created rather than when ``datajoint`` is imported. + + Parameters + ---------- + module : str + Import name of the driver, e.g. ``'pymysql'`` or ``'psycopg2'``. + backend : str + Backend name for the error message, e.g. ``'MySQL'``. + extra : str + The ``datajoint`` extra that installs the driver, e.g. ``'mysql'``. + + Returns + ------- + ModuleType + The imported driver module. + + Raises + ------ + DataJointError + If the driver is not installed. + """ + try: + return importlib.import_module(module) + except ImportError as error: + raise DataJointError( + f"The {backend} backend requires the {module} driver, which is not installed. " + f'Install it with: pip install "datajoint[{extra}]"' + ) from error + class DatabaseAdapter(ABC): """ diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index 2ef9baf84..857913128 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -9,10 +9,12 @@ from typing import Any -import pymysql as client - from .. import errors -from .base import DatabaseAdapter +from .base import DatabaseAdapter, import_driver + +# The pymysql driver (the ``datajoint[mysql]`` extra), imported when the first +# MySQLAdapter is created so that ``import datajoint`` loads no database driver. +client: Any = None # Core type mapping: DataJoint core types → MySQL types CORE_TYPE_MAP = { @@ -48,6 +50,18 @@ class MySQLAdapter(DatabaseAdapter): """MySQL database adapter implementation.""" + def __init__(self) -> None: + """ + Initialize MySQL adapter. + + Raises + ------ + DataJointError + If pymysql is not installed (``pip install "datajoint[mysql]"``). + """ + global client + client = import_driver("pymysql", backend="MySQL", extra="mysql") + # ========================================================================= # Connection Management # ========================================================================= @@ -175,9 +189,7 @@ def get_cursor(self, connection: Any, as_dict: bool = False) -> Any: Any pymysql cursor object. """ - import pymysql - - cursor_class = pymysql.cursors.DictCursor if as_dict else pymysql.cursors.Cursor + cursor_class = client.cursors.DictCursor if as_dict else client.cursors.Cursor return connection.cursor(cursor=cursor_class) # ========================================================================= diff --git a/src/datajoint/adapters/postgres.py b/src/datajoint/adapters/postgres.py index 3a55d8eb8..5e18470ac 100644 --- a/src/datajoint/adapters/postgres.py +++ b/src/datajoint/adapters/postgres.py @@ -10,15 +10,13 @@ import re from typing import Any -try: - import psycopg2 as client - from psycopg2 import sql -except ImportError: - client = None # type: ignore - sql = None # type: ignore - from .. import errors -from .base import DatabaseAdapter +from .base import DatabaseAdapter, import_driver + +# The psycopg2 driver (the ``datajoint[postgres]`` extra), imported when the first +# PostgreSQLAdapter is created so that ``import datajoint`` loads no database driver. +# Either the psycopg2 or the psycopg2-binary distribution provides it. +client: Any = None # Core type mapping: DataJoint core types → PostgreSQL types CORE_TYPE_MAP = { @@ -56,11 +54,16 @@ class PostgreSQLAdapter(DatabaseAdapter): """PostgreSQL database adapter implementation.""" def __init__(self) -> None: - """Initialize PostgreSQL adapter.""" - if client is None: - raise ImportError( - "psycopg2 is required for PostgreSQL support. " "Install it with: pip install 'datajoint[postgres]'" - ) + """ + Initialize PostgreSQL adapter. + + Raises + ------ + DataJointError + If psycopg2 is not installed (``pip install "datajoint[postgres]"``). + """ + global client + client = import_driver("psycopg2", backend="PostgreSQL", extra="postgres") # ========================================================================= # Connection Management diff --git a/tests/unit/test_adapters.py b/tests/unit/test_adapters.py index bd0afa9e0..673977901 100644 --- a/tests/unit/test_adapters.py +++ b/tests/unit/test_adapters.py @@ -4,9 +4,14 @@ Tests adapter functionality without requiring actual database connections. """ +import re +import sys + import pytest from datajoint.adapters import DatabaseAdapter, MySQLAdapter, PostgreSQLAdapter, get_adapter +from datajoint.connection import Connection +from datajoint.errors import DataJointError class TestAdapterRegistry: @@ -48,6 +53,45 @@ def test_get_adapter_invalid(self): get_adapter("sqlite") +# Each backend, the driver module its adapter imports, and the extra that installs it. +MISSING_DRIVER_CASES = [ + ("mysql", "pymysql", "mysql"), + ("postgresql", "psycopg2", "postgres"), + ("postgres", "psycopg2", "postgres"), +] + + +class TestMissingDriver: + """A missing database driver is reported with the extra that installs it.""" + + @pytest.mark.parametrize("backend, driver, extra", MISSING_DRIVER_CASES) + def test_get_adapter_names_extra(self, monkeypatch, backend, driver, extra): + """Creating the adapter without its driver raises a DataJointError naming the extra.""" + # A None entry in sys.modules makes `import ` raise ImportError. + monkeypatch.setitem(sys.modules, driver, None) + with pytest.raises(DataJointError, match=re.escape(f'pip install "datajoint[{extra}]"')) as info: + get_adapter(backend) + assert driver in str(info.value) + assert isinstance(info.value.__cause__, ImportError) + + @pytest.mark.parametrize("backend, driver, extra", MISSING_DRIVER_CASES) + def test_connection_names_extra(self, monkeypatch, backend, driver, extra): + """Connecting without the driver fails before contacting any server.""" + monkeypatch.setitem(sys.modules, driver, None) + with pytest.raises(DataJointError, match=re.escape(f'pip install "datajoint[{extra}]"')): + Connection("localhost", "user", "password", backend=backend) + + def test_other_driver_not_required(self, monkeypatch): + """Each backend needs only its own driver.""" + pytest.importorskip("psycopg2") + with monkeypatch.context() as patch: + patch.setitem(sys.modules, "pymysql", None) + assert isinstance(get_adapter("postgresql"), PostgreSQLAdapter) + with monkeypatch.context() as patch: + patch.setitem(sys.modules, "psycopg2", None) + assert isinstance(get_adapter("mysql"), MySQLAdapter) + + class TestMySQLAdapter: """Test MySQL adapter implementation.""" diff --git a/tests/unit/test_lazy_imports.py b/tests/unit/test_lazy_imports.py index a87412151..36e33c68d 100644 --- a/tests/unit/test_lazy_imports.py +++ b/tests/unit/test_lazy_imports.py @@ -2,9 +2,11 @@ Tests for lazy import behavior. These tests verify that heavy dependencies (networkx, matplotlib, click) -are not loaded until their associated features are accessed. +are not loaded until their associated features are accessed, and that +``import datajoint`` loads no database driver. """ +import subprocess import sys @@ -85,3 +87,20 @@ def test_core_imports_available(): # Heavy modules should still not be loaded assert "datajoint.diagram" not in sys.modules assert "datajoint.cli" not in sys.modules + + +def test_import_loads_no_database_driver(): + """import datajoint should not import pymysql or psycopg2. + + Drivers are optional extras, so the import must succeed without them and + leave the driver to the adapter that connects. A fresh interpreter is used + so that drivers already imported by other tests do not hide the import. + """ + code = ( + "import sys, warnings\n" + "warnings.simplefilter('ignore')\n" + "import datajoint\n" + "print(sorted(m for m in sys.modules if m.split('.')[0] in ('pymysql', 'psycopg2')))\n" + ) + result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, check=True) + assert result.stdout.strip() == "[]", f"import datajoint loaded database drivers: {result.stdout.strip()}" From e77d8a551320b2adcb995f273afa66ac8e0cebe8 Mon Sep 17 00:00:00 2001 From: mayuriphad Date: Sun, 18 Oct 2026 15:38:56 +0530 Subject: [PATCH 02/37] fix(heading): keep table_info in set_primary_key so a later rename quotes for the backend Signed-off-by: mayuriphad --- src/datajoint/heading.py | 1 + tests/unit/test_pk_rules.py | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/src/datajoint/heading.py b/src/datajoint/heading.py index 9addae474..0c126c533 100644 --- a/src/datajoint/heading.py +++ b/src/datajoint/heading.py @@ -765,6 +765,7 @@ def set_primary_key(self, primary_key): (dict(self.attributes[name].todict(), in_key=True) for name in primary_key), (dict(self.attributes[name].todict(), in_key=False) for name in self.names if name not in primary_key), ), + table_info=self.table_info, lineage_available=self._lineage_available, ) diff --git a/tests/unit/test_pk_rules.py b/tests/unit/test_pk_rules.py index 2c554091b..148bbacc1 100644 --- a/tests/unit/test_pk_rules.py +++ b/tests/unit/test_pk_rules.py @@ -5,6 +5,9 @@ primary keys in join operations. """ +from types import SimpleNamespace + +from datajoint.adapters import PostgreSQLAdapter from datajoint.heading import Heading @@ -205,3 +208,14 @@ def test_b_determines_a_ordering(self): assert names.index("x") < names.index("z") # y should be secondary (demoted from A's PK) assert "y" in result.secondary_attributes + + +class TestSetPrimaryKey: + """Tests for Heading.set_primary_key.""" + + def test_keeps_the_adapter_for_a_later_rename(self): + """A rename after set_primary_key (as dj.U & table does) quotes for the connection's backend.""" + heading = make_heading(["a"], ["b"]) + heading.table_info = {"conn": SimpleNamespace(adapter=PostgreSQLAdapter())} + renamed = heading.set_primary_key(["b"]).select([], rename_map={"c": "b"}) + assert renamed.attributes["c"].attribute_expression == '"b"' From 207028cdf78b29e7ddcce2f5a78999bd9a0daf93 Mon Sep 17 00:00:00 2001 From: TheeCoderAhmed Date: Thu, 29 Oct 2026 06:45:43 +0300 Subject: [PATCH 03/37] fix: include the store location in ObjectRef.full_path For s3, gcs and azure stores, full_path built :/// and left out the store's location, so it pointed to a path where the object is not when location is set. Use StorageBackend.get_url(), which builds the URL from the same _full_path the backend writes to. Fixes #1646 --- src/datajoint/objectref.py | 11 ++--------- tests/unit/test_objectref.py | 38 ++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 9 deletions(-) create mode 100644 tests/unit/test_objectref.py diff --git a/src/datajoint/objectref.py b/src/datajoint/objectref.py index c312e0c5d..9bd09f0bf 100644 --- a/src/datajoint/objectref.py +++ b/src/datajoint/objectref.py @@ -174,15 +174,8 @@ def full_path(self) -> str: protocol = self._backend.protocol if protocol == "file": return str(Path(self._backend.spec.get("location", "")) / self.path) - elif protocol == "s3": - bucket = self._backend.spec["bucket"] - return f"s3://{bucket}/{self.path}" - elif protocol == "gcs": - bucket = self._backend.spec["bucket"] - return f"gs://{bucket}/{self.path}" - elif protocol == "azure": - container = self._backend.spec["container"] - return f"az://{container}/{self.path}" + elif protocol in ("s3", "gcs", "azure"): + return self._backend.get_url(self.path) else: return self.path diff --git a/tests/unit/test_objectref.py b/tests/unit/test_objectref.py new file mode 100644 index 000000000..f0e70220a --- /dev/null +++ b/tests/unit/test_objectref.py @@ -0,0 +1,38 @@ +"""Unit tests for ObjectRef.""" + +from datetime import datetime, timezone + +import pytest + +from datajoint.objectref import ObjectRef +from datajoint.storage import StorageBackend + + +def _object_ref(spec): + return ObjectRef( + path="_schema/scratch/result/data_abc.txt", + size=5, + hash=None, + ext=".txt", + is_dir=False, + timestamp=datetime.now(timezone.utc), + _backend=StorageBackend(spec), + ) + + +@pytest.mark.parametrize( + ("spec", "prefix"), + [ + ( + {"protocol": "s3", "endpoint": "localhost:9000", "bucket": "bkt", "location": "proj/outbox"}, + "s3://bkt/proj/outbox/", + ), + ({"protocol": "s3", "endpoint": "localhost:9000", "bucket": "bkt"}, "s3://bkt/"), + ({"protocol": "gcs", "bucket": "bkt", "location": "proj"}, "gs://bkt/proj/"), + ({"protocol": "azure", "container": "ctr", "location": "proj"}, "az://ctr/proj/"), + ], +) +def test_full_path_includes_store_location(spec, prefix): + """full_path points where the backend stores the object, location included.""" + ref = _object_ref(spec) + assert ref.full_path == prefix + ref.path From 6760c26d65d91ebf826a14fc7275ba4b884b1755 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 2 Nov 2026 13:58:37 -0600 Subject: [PATCH 04/37] Refresh pixi.lock for the optional driver extras --- pixi.lock | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pixi.lock b/pixi.lock index e287ed2ae..3984f1eb7 100644 --- a/pixi.lock +++ b/pixi.lock @@ -111,7 +111,6 @@ environments: - pypi: https://files.pythonhosted.org/packages/cf/4e/35a80cae583a37cf15604b44240e45c05e04e86f9cfd766623149297e971/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl - pypi: https://files.pythonhosted.org/packages/c1/60/5d4751ba3f4a40a6891f24eec885f51afd78d208498268c734e256fb13c4/pydantic_settings-2.12.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/7e/32/a7125fb28c4261a627f999d5fb4afff25b523800faed2c30979949d6facd/pydot-4.0.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/7c/4c/ad33b92b9864cbde84f259d5df035a6447f91891f5be77788e2a3892bce3/pymysql-1.1.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/53/b8/fbab973592e23ae313042d450fc26fa24282ebffba21ba373786e1ce63b4/pyparsing-3.2.4-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/14/1b/a298b06749107c305e1fe0f814c6c74aea7b2f1e10989cb30f544a1b3253/python_dotenv-1.2.1-py3-none-any.whl @@ -236,7 +235,6 @@ environments: - pypi: https://files.pythonhosted.org/packages/15/df/a4c740c0943e93e6500f9eb23f4ca7ec9bf71b19e608ae5b579678c8d02f/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl - pypi: https://files.pythonhosted.org/packages/c1/60/5d4751ba3f4a40a6891f24eec885f51afd78d208498268c734e256fb13c4/pydantic_settings-2.12.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/7e/32/a7125fb28c4261a627f999d5fb4afff25b523800faed2c30979949d6facd/pydot-4.0.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/7c/4c/ad33b92b9864cbde84f259d5df035a6447f91891f5be77788e2a3892bce3/pymysql-1.1.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/10/5e/1aa9a93198c6b64513c9d7752de7422c06402de6600a8767da1524f9570b/pyparsing-3.2.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/14/1b/a298b06749107c305e1fe0f814c6c74aea7b2f1e10989cb30f544a1b3253/python_dotenv-1.2.1-py3-none-any.whl @@ -316,7 +314,6 @@ environments: - pypi: https://files.pythonhosted.org/packages/94/02/abfa0e0bda67faa65fef1c84971c7e45928e108fe24333c81f3bfe35d5f5/pydantic_core-2.41.5-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/c1/60/5d4751ba3f4a40a6891f24eec885f51afd78d208498268c734e256fb13c4/pydantic_settings-2.12.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/7e/32/a7125fb28c4261a627f999d5fb4afff25b523800faed2c30979949d6facd/pydot-4.0.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/7c/4c/ad33b92b9864cbde84f259d5df035a6447f91891f5be77788e2a3892bce3/pymysql-1.1.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/10/5e/1aa9a93198c6b64513c9d7752de7422c06402de6600a8767da1524f9570b/pyparsing-3.2.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/14/1b/a298b06749107c305e1fe0f814c6c74aea7b2f1e10989cb30f544a1b3253/python_dotenv-1.2.1-py3-none-any.whl @@ -4495,8 +4492,8 @@ packages: requires_python: '>=3.8' - pypi: ./ name: datajoint - version: 2.3.5.dev28+ge3d2a553e.d20261024 - sha256: 9ac2b52fcb44ab2d1c54ec75a4c390fc2a8d53b0480a2490d897c2dc22f593a3 + version: 2.3.5.dev44+g215175ada + sha256: 93aa78078608348c30e7d6a88ad78f218220990a716b35a4a52f62fb5d7955d6 requires_dist: - deepdiff - deepdiff<9 ; python_full_version >= '3.15' @@ -4507,7 +4504,6 @@ packages: - pandas - pydantic-settings>=2.0.0 - pydot - - pymysql>=0.7.2 - pyparsing - tqdm - pyarrow>=14.0.0 ; extra == 'arrow' @@ -4515,11 +4511,14 @@ packages: - codespell ; extra == 'dev' - polars>=0.20.0 ; extra == 'dev' - pre-commit ; extra == 'dev' + - psycopg2-binary>=2.9.0 ; extra == 'dev' - pyarrow>=14.0.0 ; extra == 'dev' + - pymysql>=0.7.2 ; extra == 'dev' - pytest ; extra == 'dev' - pytest-cov ; extra == 'dev' - ruff ; extra == 'dev' - gcsfs>=2023.1.0 ; extra == 'gcs' + - pymysql>=0.7.2 ; extra == 'mysql' - polars>=0.20.0 ; extra == 'polars' - psycopg2-binary>=2.9.0 ; extra == 'postgres' - s3fs>=2023.1.0 ; extra == 's3' @@ -4529,6 +4528,7 @@ packages: - polars>=0.20.0 ; extra == 'test' - psycopg2-binary>=2.9.0 ; extra == 'test' - pyarrow>=14.0.0 ; extra == 'test' + - pymysql>=0.7.2 ; extra == 'test' - pytest ; extra == 'test' - pytest-cov ; extra == 'test' - requests ; extra == 'test' From 247125c9105d25c786fe52dc115d48bdb669f9bf Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Wed, 4 Nov 2026 15:46:33 -0600 Subject: [PATCH 05/37] fix: use two-digit hour in dependabot schedule time Dependabot rejects time "9:00" (must match ^\d\d:\d\d$), so the config failed to parse and no GitHub Actions updates were scheduled. --- .github/dependabot.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index aac560ed2..d005b58cc 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,7 +5,7 @@ updates: schedule: interval: "monthly" day: "wednesday" - time: "9:00" + time: "09:00" timezone: "America/Chicago" groups: all-actions: From 4cc2dda6cf4da61509559e1b108de1b67d67ff59 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Thu, 5 Nov 2026 07:24:22 -0600 Subject: [PATCH 06/37] ci: add Dependabot coverage for Python dependencies Adds a pip entry for pyproject.toml alongside the github-actions one. increase-if-necessary keeps minimum-version requirements unchanged when they already admit a new release; security updates are grouped. --- .github/dependabot.yml | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index aac560ed2..0a2243e1c 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -9,4 +9,19 @@ updates: timezone: "America/Chicago" groups: all-actions: - patterns: [ "*" ] \ No newline at end of file + patterns: [ "*" ] + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "weekly" + day: "wednesday" + time: "09:00" + timezone: "America/Chicago" + # datajoint is a library: its dependencies declare minimum versions only. + # Leave a requirement alone when it already admits the new release, so + # users are not pushed onto the newest version of each dependency. + versioning-strategy: "increase-if-necessary" + groups: + python-security: + applies-to: security-updates + patterns: [ "*" ] From a827d2f02e9fbacd9868dadfe01e0b66802894fe Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Thu, 5 Nov 2026 07:33:37 -0600 Subject: [PATCH 07/37] fix: declare minimum versions for all core dependencies numpy, pandas, pyparsing, tqdm, networkx, pydot, and packaging had no version specifier. GitHub's dependency graph omits such requirements, so they were missing from the SBOM and from Dependabot alerts. The minimums were verified by running the full test suite on Python 3.10 with each dependency at its minimum. pyparsing 3.1.0 and pydot 2.x fail it: pyparsing 3.1.0 strips the quotes from quoted defaults, and pydot 2.x produces DOT that graphviz rejects. tqdm>=4.66.3 excludes CVE-2024-34062. --- pixi.lock | 18 +++++++++--------- pyproject.toml | 18 +++++++++++------- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/pixi.lock b/pixi.lock index e287ed2ae..78dd44bd7 100644 --- a/pixi.lock +++ b/pixi.lock @@ -4495,21 +4495,21 @@ packages: requires_python: '>=3.8' - pypi: ./ name: datajoint - version: 2.3.5.dev28+ge3d2a553e.d20261024 - sha256: 9ac2b52fcb44ab2d1c54ec75a4c390fc2a8d53b0480a2490d897c2dc22f593a3 + version: 2.3.5.dev42+g3c912c461.d20261105 + sha256: d1322b6612f5817610862f08fde2d86a402995b9be0cfdf208c8935ef04defe4 requires_dist: - deepdiff - deepdiff<9 ; python_full_version >= '3.15' - fsspec>=2023.1.0 - - networkx - - numpy - - packaging - - pandas + - networkx>=3.0 + - numpy>=1.22.4 + - packaging>=22.0 + - pandas>=1.5.3 - pydantic-settings>=2.0.0 - - pydot + - pydot>=3.0.0 - pymysql>=0.7.2 - - pyparsing - - tqdm + - pyparsing>=3.1.1 + - tqdm>=4.66.3 - pyarrow>=14.0.0 ; extra == 'arrow' - adlfs>=2023.1.0 ; extra == 'azure' - codespell ; extra == 'dev' diff --git a/pyproject.toml b/pyproject.toml index 47c1019e7..a318ed1d1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,20 +6,24 @@ build-backend = "hatchling.build" name = "datajoint" dynamic = ["version"] dependencies = [ - "numpy", + "numpy>=1.22.4", "pymysql>=0.7.2", "deepdiff", # deepdiff 9 requires cachebox<6, which ships no Python 3.15 wheels and cannot # be built for 3.15 (PyO3 0.27). Drop once deepdiff accepts cachebox 6. "deepdiff<9; python_version >= '3.15'", - "pyparsing", - "pandas", - "tqdm", - "networkx", - "pydot", + # pyparsing 3.1.0 drops the quotes from quoted defaults (= ""), which + # declares the attribute without a default. + "pyparsing>=3.1.1", + "pandas>=1.5.3", + # CVE-2024-34062 + "tqdm>=4.66.3", + "networkx>=3.0", + # pydot 2.x emits DOT that graphviz rejects for datajoint diagrams. + "pydot>=3.0.0", "fsspec>=2023.1.0", "pydantic-settings>=2.0.0", - "packaging", + "packaging>=22.0", ] requires-python = ">=3.10,<3.16" From 550bd8ff25d431cc072105b5cd8dbfe70544834a Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Fri, 6 Nov 2026 08:40:27 -0600 Subject: [PATCH 08/37] ci: Dependabot leaves the deepdiff<9 cap on Python 3.15 alone pyproject.toml keeps deepdiff<9 for Python 3.15 on purpose: deepdiff 9 requires cachebox<6, which has no 3.15 wheels. With increase-if-necessary, Dependabot would propose widening that cap at every new deepdiff major, so ignore semver-major updates for deepdiff. Also state that version updates stay one PR per package, since each raises an upper bound and deserves its own test run and review. --- .github/dependabot.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0a2243e1c..267fa1d43 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -21,6 +21,13 @@ updates: # Leave a requirement alone when it already admits the new release, so # users are not pushed onto the newest version of each dependency. versioning-strategy: "increase-if-necessary" + # deepdiff<9 on Python 3.15 is deliberate (see pyproject.toml); do not + # propose raising it to admit a new major version. + ignore: + - dependency-name: "deepdiff" + update-types: [ "version-update:semver-major" ] + # Version updates stay one PR per package: each one raises an upper bound + # and gets its own test run and review. Security updates are grouped. groups: python-security: applies-to: security-updates From adca1cf510f5a0cf611cfb88c6d540ba1d1136f2 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Fri, 6 Nov 2026 08:42:54 -0600 Subject: [PATCH 09/37] ci: pin actions to commit SHAs and run workflows with read-only tokens Pin every action in the lint, test, and stale workflows to the commit its current tag resolves to, so a moved or compromised tag cannot change what runs. Lint and test get a read-only GITHUB_TOKEN, and their checkouts do not persist the token in the working copy. --- .../workflows/close_inactive_issues_prs.yaml | 2 +- .github/workflows/lint.yaml | 14 ++++++++----- .github/workflows/test.yaml | 20 +++++++++++++------ 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/.github/workflows/close_inactive_issues_prs.yaml b/.github/workflows/close_inactive_issues_prs.yaml index bb2eba036..4c68e30e0 100644 --- a/.github/workflows/close_inactive_issues_prs.yaml +++ b/.github/workflows/close_inactive_issues_prs.yaml @@ -11,7 +11,7 @@ jobs: issues: write pull-requests: write steps: - - uses: actions/stale@v9 + - uses: actions/stale@5bef64f19d7facfb25b37b414482c7164d639639 # v9.1.0 with: repo-token: ${{ secrets.GITHUB_TOKEN }} operations-per-run: 500 # API rate limit diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index e7e6dc2ae..c5cffa4ea 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -10,20 +10,24 @@ on: - "**" # every branch - "!gh-pages" # exclude gh-pages branch - "!stage*" # exclude branches beginning with stage +permissions: + contents: read jobs: lint: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 # enforce the same check as pre-commit # but only run important checks - - uses: pre-commit/action@v3.0.1 + - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 with: extra_args: codespell --all-files - - uses: pre-commit/action@v3.0.1 + - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 with: extra_args: ruff --all-files - - uses: pre-commit/action@v3.0.1 + - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 with: extra_args: ruff-format --all-files diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index a3f2bc5c8..934eebc16 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -24,6 +24,9 @@ on: - "pixi.lock" - ".github/workflows/test.yaml" +permissions: + contents: read + jobs: test: runs-on: ubuntu-latest @@ -40,10 +43,12 @@ jobs: mysql-image: ["datajoint/mysql:8.0", "mysql:8.4"] name: test (${{ matrix.environment }}, mysql=${{ matrix.mysql-image }}) steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false - name: Set up pixi - uses: prefix-dev/setup-pixi@v0.9.3 + uses: prefix-dev/setup-pixi@82d477f15f3a381dbcc8adc1206ce643fe110fb7 # v0.9.3 with: cache: true locked: false @@ -58,10 +63,12 @@ jobs: unit-tests: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false - name: Set up pixi - uses: prefix-dev/setup-pixi@v0.9.3 + uses: prefix-dev/setup-pixi@82d477f15f3a381dbcc8adc1206ce643fe110fb7 # v0.9.3 with: cache: true locked: false @@ -84,12 +91,13 @@ jobs: python-version: ["3.10", "3.14", "3.15"] name: unit-tests-windows (py${{ matrix.python-version }}) steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: fetch-depth: 0 # hatch-vcs derives the version from git history/tags + persist-credentials: false - name: Set up Python - uses: actions/setup-python@v5 + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: ${{ matrix.python-version }} From a98fd31f8704828c18881e4be55d0413aeaa9825 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Fri, 6 Nov 2026 09:10:30 -0600 Subject: [PATCH 10/37] fix: raise pandas and pymysql minimums, add a deepdiff minimum - pandas>=2.2.2: pandas does not cap numpy, so pandas 1.5.3 with numpy 2 installs and then fails on import (numpy.dtype size changed). 2.2.2 is the first pandas built against numpy 2; 2.2.1 still requires numpy<2. - deepdiff>=6.6.0: DeepHash(ignore_iterable_order=...) first appears in 6.4, and deepdiff before 6.6 uses np.float_, which numpy 2 removed. - pymysql>=1.0.0: connections pass ssl_disabled, which pymysql 0.x does not accept, so every MySQL connection fails on 0.7.2 through 0.10.1. Full suite on Python 3.10 with every core dependency at its minimum passes, and again with numpy 2.2.6 in place of numpy 1.22.4. --- pixi.lock | 10 +++++----- pyproject.toml | 10 +++++++--- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/pixi.lock b/pixi.lock index 78dd44bd7..d5432cac9 100644 --- a/pixi.lock +++ b/pixi.lock @@ -4495,19 +4495,19 @@ packages: requires_python: '>=3.8' - pypi: ./ name: datajoint - version: 2.3.5.dev42+g3c912c461.d20261105 - sha256: d1322b6612f5817610862f08fde2d86a402995b9be0cfdf208c8935ef04defe4 + version: 2.3.5.dev43+ga827d2f02.d20261106 + sha256: 12ab4fbf08f9c5ce4f99e477cf65cd2b1f24a2f1b03e4099d4b7641458b29619 requires_dist: - - deepdiff - deepdiff<9 ; python_full_version >= '3.15' + - deepdiff>=6.6.0 - fsspec>=2023.1.0 - networkx>=3.0 - numpy>=1.22.4 - packaging>=22.0 - - pandas>=1.5.3 + - pandas>=2.2.2 - pydantic-settings>=2.0.0 - pydot>=3.0.0 - - pymysql>=0.7.2 + - pymysql>=1.0.0 - pyparsing>=3.1.1 - tqdm>=4.66.3 - pyarrow>=14.0.0 ; extra == 'arrow' diff --git a/pyproject.toml b/pyproject.toml index a318ed1d1..a3dab9712 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,15 +7,19 @@ name = "datajoint" dynamic = ["version"] dependencies = [ "numpy>=1.22.4", - "pymysql>=0.7.2", - "deepdiff", + # pymysql 1.0 adds the ssl_disabled connection option. + "pymysql>=1.0.0", + # deepdiff 6.4 adds DeepHash(ignore_iterable_order=...); 6.6 supports numpy 2. + "deepdiff>=6.6.0", # deepdiff 9 requires cachebox<6, which ships no Python 3.15 wheels and cannot # be built for 3.15 (PyO3 0.27). Drop once deepdiff accepts cachebox 6. "deepdiff<9; python_version >= '3.15'", # pyparsing 3.1.0 drops the quotes from quoted defaults (= ""), which # declares the attribute without a default. "pyparsing>=3.1.1", - "pandas>=1.5.3", + # pandas 2.2.2 is the first release built against numpy 2; older pandas + # fails on import when numpy 2 is installed. + "pandas>=2.2.2", # CVE-2024-34062 "tqdm>=4.66.3", "networkx>=3.0", From c9e65d9041536c3a00f3163a4135d9136fbefc36 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Wed, 4 Nov 2026 15:46:33 -0600 Subject: [PATCH 11/37] fix: use two-digit hour in dependabot schedule time Dependabot rejects time "9:00" (must match ^\d\d:\d\d$), so the config failed to parse and no GitHub Actions updates were scheduled. (cherry picked from commit 247125c9105d25c786fe52dc115d48bdb669f9bf) --- .github/dependabot.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 267fa1d43..0b0fbc610 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,7 +5,7 @@ updates: schedule: interval: "monthly" day: "wednesday" - time: "9:00" + time: "09:00" timezone: "America/Chicago" groups: all-actions: From b2b4b5a7a872964d1b4c6d8a53f2ed8325fdafe1 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Fri, 6 Nov 2026 09:25:12 -0600 Subject: [PATCH 12/37] ci: run pre-commit directly so every lint action is pinned by SHA pre-commit/action calls actions/cache by tag and installs an unpinned pre-commit. Run the same steps directly: pre-commit pinned to a version and actions/cache pinned by SHA. --- .github/workflows/lint.yaml | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index c5cffa4ea..bad589202 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -21,13 +21,14 @@ jobs: persist-credentials: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 # enforce the same check as pre-commit - # but only run important checks - - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 + # but only run important checks. + # These steps are what pre-commit/action does, written out so that every + # action is pinned by SHA (pre-commit/action calls actions/cache by tag). + - run: python -m pip install pre-commit==4.7.0 + - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: - extra_args: codespell --all-files - - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 - with: - extra_args: ruff --all-files - - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 - with: - extra_args: ruff-format --all-files + path: ~/.cache/pre-commit + key: pre-commit-3|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml') }} + - run: pre-commit run --show-diff-on-failure --color=always codespell --all-files + - run: pre-commit run --show-diff-on-failure --color=always ruff --all-files + - run: pre-commit run --show-diff-on-failure --color=always ruff-format --all-files From 5b256aef930896adae7374feb9da189474f38b2e Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Fri, 6 Nov 2026 09:25:36 -0600 Subject: [PATCH 13/37] ci: declare workflow permissions after the name, clear of the triggers PR 1588 adds a workflow_call trigger just before jobs:, where the permissions block was, so the two PRs conflicted. --- .github/workflows/lint.yaml | 4 ++-- .github/workflows/test.yaml | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index bad589202..456b254c7 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -1,4 +1,6 @@ name: Lint +permissions: + contents: read on: push: branches: @@ -10,8 +12,6 @@ on: - "**" # every branch - "!gh-pages" # exclude gh-pages branch - "!stage*" # exclude branches beginning with stage -permissions: - contents: read jobs: lint: runs-on: ubuntu-latest diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 934eebc16..3794f1a2a 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -1,5 +1,8 @@ name: Test +permissions: + contents: read + on: push: branches: @@ -24,9 +27,6 @@ on: - "pixi.lock" - ".github/workflows/test.yaml" -permissions: - contents: read - jobs: test: runs-on: ubuntu-latest From cc4ca9e3d971bac87a697d959e48a42bfa1ba2f0 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Fri, 6 Nov 2026 09:21:04 -0600 Subject: [PATCH 14/37] ci: test the declared minimum versions; raise deepdiff and pymysql minimums A new test job runs the full suite on Python 3.10 with every runtime dependency pinned at the minimum pyproject.toml declares. .github/scripts/minimum_requirements.py derives the pins and fails when a runtime dependency declares no minimum. deepdiff and pymysql now start at the first release without known vulnerabilities rather than the oldest that works: deepdiff>=8.6.2 (CVE-2025-58367, CVE-2026-33155; was 6.6.0) and pymysql>=1.1.1 (CVE-2024-36039; was 1.0.0). pixi.lock moves deepdiff from 8.6.1 to 9.1.0 where Python < 3.15. --- .github/scripts/minimum_requirements.py | 81 ++++++++++++++++++++++++ .github/workflows/test.yaml | 38 +++++++++++ pixi.lock | 84 +++++++++++-------------- pyproject.toml | 10 +-- 4 files changed, 162 insertions(+), 51 deletions(-) create mode 100644 .github/scripts/minimum_requirements.py diff --git a/.github/scripts/minimum_requirements.py b/.github/scripts/minimum_requirements.py new file mode 100644 index 000000000..4801e2937 --- /dev/null +++ b/.github/scripts/minimum_requirements.py @@ -0,0 +1,81 @@ +"""Print pins for the minimum version of each runtime dependency. + +Reads [project].dependencies from pyproject.toml and prints one `name==minimum` +line per dependency that applies to the given Python version. CI installs the +package with these as constraints, so the test suite runs against the oldest +versions that pyproject.toml admits. Optional extras are not pinned. + +Every applicable dependency must declare a minimum (>=, ==, or ~=). A +dependency without one is an error: GitHub's dependency graph omits it, and +its oldest release is untested. + +Usage: python minimum_requirements.py [pyproject.toml] [--python 3.10] +""" + +import argparse +import re +import sys + +from packaging.requirements import Requirement +from packaging.specifiers import SpecifierSet +from packaging.utils import canonicalize_name +from packaging.version import Version + +try: + import tomllib +except ModuleNotFoundError: # Python 3.10 + import tomli as tomllib + + +def python_version(value: str) -> str: + if not re.fullmatch(r"3\.\d+", value): + raise argparse.ArgumentTypeError(f"expected a version like 3.10, got {value!r}") + return value + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("pyproject", nargs="?", default="pyproject.toml") + parser.add_argument("--python", type=python_version, default="3.10", help="Python version to evaluate markers for") + args = parser.parse_args() + + with open(args.pyproject, "rb") as f: + dependencies = tomllib.load(f)["project"]["dependencies"] + + # A dependency may span several lines, e.g. a minimum plus an upper bound + # under a marker. Combine the applicable lines per package. + environment = {"python_version": args.python, "python_full_version": f"{args.python}.0"} + specifiers: dict[str, SpecifierSet] = {} + for line in dependencies: + req = Requirement(line) + if req.marker is not None and not req.marker.evaluate(environment): + continue + name = canonicalize_name(req.name) + specifiers[name] = specifiers.get(name, SpecifierSet()) & req.specifier + + pins, errors = {}, [] + for name, specifier in sorted(specifiers.items()): + bounds = [s.version for s in specifier if s.operator in (">=", "==", "~=")] + if not bounds: + errors.append(f"{name} declares no minimum version") + continue + if any("*" in bound for bound in bounds): + errors.append(f"{name}: wildcard versions are not supported ({specifier})") + continue + minimum = max(bounds, key=Version) + if minimum not in specifier: + errors.append(f"{name}: minimum {minimum} is excluded by {specifier}") + continue + pins[name] = minimum + + if errors: + for error in errors: + print(f"error: {error}", file=sys.stderr) + return 1 + for name, version in pins.items(): + print(f"{name}=={version}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index a3f2bc5c8..f5404b036 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -11,6 +11,7 @@ on: - "tests/**" - "pyproject.toml" - "pixi.lock" + - ".github/scripts/minimum_requirements.py" - ".github/workflows/test.yaml" pull_request: branches: @@ -22,6 +23,7 @@ on: - "tests/**" - "pyproject.toml" - "pixi.lock" + - ".github/scripts/minimum_requirements.py" - ".github/workflows/test.yaml" jobs: @@ -104,3 +106,39 @@ jobs: - name: Run unit tests run: pytest tests/unit -v + + # Minimum versions: run the full suite on the oldest supported Python with + # every runtime dependency ([project].dependencies; extras are not pinned) at + # the minimum pyproject.toml declares, so those minimums stay true. + # minimum_requirements.py also fails the job when a runtime dependency + # declares no minimum. Uses pip, not pixi, because pixi resolves the newest + # versions from the lock file. + test-min-versions: + runs-on: ubuntu-latest + timeout-minutes: 45 + name: test (minimum dependency versions, py3.10) + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + fetch-depth: 0 # hatch-vcs derives the version from git history/tags + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.10" + + - name: Install graphviz + run: sudo apt-get update && sudo apt-get install -y graphviz + + - name: Pin runtime dependencies at their minimums + run: | + python -m pip install tomli==2.5.0 packaging==26.3 + python .github/scripts/minimum_requirements.py --python 3.10 > "$RUNNER_TEMP/minimum.txt" + cat "$RUNNER_TEMP/minimum.txt" + + - name: Install package with test extras + run: python -m pip install -e ".[test]" -c "$RUNNER_TEMP/minimum.txt" + + - name: Run tests + run: python -m pytest tests/ diff --git a/pixi.lock b/pixi.lock index d5432cac9..1398fa337 100644 --- a/pixi.lock +++ b/pixi.lock @@ -100,7 +100,8 @@ environments: - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxtst-1.2.5-hb9d3cd8_3.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/zstd-1.5.7-hb8e6e7a_2.conda - pypi: https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/13/95/450765b971a3bed9d7cf003c3833c1976482eb83b0241b6dbb840a25b43b/cachebox-5.2.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl + - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/1f/5f4a3cd9e4440e9d9bc78ad0a91a1c8d46b4d429d5239ebe6793c9fe5c41/fsspec-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/eb/8d/776adee7bbf76365fdd7f2552710282c79a4ead5d2a46408c9043a2b70ba/networkx-3.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/9a/a5/bf3db6e66c4b160d6ea10b534c381a1955dfab34cb1017ea93aa33c70ed3/numpy-2.3.3-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl @@ -225,7 +226,8 @@ environments: - conda: https://conda.anaconda.org/conda-forge/linux-aarch64/xorg-xorgproto-2024.1-h86ecc28_1.conda - conda: https://conda.anaconda.org/conda-forge/linux-aarch64/zstd-1.5.7-hbcf94c1_2.conda - pypi: https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/46/17/794e5f93e0a172aa14ecd692f6d89bdf094f71eb35fa923d0a0af25cef1c/cachebox-5.2.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl + - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/1f/5f4a3cd9e4440e9d9bc78ad0a91a1c8d46b4d429d5239ebe6793c9fe5c41/fsspec-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/eb/8d/776adee7bbf76365fdd7f2552710282c79a4ead5d2a46408c9043a2b70ba/networkx-3.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/3e/d1/913fe563820f3c6b079f992458f7331278dcd7ba8427e8e745af37ddb44f/numpy-2.3.4-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl @@ -305,7 +307,8 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/tzdata-2025b-h78e105d_0.conda - conda: https://conda.anaconda.org/conda-forge/osx-arm64/zstd-1.5.7-h6491c7d_2.conda - pypi: https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/cd/87/45f834154f79721e5b64a80ffab4f9710834c4f9c01fa977f94a9116c32a/cachebox-5.2.3-cp313-cp313-macosx_11_0_arm64.whl + - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/1f/5f4a3cd9e4440e9d9bc78ad0a91a1c8d46b4d429d5239ebe6793c9fe5c41/fsspec-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/eb/8d/776adee7bbf76365fdd7f2552710282c79a4ead5d2a46408c9043a2b70ba/networkx-3.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/3e/46/bdd3370dcea2f95ef14af79dbf81e6927102ddf1cc54adc0024d61252fd9/numpy-2.3.4-cp313-cp313-macosx_11_0_arm64.whl @@ -435,6 +438,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/25/8a/c46dcc25341b5bce5472c718902eb3d38600a903b14fa6aeecef3f21a46f/asttokens-3.0.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fb/51/08f32aea872253173f513ba68122f4300966290677c8e59887b4ffd5d957/botocore-1.42.70-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/13/95/450765b971a3bed9d7cf003c3833c1976482eb83b0241b6dbb840a25b43b/cachebox-5.2.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl - pypi: https://files.pythonhosted.org/packages/e5/48/1549795ba7742c948d2ad169c1c8cdbae65bc450d6cd753d124b17c8cd32/certifi-2025.8.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/98/df/0a1755e750013a2081e863e7cd37e0cdd02664372c754e5560099eb7aa44/cffi-2.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl - pypi: https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl @@ -445,7 +449,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/34/71/1ea5a7352ae516d5512d17babe7e1b87d9db5150b21f794b1377eac1edc0/cryptography-46.0.6-cp311-abi3-manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/33/6b/e0547afaf41bf2c42e52430072fa5658766e3d65bd4b03a563d1b6336f57/distlib-0.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl @@ -629,6 +633,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/25/8a/c46dcc25341b5bce5472c718902eb3d38600a903b14fa6aeecef3f21a46f/asttokens-3.0.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fb/51/08f32aea872253173f513ba68122f4300966290677c8e59887b4ffd5d957/botocore-1.42.70-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/46/17/794e5f93e0a172aa14ecd692f6d89bdf094f71eb35fa923d0a0af25cef1c/cachebox-5.2.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl - pypi: https://files.pythonhosted.org/packages/e4/37/af0d2ef3967ac0d6113837b44a4f0bfe1328c2b9763bd5b1744520e5cfed/certifi-2025.10.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/a9/f5/a2c23eb03b61a0b8747f211eb716446c826ad66818ddc7810cc2cc19b3f2/cffi-2.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl - pypi: https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl @@ -639,7 +644,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/d4/12/123be7292674abf76b21ac1fc0e1af50661f0e5b8f0ec8285faac18eb99e/cryptography-46.0.6-cp311-abi3-manylinux_2_28_aarch64.whl - pypi: https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/33/6b/e0547afaf41bf2c42e52430072fa5658766e3d65bd4b03a563d1b6336f57/distlib-0.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl @@ -778,6 +783,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/25/8a/c46dcc25341b5bce5472c718902eb3d38600a903b14fa6aeecef3f21a46f/asttokens-3.0.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fb/51/08f32aea872253173f513ba68122f4300966290677c8e59887b4ffd5d957/botocore-1.42.70-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/cd/87/45f834154f79721e5b64a80ffab4f9710834c4f9c01fa977f94a9116c32a/cachebox-5.2.3-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/e4/37/af0d2ef3967ac0d6113837b44a4f0bfe1328c2b9763bd5b1744520e5cfed/certifi-2025.10.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4a/d2/a6c0296814556c68ee32009d9c2ad4f85f2707cdecfd7727951ec228005d/cffi-2.0.0-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl @@ -788,7 +794,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/47/23/9285e15e3bc57325b0a72e592921983a701efc1ee8f91c06c5f0235d86d9/cryptography-46.0.6-cp311-abi3-macosx_10_9_universal2.whl - pypi: https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/33/6b/e0547afaf41bf2c42e52430072fa5658766e3d65bd4b03a563d1b6336f57/distlib-0.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl @@ -968,6 +974,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/25/8a/c46dcc25341b5bce5472c718902eb3d38600a903b14fa6aeecef3f21a46f/asttokens-3.0.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fb/51/08f32aea872253173f513ba68122f4300966290677c8e59887b4ffd5d957/botocore-1.42.70-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/13/95/450765b971a3bed9d7cf003c3833c1976482eb83b0241b6dbb840a25b43b/cachebox-5.2.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl - pypi: https://files.pythonhosted.org/packages/e5/48/1549795ba7742c948d2ad169c1c8cdbae65bc450d6cd753d124b17c8cd32/certifi-2025.8.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/98/df/0a1755e750013a2081e863e7cd37e0cdd02664372c754e5560099eb7aa44/cffi-2.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl - pypi: https://files.pythonhosted.org/packages/7e/95/42aa2156235cbc8fa61208aded06ef46111c4d3f0de233107b3f38631803/charset_normalizer-3.4.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl @@ -976,7 +983,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/34/71/1ea5a7352ae516d5512d17babe7e1b87d9db5150b21f794b1377eac1edc0/cryptography-46.0.6-cp311-abi3-manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/f5/11/02ebebb09ff2104b690457cb7bc6ed700c9e0ce88cf581486bb0a5d3c88b/faker-37.8.0-py3-none-any.whl @@ -1152,6 +1159,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/25/8a/c46dcc25341b5bce5472c718902eb3d38600a903b14fa6aeecef3f21a46f/asttokens-3.0.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fb/51/08f32aea872253173f513ba68122f4300966290677c8e59887b4ffd5d957/botocore-1.42.70-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/46/17/794e5f93e0a172aa14ecd692f6d89bdf094f71eb35fa923d0a0af25cef1c/cachebox-5.2.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl - pypi: https://files.pythonhosted.org/packages/e4/37/af0d2ef3967ac0d6113837b44a4f0bfe1328c2b9763bd5b1744520e5cfed/certifi-2025.10.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/a9/f5/a2c23eb03b61a0b8747f211eb716446c826ad66818ddc7810cc2cc19b3f2/cffi-2.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl - pypi: https://files.pythonhosted.org/packages/7d/62/73a6d7450829655a35bb88a88fca7d736f9882a27eacdca2c6d505b57e2e/charset_normalizer-3.4.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl @@ -1160,7 +1168,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/d4/12/123be7292674abf76b21ac1fc0e1af50661f0e5b8f0ec8285faac18eb99e/cryptography-46.0.6-cp311-abi3-manylinux_2_28_aarch64.whl - pypi: https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/8e/98/2c050dec90e295a524c9b65c4cb9e7c302386a296b2938710448cbd267d5/faker-37.12.0-py3-none-any.whl @@ -1291,6 +1299,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/25/8a/c46dcc25341b5bce5472c718902eb3d38600a903b14fa6aeecef3f21a46f/asttokens-3.0.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fb/51/08f32aea872253173f513ba68122f4300966290677c8e59887b4ffd5d957/botocore-1.42.70-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/cd/87/45f834154f79721e5b64a80ffab4f9710834c4f9c01fa977f94a9116c32a/cachebox-5.2.3-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/e4/37/af0d2ef3967ac0d6113837b44a4f0bfe1328c2b9763bd5b1744520e5cfed/certifi-2025.10.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4a/d2/a6c0296814556c68ee32009d9c2ad4f85f2707cdecfd7727951ec228005d/cffi-2.0.0-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/97/45/4b3a1239bbacd321068ea6e7ac28875b03ab8bc0aa0966452db17cd36714/charset_normalizer-3.4.4-cp313-cp313-macosx_10_13_universal2.whl @@ -1299,7 +1308,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/47/23/9285e15e3bc57325b0a72e592921983a701efc1ee8f91c06c5f0235d86d9/cryptography-46.0.6-cp311-abi3-macosx_10_9_universal2.whl - pypi: https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/8e/98/2c050dec90e295a524c9b65c4cb9e7c302386a296b2938710448cbd267d5/faker-37.12.0-py3-none-any.whl @@ -3558,6 +3567,16 @@ packages: version: 5.2.3 sha256: ad16d733219f4cab3eec6533af30ab7b9c919c6e3e22ad1ef4eb82629a62edef requires_python: '>=3.9' +- pypi: https://files.pythonhosted.org/packages/13/95/450765b971a3bed9d7cf003c3833c1976482eb83b0241b6dbb840a25b43b/cachebox-5.2.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl + name: cachebox + version: 5.2.3 + sha256: 10bedf96db8f9766cc956f9adcc623e604264e5d6fa2e255432f8c2ed7519143 + requires_python: '>=3.9' +- pypi: https://files.pythonhosted.org/packages/46/17/794e5f93e0a172aa14ecd692f6d89bdf094f71eb35fa923d0a0af25cef1c/cachebox-5.2.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl + name: cachebox + version: 5.2.3 + sha256: b5ff26bfd8f7e95b3becf6d5f65c25edaca50fa68078868648b70d79bcccc260 + requires_python: '>=3.9' - pypi: https://files.pythonhosted.org/packages/78/c4/c9b3fa764ac5420a9e079ad53fa8840d4a26b74c4ccda56acbef49cf76ff/cachebox-5.2.3-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl name: cachebox version: 5.2.3 @@ -3578,6 +3597,11 @@ packages: version: 5.2.3 sha256: 56cb03ec6289a2ac5daf7422d755683324f02d821bfa796087100df2a7ebd5de requires_python: '>=3.9' +- pypi: https://files.pythonhosted.org/packages/cd/87/45f834154f79721e5b64a80ffab4f9710834c4f9c01fa977f94a9116c32a/cachebox-5.2.3-cp313-cp313-macosx_11_0_arm64.whl + name: cachebox + version: 5.2.3 + sha256: 40ac878af00d5969862c1f6bc076de1e34ca248662fce6aecca1761f52e33e32 + requires_python: '>=3.9' - pypi: https://files.pythonhosted.org/packages/fc/62/33aaade81b181d5191cc39c867c297aa7c65f3191aa9749bf99b77496b88/cachebox-5.2.3-cp314-cp314-macosx_11_0_arm64.whl name: cachebox version: 5.2.3 @@ -4495,11 +4519,11 @@ packages: requires_python: '>=3.8' - pypi: ./ name: datajoint - version: 2.3.5.dev43+ga827d2f02.d20261106 - sha256: 12ab4fbf08f9c5ce4f99e477cf65cd2b1f24a2f1b03e4099d4b7641458b29619 + version: 2.3.5.dev44+ga98fd31f8.d20261106 + sha256: c46e98faa841d295d460fd73ac6906a92a8cbdada81d3a0c93769a13b017a96f requires_dist: - deepdiff<9 ; python_full_version >= '3.15' - - deepdiff>=6.6.0 + - deepdiff>=8.6.2 - fsspec>=2023.1.0 - networkx>=3.0 - numpy>=1.22.4 @@ -4507,7 +4531,7 @@ packages: - pandas>=2.2.2 - pydantic-settings>=2.0.0 - pydot>=3.0.0 - - pymysql>=1.0.0 + - pymysql>=1.1.1 - pyparsing>=3.1.1 - tqdm>=4.66.3 - pyarrow>=14.0.0 ; extra == 'arrow' @@ -4605,40 +4629,6 @@ packages: version: 5.3.1 sha256: f47fe6fdbd2edd623ecfe36875d37aba411624e2670dd395dddae1358689bb3c requires_python: '>=3.8' -- pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl - name: deepdiff - version: 8.6.1 - sha256: ee8708a7f7d37fb273a541fa24ad010ed484192cd0c4ffc0fa0ed5e2d4b9e78b - requires_dist: - - orderly-set>=5.4.1,<6 - - click~=8.1.0 ; extra == 'cli' - - pyyaml~=6.0.0 ; extra == 'cli' - - coverage~=7.6.0 ; extra == 'coverage' - - bump2version~=1.0.0 ; extra == 'dev' - - jsonpickle~=4.0.0 ; extra == 'dev' - - ipdb~=0.13.0 ; extra == 'dev' - - numpy~=2.2.0 ; python_full_version >= '3.10' and extra == 'dev' - - numpy~=2.0 ; python_full_version < '3.10' and extra == 'dev' - - python-dateutil~=2.9.0 ; extra == 'dev' - - orjson~=3.10.0 ; extra == 'dev' - - tomli~=2.2.0 ; extra == 'dev' - - tomli-w~=1.2.0 ; extra == 'dev' - - pandas~=2.2.0 ; extra == 'dev' - - polars~=1.21.0 ; extra == 'dev' - - nox==2025.5.1 ; extra == 'dev' - - uuid6==2025.0.1 ; extra == 'dev' - - sphinx~=6.2.0 ; extra == 'docs' - - sphinx-sitemap~=2.6.0 ; extra == 'docs' - - sphinxemoji~=0.3.0 ; extra == 'docs' - - orjson ; extra == 'optimize' - - flake8~=7.1.0 ; extra == 'static' - - flake8-pyproject~=1.2.3 ; extra == 'static' - - pydantic~=2.10.0 ; extra == 'static' - - pytest~=8.3.0 ; extra == 'test' - - pytest-benchmark~=5.1.0 ; extra == 'test' - - pytest-cov~=6.0.0 ; extra == 'test' - - python-dotenv~=1.0.0 ; extra == 'test' - requires_python: '>=3.9' - pypi: https://files.pythonhosted.org/packages/2b/5f/c52bd1255db763d0cdcb7084d2e90c42119cb229302c56bdf1d0aa78abd2/deepdiff-8.6.2-py3-none-any.whl name: deepdiff version: 8.6.2 diff --git a/pyproject.toml b/pyproject.toml index a3dab9712..c14fc55bb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,10 +7,12 @@ name = "datajoint" dynamic = ["version"] dependencies = [ "numpy>=1.22.4", - # pymysql 1.0 adds the ssl_disabled connection option. - "pymysql>=1.0.0", - # deepdiff 6.4 adds DeepHash(ignore_iterable_order=...); 6.6 supports numpy 2. - "deepdiff>=6.6.0", + # pymysql 1.0 adds the ssl_disabled connection option; 1.1.1 fixes + # CVE-2024-36039. + "pymysql>=1.1.1", + # deepdiff 6.4 adds DeepHash(ignore_iterable_order=...); 6.6 supports numpy 2; + # 8.6.2 fixes CVE-2025-58367 and CVE-2026-33155. + "deepdiff>=8.6.2", # deepdiff 9 requires cachebox<6, which ships no Python 3.15 wheels and cannot # be built for 3.15 (PyO3 0.27). Drop once deepdiff accepts cachebox 6. "deepdiff<9; python_version >= '3.15'", From a69650bbc8d7afc31c8d40f6dd6a28782867109c Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Fri, 6 Nov 2026 10:05:39 -0600 Subject: [PATCH 15/37] fix: keep deepdiff>=6.6.0; its advisories do not affect DeepHash CVE-2025-58367 and CVE-2026-33155 are in deepdiff's Delta class and pickle_load. datajoint uses only DeepHash, so the oldest working version stays the minimum and Dependabot reports the advisories. pymysql stays at 1.1.1 for CVE-2024-36039. --- pixi.lock | 82 ++++++++++++++++++++++++++++---------------------- pyproject.toml | 7 +++-- 2 files changed, 50 insertions(+), 39 deletions(-) diff --git a/pixi.lock b/pixi.lock index 1398fa337..51ea3feda 100644 --- a/pixi.lock +++ b/pixi.lock @@ -100,8 +100,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/linux-64/xorg-libxtst-1.2.5-hb9d3cd8_3.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/zstd-1.5.7-hb8e6e7a_2.conda - pypi: https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/13/95/450765b971a3bed9d7cf003c3833c1976482eb83b0241b6dbb840a25b43b/cachebox-5.2.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl - - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/1f/5f4a3cd9e4440e9d9bc78ad0a91a1c8d46b4d429d5239ebe6793c9fe5c41/fsspec-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/eb/8d/776adee7bbf76365fdd7f2552710282c79a4ead5d2a46408c9043a2b70ba/networkx-3.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/9a/a5/bf3db6e66c4b160d6ea10b534c381a1955dfab34cb1017ea93aa33c70ed3/numpy-2.3.3-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl @@ -226,8 +225,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/linux-aarch64/xorg-xorgproto-2024.1-h86ecc28_1.conda - conda: https://conda.anaconda.org/conda-forge/linux-aarch64/zstd-1.5.7-hbcf94c1_2.conda - pypi: https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/46/17/794e5f93e0a172aa14ecd692f6d89bdf094f71eb35fa923d0a0af25cef1c/cachebox-5.2.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl - - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/1f/5f4a3cd9e4440e9d9bc78ad0a91a1c8d46b4d429d5239ebe6793c9fe5c41/fsspec-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/eb/8d/776adee7bbf76365fdd7f2552710282c79a4ead5d2a46408c9043a2b70ba/networkx-3.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/3e/d1/913fe563820f3c6b079f992458f7331278dcd7ba8427e8e745af37ddb44f/numpy-2.3.4-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl @@ -307,8 +305,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/tzdata-2025b-h78e105d_0.conda - conda: https://conda.anaconda.org/conda-forge/osx-arm64/zstd-1.5.7-h6491c7d_2.conda - pypi: https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/cd/87/45f834154f79721e5b64a80ffab4f9710834c4f9c01fa977f94a9116c32a/cachebox-5.2.3-cp313-cp313-macosx_11_0_arm64.whl - - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/d5/1f/5f4a3cd9e4440e9d9bc78ad0a91a1c8d46b4d429d5239ebe6793c9fe5c41/fsspec-2026.3.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/eb/8d/776adee7bbf76365fdd7f2552710282c79a4ead5d2a46408c9043a2b70ba/networkx-3.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/3e/46/bdd3370dcea2f95ef14af79dbf81e6927102ddf1cc54adc0024d61252fd9/numpy-2.3.4-cp313-cp313-macosx_11_0_arm64.whl @@ -438,7 +435,6 @@ environments: - pypi: https://files.pythonhosted.org/packages/25/8a/c46dcc25341b5bce5472c718902eb3d38600a903b14fa6aeecef3f21a46f/asttokens-3.0.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fb/51/08f32aea872253173f513ba68122f4300966290677c8e59887b4ffd5d957/botocore-1.42.70-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/13/95/450765b971a3bed9d7cf003c3833c1976482eb83b0241b6dbb840a25b43b/cachebox-5.2.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl - pypi: https://files.pythonhosted.org/packages/e5/48/1549795ba7742c948d2ad169c1c8cdbae65bc450d6cd753d124b17c8cd32/certifi-2025.8.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/98/df/0a1755e750013a2081e863e7cd37e0cdd02664372c754e5560099eb7aa44/cffi-2.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl - pypi: https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl @@ -449,7 +445,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/34/71/1ea5a7352ae516d5512d17babe7e1b87d9db5150b21f794b1377eac1edc0/cryptography-46.0.6-cp311-abi3-manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/33/6b/e0547afaf41bf2c42e52430072fa5658766e3d65bd4b03a563d1b6336f57/distlib-0.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl @@ -633,7 +629,6 @@ environments: - pypi: https://files.pythonhosted.org/packages/25/8a/c46dcc25341b5bce5472c718902eb3d38600a903b14fa6aeecef3f21a46f/asttokens-3.0.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fb/51/08f32aea872253173f513ba68122f4300966290677c8e59887b4ffd5d957/botocore-1.42.70-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/46/17/794e5f93e0a172aa14ecd692f6d89bdf094f71eb35fa923d0a0af25cef1c/cachebox-5.2.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl - pypi: https://files.pythonhosted.org/packages/e4/37/af0d2ef3967ac0d6113837b44a4f0bfe1328c2b9763bd5b1744520e5cfed/certifi-2025.10.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/a9/f5/a2c23eb03b61a0b8747f211eb716446c826ad66818ddc7810cc2cc19b3f2/cffi-2.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl - pypi: https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl @@ -644,7 +639,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/d4/12/123be7292674abf76b21ac1fc0e1af50661f0e5b8f0ec8285faac18eb99e/cryptography-46.0.6-cp311-abi3-manylinux_2_28_aarch64.whl - pypi: https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/33/6b/e0547afaf41bf2c42e52430072fa5658766e3d65bd4b03a563d1b6336f57/distlib-0.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl @@ -783,7 +778,6 @@ environments: - pypi: https://files.pythonhosted.org/packages/25/8a/c46dcc25341b5bce5472c718902eb3d38600a903b14fa6aeecef3f21a46f/asttokens-3.0.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fb/51/08f32aea872253173f513ba68122f4300966290677c8e59887b4ffd5d957/botocore-1.42.70-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/cd/87/45f834154f79721e5b64a80ffab4f9710834c4f9c01fa977f94a9116c32a/cachebox-5.2.3-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/e4/37/af0d2ef3967ac0d6113837b44a4f0bfe1328c2b9763bd5b1744520e5cfed/certifi-2025.10.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4a/d2/a6c0296814556c68ee32009d9c2ad4f85f2707cdecfd7727951ec228005d/cffi-2.0.0-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl @@ -794,7 +788,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/47/23/9285e15e3bc57325b0a72e592921983a701efc1ee8f91c06c5f0235d86d9/cryptography-46.0.6-cp311-abi3-macosx_10_9_universal2.whl - pypi: https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/33/6b/e0547afaf41bf2c42e52430072fa5658766e3d65bd4b03a563d1b6336f57/distlib-0.4.0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl @@ -974,7 +968,6 @@ environments: - pypi: https://files.pythonhosted.org/packages/25/8a/c46dcc25341b5bce5472c718902eb3d38600a903b14fa6aeecef3f21a46f/asttokens-3.0.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fb/51/08f32aea872253173f513ba68122f4300966290677c8e59887b4ffd5d957/botocore-1.42.70-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/13/95/450765b971a3bed9d7cf003c3833c1976482eb83b0241b6dbb840a25b43b/cachebox-5.2.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl - pypi: https://files.pythonhosted.org/packages/e5/48/1549795ba7742c948d2ad169c1c8cdbae65bc450d6cd753d124b17c8cd32/certifi-2025.8.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/98/df/0a1755e750013a2081e863e7cd37e0cdd02664372c754e5560099eb7aa44/cffi-2.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl - pypi: https://files.pythonhosted.org/packages/7e/95/42aa2156235cbc8fa61208aded06ef46111c4d3f0de233107b3f38631803/charset_normalizer-3.4.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl @@ -983,7 +976,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/34/71/1ea5a7352ae516d5512d17babe7e1b87d9db5150b21f794b1377eac1edc0/cryptography-46.0.6-cp311-abi3-manylinux_2_28_x86_64.whl - pypi: https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/f5/11/02ebebb09ff2104b690457cb7bc6ed700c9e0ce88cf581486bb0a5d3c88b/faker-37.8.0-py3-none-any.whl @@ -1159,7 +1152,6 @@ environments: - pypi: https://files.pythonhosted.org/packages/25/8a/c46dcc25341b5bce5472c718902eb3d38600a903b14fa6aeecef3f21a46f/asttokens-3.0.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fb/51/08f32aea872253173f513ba68122f4300966290677c8e59887b4ffd5d957/botocore-1.42.70-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/46/17/794e5f93e0a172aa14ecd692f6d89bdf094f71eb35fa923d0a0af25cef1c/cachebox-5.2.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl - pypi: https://files.pythonhosted.org/packages/e4/37/af0d2ef3967ac0d6113837b44a4f0bfe1328c2b9763bd5b1744520e5cfed/certifi-2025.10.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/a9/f5/a2c23eb03b61a0b8747f211eb716446c826ad66818ddc7810cc2cc19b3f2/cffi-2.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl - pypi: https://files.pythonhosted.org/packages/7d/62/73a6d7450829655a35bb88a88fca7d736f9882a27eacdca2c6d505b57e2e/charset_normalizer-3.4.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl @@ -1168,7 +1160,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/d4/12/123be7292674abf76b21ac1fc0e1af50661f0e5b8f0ec8285faac18eb99e/cryptography-46.0.6-cp311-abi3-manylinux_2_28_aarch64.whl - pypi: https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/8e/98/2c050dec90e295a524c9b65c4cb9e7c302386a296b2938710448cbd267d5/faker-37.12.0-py3-none-any.whl @@ -1299,7 +1291,6 @@ environments: - pypi: https://files.pythonhosted.org/packages/25/8a/c46dcc25341b5bce5472c718902eb3d38600a903b14fa6aeecef3f21a46f/asttokens-3.0.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/fb/51/08f32aea872253173f513ba68122f4300966290677c8e59887b4ffd5d957/botocore-1.42.70-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/cd/87/45f834154f79721e5b64a80ffab4f9710834c4f9c01fa977f94a9116c32a/cachebox-5.2.3-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/e4/37/af0d2ef3967ac0d6113837b44a4f0bfe1328c2b9763bd5b1744520e5cfed/certifi-2025.10.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4a/d2/a6c0296814556c68ee32009d9c2ad4f85f2707cdecfd7727951ec228005d/cffi-2.0.0-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/97/45/4b3a1239bbacd321068ea6e7ac28875b03ab8bc0aa0966452db17cd36714/charset_normalizer-3.4.4-cp313-cp313-macosx_10_13_universal2.whl @@ -1308,7 +1299,7 @@ environments: - pypi: https://files.pythonhosted.org/packages/47/23/9285e15e3bc57325b0a72e592921983a701efc1ee8f91c06c5f0235d86d9/cryptography-46.0.6-cp311-abi3-macosx_10_9_universal2.whl - pypi: https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/4e/8c/f3147f5c4b73e7550fe5f9352eaa956ae838d5c51eb58e7a25b9f3e2643b/decorator-5.2.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/c7/26/4a2bad8eb430d8d805a4642c4bff25103a37548d74ab346f8b1e024abcc5/deepdiff-9.1.0-py3-none-any.whl + - pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/8e/98/2c050dec90e295a524c9b65c4cb9e7c302386a296b2938710448cbd267d5/faker-37.12.0-py3-none-any.whl @@ -3567,16 +3558,6 @@ packages: version: 5.2.3 sha256: ad16d733219f4cab3eec6533af30ab7b9c919c6e3e22ad1ef4eb82629a62edef requires_python: '>=3.9' -- pypi: https://files.pythonhosted.org/packages/13/95/450765b971a3bed9d7cf003c3833c1976482eb83b0241b6dbb840a25b43b/cachebox-5.2.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl - name: cachebox - version: 5.2.3 - sha256: 10bedf96db8f9766cc956f9adcc623e604264e5d6fa2e255432f8c2ed7519143 - requires_python: '>=3.9' -- pypi: https://files.pythonhosted.org/packages/46/17/794e5f93e0a172aa14ecd692f6d89bdf094f71eb35fa923d0a0af25cef1c/cachebox-5.2.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl - name: cachebox - version: 5.2.3 - sha256: b5ff26bfd8f7e95b3becf6d5f65c25edaca50fa68078868648b70d79bcccc260 - requires_python: '>=3.9' - pypi: https://files.pythonhosted.org/packages/78/c4/c9b3fa764ac5420a9e079ad53fa8840d4a26b74c4ccda56acbef49cf76ff/cachebox-5.2.3-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl name: cachebox version: 5.2.3 @@ -3597,11 +3578,6 @@ packages: version: 5.2.3 sha256: 56cb03ec6289a2ac5daf7422d755683324f02d821bfa796087100df2a7ebd5de requires_python: '>=3.9' -- pypi: https://files.pythonhosted.org/packages/cd/87/45f834154f79721e5b64a80ffab4f9710834c4f9c01fa977f94a9116c32a/cachebox-5.2.3-cp313-cp313-macosx_11_0_arm64.whl - name: cachebox - version: 5.2.3 - sha256: 40ac878af00d5969862c1f6bc076de1e34ca248662fce6aecca1761f52e33e32 - requires_python: '>=3.9' - pypi: https://files.pythonhosted.org/packages/fc/62/33aaade81b181d5191cc39c867c297aa7c65f3191aa9749bf99b77496b88/cachebox-5.2.3-cp314-cp314-macosx_11_0_arm64.whl name: cachebox version: 5.2.3 @@ -4519,11 +4495,11 @@ packages: requires_python: '>=3.8' - pypi: ./ name: datajoint - version: 2.3.5.dev44+ga98fd31f8.d20261106 - sha256: c46e98faa841d295d460fd73ac6906a92a8cbdada81d3a0c93769a13b017a96f + version: 2.3.5.dev45+gcc4ca9e3d.d20261106 + sha256: 204220782b38892346a27748aa110b40929b1a0075f07b5b72fabd073c84a924 requires_dist: - deepdiff<9 ; python_full_version >= '3.15' - - deepdiff>=8.6.2 + - deepdiff>=6.6.0 - fsspec>=2023.1.0 - networkx>=3.0 - numpy>=1.22.4 @@ -4629,6 +4605,40 @@ packages: version: 5.3.1 sha256: f47fe6fdbd2edd623ecfe36875d37aba411624e2670dd395dddae1358689bb3c requires_python: '>=3.8' +- pypi: https://files.pythonhosted.org/packages/f7/e6/efe534ef0952b531b630780e19cabd416e2032697019d5295defc6ef9bd9/deepdiff-8.6.1-py3-none-any.whl + name: deepdiff + version: 8.6.1 + sha256: ee8708a7f7d37fb273a541fa24ad010ed484192cd0c4ffc0fa0ed5e2d4b9e78b + requires_dist: + - orderly-set>=5.4.1,<6 + - click~=8.1.0 ; extra == 'cli' + - pyyaml~=6.0.0 ; extra == 'cli' + - coverage~=7.6.0 ; extra == 'coverage' + - bump2version~=1.0.0 ; extra == 'dev' + - jsonpickle~=4.0.0 ; extra == 'dev' + - ipdb~=0.13.0 ; extra == 'dev' + - numpy~=2.2.0 ; python_full_version >= '3.10' and extra == 'dev' + - numpy~=2.0 ; python_full_version < '3.10' and extra == 'dev' + - python-dateutil~=2.9.0 ; extra == 'dev' + - orjson~=3.10.0 ; extra == 'dev' + - tomli~=2.2.0 ; extra == 'dev' + - tomli-w~=1.2.0 ; extra == 'dev' + - pandas~=2.2.0 ; extra == 'dev' + - polars~=1.21.0 ; extra == 'dev' + - nox==2025.5.1 ; extra == 'dev' + - uuid6==2025.0.1 ; extra == 'dev' + - sphinx~=6.2.0 ; extra == 'docs' + - sphinx-sitemap~=2.6.0 ; extra == 'docs' + - sphinxemoji~=0.3.0 ; extra == 'docs' + - orjson ; extra == 'optimize' + - flake8~=7.1.0 ; extra == 'static' + - flake8-pyproject~=1.2.3 ; extra == 'static' + - pydantic~=2.10.0 ; extra == 'static' + - pytest~=8.3.0 ; extra == 'test' + - pytest-benchmark~=5.1.0 ; extra == 'test' + - pytest-cov~=6.0.0 ; extra == 'test' + - python-dotenv~=1.0.0 ; extra == 'test' + requires_python: '>=3.9' - pypi: https://files.pythonhosted.org/packages/2b/5f/c52bd1255db763d0cdcb7084d2e90c42119cb229302c56bdf1d0aa78abd2/deepdiff-8.6.2-py3-none-any.whl name: deepdiff version: 8.6.2 diff --git a/pyproject.toml b/pyproject.toml index c14fc55bb..75789801c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,9 +10,10 @@ dependencies = [ # pymysql 1.0 adds the ssl_disabled connection option; 1.1.1 fixes # CVE-2024-36039. "pymysql>=1.1.1", - # deepdiff 6.4 adds DeepHash(ignore_iterable_order=...); 6.6 supports numpy 2; - # 8.6.2 fixes CVE-2025-58367 and CVE-2026-33155. - "deepdiff>=8.6.2", + # deepdiff 6.4 adds DeepHash(ignore_iterable_order=...); 6.6 supports numpy 2. + # CVE-2025-58367 and CVE-2026-33155 (fixed in 8.6.2) affect Delta and + # pickle_load; datajoint uses only DeepHash. + "deepdiff>=6.6.0", # deepdiff 9 requires cachebox<6, which ships no Python 3.15 wheels and cannot # be built for 3.15 (PyO3 0.27). Drop once deepdiff accepts cachebox 6. "deepdiff<9; python_version >= '3.15'", From 45bfc7cc951efc521eeab1eeb69786937e4ce00d Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Fri, 6 Nov 2026 11:34:14 -0600 Subject: [PATCH 16/37] fix: a restricted right operand of a left join no longer drops unmatched rows aggr (exclude_nonmatching=False), extend, and union of operands with secondary attributes use a left join. A restriction on the right operand, including dj.Top, went into the outer WHERE, where it removed the left rows with no match. It is now applied inside a subquery for the right operand. An unrestricted right operand is joined directly, and inner joins are unchanged. Fixes #1650. --- src/datajoint/expression.py | 5 + tests/integration/test_aggr_left_join.py | 244 +++++++++++++++++++++++ 2 files changed, 249 insertions(+) create mode 100644 tests/integration/test_aggr_left_join.py diff --git a/src/datajoint/expression.py b/src/datajoint/expression.py index 1b5f5ac9e..3fafd3634 100644 --- a/src/datajoint/expression.py +++ b/src/datajoint/expression.py @@ -419,6 +419,11 @@ def join(self, other, semantic_check=True, left=False, allow_nullable_pk=False): need_subquery1 = True if len(other.support) > 1 and join_attributes: need_subquery2 = True + # A left join keeps every row of self, so a restriction on other (including dj.Top) + # must be applied before the join, inside a subquery. In the outer WHERE it would + # remove the rows of self that have no match. An unrestricted other needs no subquery. + if left and (other.restriction or other._top): + need_subquery2 = True if need_subquery1: self = self.make_subquery() if need_subquery2: diff --git a/tests/integration/test_aggr_left_join.py b/tests/integration/test_aggr_left_join.py new file mode 100644 index 000000000..3a5d95fbd --- /dev/null +++ b/tests/integration/test_aggr_left_join.py @@ -0,0 +1,244 @@ +""" +Left joins keep every row of the left operand when the right operand is restricted (#1650). + +aggr (with the default exclude_nonmatching=False), extend, and union of operands with secondary +attributes use a left join. A restriction on the right operand, including dj.Top, must be +applied before the join, in a subquery. In the outer WHERE it removes the left rows that have +no match. An unrestricted right operand is joined without a subquery, and inner joins keep +their restrictions in the WHERE clause. +""" + +import time + +import pytest + +import datajoint as dj + + +@pytest.fixture(scope="function") +def schema_by_backend(connection_by_backend, db_creds_by_backend): + """Create a fresh schema per test, parameterized across backends.""" + backend = db_creds_by_backend["backend"] + test_id = str(int(time.time() * 1000))[-8:] + schema_name = f"djtest_aggr_left_{backend}_{test_id}"[:64] + drop = f"DROP DATABASE IF EXISTS {connection_by_backend.adapter.quote_identifier(schema_name)}" + if connection_by_backend.is_connected: + try: + connection_by_backend.query(drop) + except Exception: + pass + + schema = dj.Schema(schema_name, connection=connection_by_backend) + yield schema + + if connection_by_backend.is_connected: + try: + connection_by_backend.query(drop) + except Exception: + pass + + +@pytest.fixture(scope="function") +def tables(schema_by_backend): + schema = schema_by_backend + + @schema + class Parent(dj.Manual): + definition = """ + parent_id : int32 + --- + label : varchar(8) + """ + + @schema + class Child(dj.Manual): + definition = """ + -> Parent + child_id : int32 + --- + color : varchar(8) + """ + + @schema + class Tag(dj.Manual): + definition = """ + -> Child + """ + + @schema + class ParentInfo(dj.Manual): + definition = """ + -> Parent + --- + info : varchar(8) + """ + + Parent.insert( + [ + {"parent_id": 1, "label": "a"}, + {"parent_id": 2, "label": "b"}, + {"parent_id": 3, "label": "a"}, + ] + ) + Child.insert( + [ + {"parent_id": 1, "child_id": 1, "color": "red"}, + {"parent_id": 1, "child_id": 2, "color": "blue"}, + {"parent_id": 2, "child_id": 1, "color": "blue"}, + ] + ) + Tag.insert([{"parent_id": 1, "child_id": 1}]) + ParentInfo.insert( + [ + {"parent_id": 1, "info": "x"}, + {"parent_id": 2, "info": "y"}, + {"parent_id": 3, "info": "z"}, + ] + ) + return Parent, Child, Tag, ParentInfo + + +def counts(expression): + rows = expression.to_dicts() + result = {row["parent_id"]: row["n"] for row in rows} + assert len(result) == len(rows), "duplicate rows" + return result + + +def right_operand_in_subquery(query): + return "JOIN (SELECT" in query.from_clause() + + +# --- aggr: the restricted group keeps every row of the grouping expression --- + + +def test_unrestricted_group_keeps_all_rows_without_subquery(tables): + Parent, Child, _, _ = tables + query = Parent.aggr(Child, n="count(child_id)") + assert counts(query) == {1: 2, 2: 1, 3: 0} + assert not right_operand_in_subquery(query) + + +def test_group_restricted_by_string_keeps_all_rows(tables): + """The reproduction from #1650.""" + Parent, Child, _, _ = tables + query = Parent.aggr(Child & "color='red'", n="count(child_id)") + assert counts(query) == {1: 1, 2: 0, 3: 0} + assert len(query) == 3 + assert right_operand_in_subquery(query) + + +@pytest.mark.parametrize( + "restriction, expected", + [ + ({"color": "blue"}, {1: 1, 2: 1, 3: 0}), + ({"parent_id": 1, "color": "blue"}, {1: 1, 2: 0, 3: 0}), + ([{"color": "red"}, {"parent_id": 2}], {1: 1, 2: 1, 3: 0}), + ("parent_id > 1", {1: 0, 2: 1, 3: 0}), + ], + ids=["mapping", "mapping-and", "list-or", "join-attribute"], +) +def test_group_restricted_by_condition_keeps_all_rows(tables, restriction, expected): + Parent, Child, _, _ = tables + assert counts(Parent.aggr(Child & restriction, n="count(child_id)")) == expected + + +def test_group_restricted_by_table_keeps_all_rows(tables): + Parent, Child, Tag, _ = tables + assert counts(Parent.aggr(Child & Tag, n="count(child_id)")) == {1: 1, 2: 0, 3: 0} + + +def test_group_restricted_by_negation_keeps_all_rows(tables): + Parent, Child, Tag, _ = tables + Tag.insert1({"parent_id": 2, "child_id": 1}) # every child of parent 2 is tagged + assert counts(Parent.aggr(Child - Tag, n="count(child_id)")) == {1: 1, 2: 0, 3: 0} + assert counts(Parent.aggr(Child - "color='red'", n="count(child_id)")) == {1: 1, 2: 1, 3: 0} + + +def test_group_restricted_by_top_keeps_all_rows(tables): + """dj.Top is applied with & like any restriction; its limit applies to the group.""" + Parent, Child, _, _ = tables + query = Parent.aggr(Child & dj.Top(1, order_by="color DESC"), n="count(child_id)") + assert counts(query) == {1: 1, 2: 0, 3: 0} + assert right_operand_in_subquery(query) + + +def test_restricted_and_projected_group_keeps_all_rows(tables): + Parent, Child, _, _ = tables + assert counts(Parent.aggr((Child & "color='red'").proj(), n="count(child_id)")) == {1: 1, 2: 0, 3: 0} + + +def test_restricted_join_as_group_keeps_all_rows(tables): + """Aggregates other than count are NULL for the rows with no match.""" + Parent, Child, Tag, _ = tables + query = Parent.aggr((Child * Tag) & "color='red'", n="count(child_id)", top="max(child_id)") + rows = {row["parent_id"]: (row["n"], row["top"]) for row in query.to_dicts()} + assert rows == {1: (1, 1), 2: (0, None), 3: (0, None)} + + +def test_restriction_on_grouping_side_stays_outside(tables): + """A restriction on the left operand still filters the result.""" + Parent, Child, _, _ = tables + query = (Parent & "parent_id > 1").aggr(Child & "color='red'", n="count(child_id)") + assert counts(query) == {2: 0, 3: 0} + + +def test_restricting_the_aggregation_result(tables): + """Restrictions on computed attributes (HAVING, or the PostgreSQL subquery) see the zero counts.""" + Parent, Child, _, _ = tables + query = Parent.aggr(Child & "color='red'", n="count(child_id)") & "n = 0" + assert set(counts(query)) == {2, 3} + + +# --- inner joins are unchanged: the restriction stays in WHERE, without a subquery --- + + +def test_inner_aggregation_keeps_restriction_in_where(tables): + Parent, Child, _, _ = tables + query = Parent.aggr(Child & "color='red'", n="count(child_id)", exclude_nonmatching=True) + assert counts(query) == {1: 1} + assert not right_operand_in_subquery(query) + assert "red" in query.where_clause() + + +def test_universal_set_aggregation_unchanged(tables): + """dj.U aggregation always excludes non-matching rows (inner join).""" + _, Child, _, _ = tables + query = dj.U("color").aggr(Child & "parent_id = 1", n="count(*)") + assert {row["color"]: row["n"] for row in query.to_dicts()} == {"red": 1, "blue": 1} + assert "(SELECT" not in query.from_clause() + + +def test_inner_join_with_restricted_operand_has_no_subquery(tables): + Parent, Child, _, _ = tables + query = Parent * (Child & "color='red'") + assert len(query) == 1 + assert not right_operand_in_subquery(query) + assert "red" in query.where_clause() + + +# --- extend and union use the same left join --- + + +def test_extend_with_restricted_operand_keeps_all_rows(tables): + Parent, Child, _, _ = tables + query = Child.extend(Parent & "label='a'") + rows = {(row["parent_id"], row["child_id"]): row["label"] for row in query.to_dicts()} + assert rows == {(1, 1): "a", (1, 2): "a", (2, 1): None} + assert len(query) == 3 + assert right_operand_in_subquery(query) + + +def test_extend_with_unrestricted_operand_has_no_subquery(tables): + Parent, Child, _, _ = tables + query = Child.extend(Parent) + assert len(query) == 3 + assert not right_operand_in_subquery(query) + + +def test_union_with_restricted_operand_keeps_all_rows(tables): + """Union of operands with secondary attributes left-joins the second operand.""" + Parent, _, _, ParentInfo = tables + query = Parent + (ParentInfo & "info in ('x', 'z')") + rows = {row["parent_id"]: (row["label"], row["info"]) for row in query.to_dicts()} + assert rows == {1: ("a", "x"), 2: ("b", None), 3: ("a", "z")} From 2a4c5761b9a3c26f0f63cd402d01c394047565bc Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Fri, 6 Nov 2026 14:07:15 -0600 Subject: [PATCH 17/37] fix: dj.Top is honored when a limited expression is used in another query An expression restricted by dj.Top keeps its ORDER BY/LIMIT in _top, and several operations ignored it or broke on it: - join() joined a limited operand directly, on either side, so the limit was dropped from *, aggr, and extend. A limited operand is now a subquery. - Restriction by a limited expression put the LIMIT inside IN (...), which MySQL rejects (error 1235). The expression is now a subquery there. - dj.U.aggr ignored the group's limit, and dj.U & expr applied DISTINCT before the limit. Both now apply the limit first. - Union put its ORDER BY/LIMIT inside the quoted alias name (a syntax error), and ignored it for operands with secondary attributes. - proj() kept the limit while dropping or redefining an attribute its ORDER BY names, so keys() and similar calls failed or selected other rows. It now adds a subquery in exactly those cases. - Top.merge let a second Top with an offset reach past the first Top's limit. - bool() ignored the limit. - Diagram.restrict() ignored a dj.Top on its seed; it now builds the seed as cascade and trace do. - A subquery heading dropped table_info, so a later rename quoted with backticks on PostgreSQL. dj.Top still cannot be negated or nested in a list or AndList; the error now says so and names the complement, dj.Top(None, order_by=..., offset=n). Fixes #1656. --- src/datajoint/condition.py | 25 +- src/datajoint/diagram.py | 5 +- src/datajoint/expression.py | 36 +- src/datajoint/heading.py | 1 + tests/integration/test_relational_operand.py | 12 +- tests/integration/test_top_in_queries.py | 391 +++++++++++++++++++ tests/unit/test_condition.py | 15 + 7 files changed, 466 insertions(+), 19 deletions(-) create mode 100644 tests/integration/test_top_in_queries.py diff --git a/src/datajoint/condition.py b/src/datajoint/condition.py index 650015539..161ed4407 100644 --- a/src/datajoint/condition.py +++ b/src/datajoint/condition.py @@ -167,15 +167,13 @@ def merge(self, other: "Top") -> "Top": Top New Top with merged limit/offset and preserved ordering. """ - # Compute effective limit (minimum of defined limits) - if self.limit is None and other.limit is None: - new_limit = None - elif self.limit is None: + # other skips other.offset rows of self's window and takes up to other.limit of the + # rest, so the merged window never extends past self's limit + if self.limit is None: new_limit = other.limit - elif other.limit is None: - new_limit = self.limit else: - new_limit = min(self.limit, other.limit) + remaining = max(self.limit - other.offset, 0) + new_limit = remaining if other.limit is None else min(remaining, other.limit) return Top( limit=new_limit, @@ -379,6 +377,15 @@ def combine_conditions(negate, conditions): negate = not negate condition = condition.restriction + # restrict() applies dj.Top itself; here it was negated or nested in a list or AndList + if isinstance(condition, Top): + raise DataJointError( + "dj.Top must be applied on its own, as `expression & dj.Top(...)`. It cannot be negated " + "(with - or dj.Not) or combined with other restrictions in a list, an AndList, or the " + "restrictions passed to populate() or progress(). For the rows after the first n, " + "use dj.Top(None, order_by=..., offset=n)." + ) + # restrict by string if isinstance(condition, str): columns.update(extract_column_names(condition)) @@ -442,7 +449,9 @@ def combine_conditions(negate, conditions): # Match on all non-hidden namesakes (hidden attributes excluded) common_attributes = [q for q in condition.heading.names if q in query_expression.heading.names] columns.update(common_attributes) - if isinstance(condition, Aggregation): + # A dj.Top limit stays inside a subquery: it applies to the expression's rows before + # they are projected to the common attributes, and MySQL rejects LIMIT inside IN (...). + if isinstance(condition, Aggregation) or condition._top is not None: condition = condition.make_subquery() return ( # without common attributes, any non-empty set matches everything diff --git a/src/datajoint/diagram.py b/src/datajoint/diagram.py index d3d7c40bc..598d36d51 100644 --- a/src/datajoint/diagram.py +++ b/src/datajoint/diagram.py @@ -799,8 +799,9 @@ def restrict(self, table_expr): if node not in result.nodes(): raise DataJointError(f"Table {node} is not in the diagram.") # Seed restriction (AND accumulation) - result._restrict_conditions.setdefault(node, AndList()).extend(table_expr.restriction) - result._restriction_attrs.setdefault(node, set()).update(table_expr.restriction_attributes) + restriction, restriction_attrs = _seed_restriction(table_expr) + result._restrict_conditions.setdefault(node, AndList()).extend(restriction) + result._restriction_attrs.setdefault(node, set()).update(restriction_attrs) # Propagate downstream result._propagate_restrictions(node, mode="restrict") return result diff --git a/src/datajoint/expression.py b/src/datajoint/expression.py index 1b5f5ac9e..25755e287 100644 --- a/src/datajoint/expression.py +++ b/src/datajoint/expression.py @@ -400,18 +400,21 @@ def join(self, other, semantic_check=True, left=False, allow_nullable_pk=False): need_subquery1 = need_subquery2 = bool( (set(self.original_heading.names) & set(other.original_heading.names)) - join_attributes ) - # need subquery if any of the join attributes are derived + # need subquery if any of the join attributes are derived, or if an operand is limited + # by dj.Top: its ORDER BY/LIMIT must apply to the operand before the join need_subquery1 = ( need_subquery1 or isinstance(self, Aggregation) or any(n in self.heading.new_attributes for n in join_attributes) or isinstance(self, Union) + or self._top is not None ) need_subquery2 = ( need_subquery2 or isinstance(other, Aggregation) or any(n in other.heading.new_attributes for n in join_attributes) or isinstance(self, Union) + or other._top is not None ) # With USING clause (instead of NATURAL JOIN), we need subqueries when # joining with multi-table expressions to ensure correct column matching @@ -614,6 +617,22 @@ def proj(self, *attributes, **named_attributes): if not need_subquery and self.restriction: # need a subquery if the restriction applies to attributes that have been renamed need_subquery = any(name in self.restriction_attributes for name in self.heading.new_attributes) + if not need_subquery and self._top is not None: + # need a subquery if dj.Top's ORDER BY names an attribute that the projection redefines, + # or a computed or renamed attribute that it drops. A dropped table column needs none. + projected = self.heading.select( + attributes, rename_map=dict(**rename_map, **replicate_map), compute_map=compute_map + ) + ordering = ", ".join(_flatten_attribute_list(self.primary_key, self._top.order_by or ["KEY"])) + need_subquery = any( + ( + projected[name].attribute_expression != self.heading[name].attribute_expression + if name in projected.names + else self.heading[name].attribute_expression is not None + ) + for name in extract_column_names(ordering) + if name in self.heading.names + ) result = self.make_subquery() if need_subquery else copy.copy(self) result._original_heading = result.original_heading @@ -1186,6 +1205,8 @@ def __bool__(self): bool True if the result is not empty. """ + if self._top is not None: + return bool(self.make_subquery()) # EXISTS must see the ORDER BY/LIMIT return bool( self.connection.query( "SELECT EXISTS(SELECT 1 FROM {from_}{where})".format(from_=self.from_clause(), where=self.where_clause()) @@ -1434,15 +1455,17 @@ def make_sql(self): if not arg1.heading.secondary_attributes and not arg2.heading.secondary_attributes: # no secondary attributes: use UNION DISTINCT fields = arg1.primary_key - alias_name = f"_u{next(self.__count)}{self.sorting_clauses()}" - alias_quoted = self.connection.adapter.quote_identifier(alias_name) + alias_quoted = self.connection.adapter.quote_identifier(f"_u{next(self.__count)}") sql1 = arg1.make_sql() if isinstance(arg1, Union) else arg1.make_sql(fields) sql2 = arg2.make_sql() if isinstance(arg2, Union) else arg2.make_sql(fields) - return f"SELECT * FROM (({sql1}) UNION ({sql2})) as {alias_quoted}" + return f"SELECT * FROM (({sql1}) UNION ({sql2})) as {alias_quoted}{self.sorting_clauses()}" # with secondary attributes, use union of left join with anti-restriction fields = self.heading.names sql1 = arg1.join(arg2, left=True).make_sql(fields) sql2 = (arg2 - arg1).proj(..., **{k: "NULL" for k in arg1.heading.secondary_attributes}).make_sql(fields) + if self._top is not None: + alias_quoted = self.connection.adapter.quote_identifier(f"_u{next(self.__count)}") + return f"SELECT * FROM (({sql1}) UNION ({sql2})) as {alias_quoted}{self.sorting_clauses()}" return "({sql1}) UNION ({sql2})".format(sql1=sql1, sql2=sql2) def from_clause(self): @@ -1509,6 +1532,8 @@ def __and__(self, other): other = other() # instantiate if a class if not isinstance(other, QueryExpression): raise DataJointError("Set U can only be restricted with a QueryExpression.") + if other._top is not None: + other = other.make_subquery() # apply the limit before DISTINCT result = copy.copy(other) result._distinct = True result._heading = result.heading.set_primary_key(self.primary_key) @@ -1563,6 +1588,9 @@ def aggr(self, group, **named_attributes): if missing: raise DataJointError(f"Attributes {missing} not found in the group expression.") + if group._top is not None: + group = group.make_subquery() # apply the limit before GROUP BY + # Create Aggregation directly without join - just group by U's primary key result = Aggregation() result._connection = group.connection diff --git a/src/datajoint/heading.py b/src/datajoint/heading.py index 9addae474..ce2d07611 100644 --- a/src/datajoint/heading.py +++ b/src/datajoint/heading.py @@ -775,5 +775,6 @@ def make_subquery_heading(self): """ return Heading( (dict(v.todict(), attribute_expression=None) for v in self.attributes.values()), + table_info=self.table_info, # keep the adapter, so a later rename quotes for the backend lineage_available=self._lineage_available, ) diff --git a/tests/integration/test_relational_operand.py b/tests/integration/test_relational_operand.py index eea53288e..afdd12328 100644 --- a/tests/integration/test_relational_operand.py +++ b/tests/integration/test_relational_operand.py @@ -608,12 +608,14 @@ def test_top_errors(self, schema_simp_pop): L() & dj.Top(order_by=1) with pytest.raises(TypeError) as err5: L() & dj.Top(offset="1") - assert "datajoint.errors.DataJointError: Invalid restriction type Top(limit=1, order_by=['KEY'], offset=0)" == str( - err1.exconly() - ) - assert "datajoint.errors.DataJointError: Invalid restriction type Top(limit=1, order_by=['KEY'], offset=0)" == str( - err2.exconly() + nested_top = ( + "datajoint.errors.DataJointError: dj.Top must be applied on its own, as `expression & dj.Top(...)`. " + "It cannot be negated (with - or dj.Not) or combined with other restrictions in a list, an AndList, " + "or the restrictions passed to populate() or progress(). For the rows after the first n, " + "use dj.Top(None, order_by=..., offset=n)." ) + assert nested_top == str(err1.exconly()) + assert nested_top == str(err2.exconly()) assert "TypeError: Top limit must be an integer" == str(err3.exconly()) assert "TypeError: Top order_by attributes must all be strings" == str(err4.exconly()) assert "TypeError: The offset argument must be an integer" == str(err5.exconly()) diff --git a/tests/integration/test_top_in_queries.py b/tests/integration/test_top_in_queries.py new file mode 100644 index 000000000..52f0ff334 --- /dev/null +++ b/tests/integration/test_top_in_queries.py @@ -0,0 +1,391 @@ +""" +dj.Top is honored when the limited expression is an operand of another query (#1656). + +An expression restricted by dj.Top carries its ORDER BY/LIMIT in ``_top``. Joins (on either +side), aggr, dj.U.aggr, dj.U restriction, union, and restriction by a limited expression must +apply that limit to the operand itself, which takes a subquery. dj.Top cannot be negated; the +rows after the first n are ``dj.Top(None, order_by=..., offset=n)``. +""" + +import time + +import pytest + +import datajoint as dj +from datajoint.errors import DataJointError + + +@pytest.fixture(scope="function") +def schema_by_backend(connection_by_backend, db_creds_by_backend): + """Create a fresh schema per test, parameterized across backends.""" + backend = db_creds_by_backend["backend"] + test_id = str(int(time.time() * 1000))[-8:] + schema_name = f"djtest_top_{backend}_{test_id}"[:64] + drop = f"DROP DATABASE IF EXISTS {connection_by_backend.adapter.quote_identifier(schema_name)}" + if connection_by_backend.is_connected: + try: + connection_by_backend.query(drop) + except Exception: + pass + + schema = dj.Schema(schema_name, connection=connection_by_backend) + yield schema + + if connection_by_backend.is_connected: + try: + connection_by_backend.query(drop) + except Exception: + pass + + +@pytest.fixture(scope="function") +def tables(schema_by_backend): + schema = schema_by_backend + + @schema + class Parent(dj.Manual): + definition = """ + parent_id : int32 + --- + label : varchar(8) + """ + + @schema + class Child(dj.Manual): + definition = """ + -> Parent + child_id : int32 + --- + color : varchar(8) + """ + + @schema + class ParentInfo(dj.Manual): + definition = """ + -> Parent + --- + info : varchar(8) + """ + + Parent.insert( + [ + {"parent_id": 1, "label": "a"}, + {"parent_id": 2, "label": "b"}, + {"parent_id": 3, "label": "a"}, + ] + ) + Child.insert( + [ + {"parent_id": 1, "child_id": 1, "color": "red"}, + {"parent_id": 1, "child_id": 2, "color": "blue"}, + {"parent_id": 2, "child_id": 1, "color": "blue"}, + ] + ) + ParentInfo.insert( + [ + {"parent_id": 1, "info": "x"}, + {"parent_id": 2, "info": "y"}, + {"parent_id": 3, "info": "z"}, + ] + ) + return Parent, Child, ParentInfo + + +# Limits used below, with the rows they select on their own. +def top_child(): # child (1, 2) + return dj.Top(1, order_by="child_id DESC, parent_id") + + +def top2_child(): # children (1, 2), (1, 1) + return dj.Top(2, order_by="child_id DESC, parent_id") + + +def rest_child(): # children (1, 1), (2, 1): all but the first + return dj.Top(None, order_by="child_id DESC, parent_id", offset=1) + + +def top_parent(): # parent 1 + return dj.Top(1, order_by="parent_id") + + +def rest_parent(): # parents 2, 3 + return dj.Top(None, order_by="parent_id", offset=1) + + +def rows(query, *attributes): + result = [tuple(row[a] for a in attributes) for row in query.to_dicts()] + assert len(result) == len(set(result)), "duplicate rows" + return set(result) + + +def counts(query, key, value="n"): + result = {row[key]: row[value] for row in query.to_dicts()} + return result + + +def test_limits_on_their_own(tables): + Parent, Child, _ = tables + assert rows(Child & top_child(), "parent_id", "child_id") == {(1, 2)} + assert rows(Child & top2_child(), "parent_id", "child_id") == {(1, 2), (1, 1)} + assert rows(Child & rest_child(), "parent_id", "child_id") == {(1, 1), (2, 1)} + assert rows(Parent & top_parent(), "parent_id") == {(1,)} + assert rows(Parent & rest_parent(), "parent_id") == {(2,), (3,)} + + +# --- joins: a limited operand on either side keeps its limit --- + + +@pytest.mark.parametrize( + "make, expected", + [ + (lambda P, C: P * (C & top_child()), {(1, 2)}), + (lambda P, C: (P & top_parent()) * C, {(1, 1), (1, 2)}), + (lambda P, C: (P & top_parent()) * (C & top_child()), {(1, 2)}), + (lambda P, C: P * ((C & "color='blue'") & dj.Top(1, order_by="parent_id DESC")), {(2, 1)}), + (lambda P, C: P * (C & rest_child()), {(1, 1), (2, 1)}), + (lambda P, C: (P & rest_parent()) * C, {(2, 1)}), + (lambda P, C: P * (C & top_child()).proj(), {(1, 2)}), + ], + ids=["right", "left", "both", "with-condition", "right-offset", "left-offset", "projected"], +) +def test_join_keeps_limit(tables, make, expected): + Parent, Child, _ = tables + assert rows(make(Parent, Child), "parent_id", "child_id") == expected + + +def test_join_without_limit_has_no_subquery(tables): + Parent, Child, _ = tables + query = Parent * (Child & "color='blue'") + assert rows(query, "parent_id", "child_id") == {(1, 2), (2, 1)} + assert "(SELECT" not in query.from_clause() + + +def test_extend_with_limited_left_operand(tables): + Parent, Child, _ = tables + query = (Child & top_child()).extend(Parent) + assert rows(query, "parent_id", "child_id", "label") == {(1, 2, "a")} + + +# --- aggregation --- + + +def test_aggr_with_limited_grouping_expression(tables): + Parent, Child, _ = tables + assert counts((Parent & top_parent()).aggr(Child, n="count(child_id)"), "parent_id") == {1: 2} + assert counts((Parent & rest_parent()).aggr(Child, n="count(child_id)"), "parent_id") == {2: 1, 3: 0} + + +@pytest.mark.parametrize( + "limit, expected", + [(top_child, {1: 1}), (rest_child, {1: 1, 2: 1})], + ids=["top", "offset"], +) +def test_inner_aggr_with_limited_group(tables, limit, expected): + Parent, Child, _ = tables + query = Parent.aggr(Child & limit(), n="count(child_id)", exclude_nonmatching=True) + assert counts(query, "parent_id") == expected + + +def test_left_join_with_limited_right_operand(tables): + Parent, Child, _ = tables + query = Child.extend(Parent & top_parent()) + assert rows(query, "parent_id", "child_id", "label") == {(1, 1, "a"), (1, 2, "a"), (2, 1, None)} + query = Parent.aggr(Child & rest_child(), n="count(child_id)") + assert counts(query, "parent_id") == {1: 1, 2: 1, 3: 0} + + +@pytest.mark.parametrize( + "limit, expected", + [(top_child, {"blue": 1}), (rest_child, {"red": 1, "blue": 1})], + ids=["top", "offset"], +) +def test_universal_aggr_with_limited_group(tables, limit, expected): + _, Child, _ = tables + assert counts(dj.U("color").aggr(Child & limit(), n="count(*)"), "color") == expected + + +def test_universal_aggr_without_limit_has_no_subquery(tables): + _, Child, _ = tables + query = dj.U("color").aggr(Child, n="count(*)") + assert counts(query, "color") == {"red": 1, "blue": 2} + assert "(SELECT" not in query.from_clause() + + +# --- restriction by a limited expression (MySQL rejects LIMIT inside IN) --- + + +@pytest.mark.parametrize( + "limit, matching, rest", + [ + (top_child, {(1,)}, {(2,), (3,)}), + (top2_child, {(1,)}, {(2,), (3,)}), + (rest_child, {(1,), (2,)}, {(3,)}), + ], + ids=["top", "top2", "offset"], +) +def test_restriction_by_limited_expression(tables, limit, matching, rest): + Parent, Child, _ = tables + assert rows(Parent & (Child & limit()), "parent_id") == matching + assert rows(Parent - (Child & limit()), "parent_id") == rest + + +def test_restriction_by_limit_on_computed_attribute(tables): + """The limit applies before the projection to the common attributes.""" + Parent, Child, _ = tables + # score: (1, 1) -> 11, (1, 2) -> 21, (2, 1) -> 12 + limited = Child.proj(score="child_id * 10 + parent_id") & dj.Top(1, order_by="score DESC") + assert rows(limited, "parent_id", "child_id", "score") == {(1, 2, 21)} + assert rows(Parent & limited, "parent_id") == {(1,)} + assert rows(Parent - limited, "parent_id") == {(2,), (3,)} + + +def test_restriction_by_limited_union(tables): + Parent, Child, ParentInfo = tables + first = (Parent.proj() + ParentInfo.proj()) & dj.Top(1, order_by="parent_id") + assert rows(Child & first, "parent_id", "child_id") == {(1, 1), (1, 2)} + assert rows(Child - first, "parent_id", "child_id") == {(2, 1)} + + +def test_restriction_without_limit_has_no_derived_table(tables): + Parent, Child, _ = tables + query = Parent & (Child & "color='blue'") + assert rows(query, "parent_id") == {(1,), (2,)} + assert query.where_clause().count("SELECT") == 1 + + +@pytest.mark.parametrize( + "limit", + [top2_child, lambda: dj.Top(2, order_by="parent_id")], + ids=["order-by-dropped-attribute", "order-by-kept-attribute"], +) +def test_universal_restriction_by_limited_expression(tables, limit): + """The limit applies to Child's rows before dj.U takes the distinct parent_id values.""" + _, Child, _ = tables + assert rows(dj.U("parent_id") & (Child & limit()), "parent_id") == {(1,)} + + +def test_universal_restriction_without_limit_has_no_subquery(tables): + _, Child, _ = tables + query = dj.U("parent_id") & Child + assert rows(query, "parent_id") == {(1,), (2,)} + assert "(SELECT" not in query.from_clause() + + +# --- projection of a limited expression --- + + +def test_keys_of_limit_on_aggregate(tables): + """The ORDER BY names a computed attribute that keys() drops.""" + Parent, Child, _ = tables + limited = Parent.aggr(Child, n="count(child_id)") & dj.Top(1, order_by="n DESC") + assert limited.keys() == [{"parent_id": 1}] + assert rows(Child * limited.proj(), "parent_id", "child_id") == {(1, 1), (1, 2)} + + +def test_projection_drops_computed_ordering_attribute(tables): + Parent, _, _ = tables + limited = Parent.proj(neg="-parent_id") & dj.Top(1, order_by="neg") # parent 3 + assert rows(limited.proj(), "parent_id") == {(3,)} + assert len(limited.proj()) == 1 + + +@pytest.mark.parametrize( + "make, attributes, expected", + [ + ( + lambda P, C: (P & dj.Top(1, order_by="label DESC, parent_id")).proj(label="-parent_id"), + ("parent_id", "label"), + {(2, -2)}, + ), + ( + lambda P, C: (C & top_child()).proj(child_id="parent_id", parent_id="child_id"), + ("parent_id", "child_id"), + {(2, 1)}, + ), + ], + ids=["recomputed", "swapped"], +) +def test_projection_redefines_ordering_attribute(tables, make, attributes, expected): + """A new attribute that takes an ORDER BY name must not change which rows the limit selects.""" + Parent, Child, _ = tables + assert rows(make(Parent, Child), *attributes) == expected + + +def test_projection_dropping_table_column_keeps_order_in_place(tables): + """ORDER BY on a table column that the projection drops needs no subquery.""" + _, Child, _ = tables + query = (Child & dj.Top(1, order_by="color DESC")).proj() + assert rows(query, "parent_id", "child_id") == {(1, 1)} + assert "(SELECT" not in query.from_clause() + + +# --- merged limits, emptiness, diagrams --- + + +@pytest.mark.parametrize( + "second", + [ + lambda: dj.Top(None, order_by="parent_id", offset=1), + lambda: dj.Top(5, order_by=None, offset=1), + ], + ids=["offset", "offset-inherit"], +) +def test_second_limit_stays_within_first(tables, second): + Parent, _, _ = tables + first_two = Parent & dj.Top(2, order_by="parent_id") # parents 1, 2 + assert rows(first_two & second(), "parent_id") == {(2,)} + assert [row["parent_id"] for row in first_two.to_dicts(limit=5, offset=1)] == [2] + + +def test_bool_of_limited_expression(tables): + Parent, _, _ = tables + assert not (Parent & dj.Top(None, order_by="parent_id", offset=3)) + assert not (Parent & dj.Top(0)) + assert Parent & rest_parent() + + +def test_diagram_restrict_by_limited_expression(tables, schema_by_backend): + Parent, Child, ParentInfo = tables + restricted = dj.Diagram(schema_by_backend).restrict(Parent & top_parent()) + expected = {Parent.full_table_name: 1, Child.full_table_name: 2, ParentInfo.full_table_name: 1} + assert restricted.counts() == expected + + +# --- union --- + + +def test_union_restricted_by_top(tables): + Parent, _, ParentInfo = tables + keys_only = (Parent.proj() + ParentInfo.proj()) & dj.Top(1, order_by="parent_id DESC") + assert rows(keys_only, "parent_id") == {(3,)} + with_attributes = (Parent + ParentInfo) & dj.Top(1, order_by="parent_id DESC") + assert rows(with_attributes, "parent_id", "label", "info") == {(3, "a", "z")} + + +def test_union_of_limited_operands(tables): + Parent, _, ParentInfo = tables + last_info = ParentInfo & dj.Top(1, order_by="parent_id DESC") + keys_only = (Parent & top_parent()).proj() + last_info.proj() + assert rows(keys_only, "parent_id") == {(1,), (3,)} + with_attributes = (Parent & top_parent()) + last_info + assert rows(with_attributes, "parent_id", "label", "info") == {(1, "a", None), (3, None, "z")} + + +# --- dj.Top cannot be negated; the error names the offset form --- + + +@pytest.mark.parametrize( + "make", + [ + lambda P: P - top_parent(), + lambda P: P & dj.Not(top_parent()), + lambda P: P & [top_parent()], + lambda P: P - [top_parent()], + lambda P: P & dj.AndList([top_parent(), "parent_id > 1"]), + ], + ids=["minus", "not", "list", "minus-list", "andlist"], +) +def test_negated_or_nested_top_is_rejected(tables, make): + Parent, _, _ = tables + with pytest.raises(DataJointError, match="offset=n"): + make(Parent) diff --git a/tests/unit/test_condition.py b/tests/unit/test_condition.py index 3200e34c4..4342f3518 100644 --- a/tests/unit/test_condition.py +++ b/tests/unit/test_condition.py @@ -53,6 +53,21 @@ def test_merge_offsets_add(self): merged = top1.merge(top2) assert merged.offset == 7 + @pytest.mark.parametrize( + "first, second, limit, offset", + [ + (Top(limit=2, order_by="id"), Top(limit=None, order_by=None, offset=1), 1, 1), + (Top(limit=2, order_by="id"), Top(limit=5, order_by=None, offset=1), 1, 1), + (Top(limit=2, order_by="id", offset=3), Top(limit=1, order_by=None, offset=1), 1, 4), + (Top(limit=2, order_by="id"), Top(limit=1, order_by=None, offset=5), 0, 5), + (Top(limit=None, order_by="id"), Top(limit=None, order_by=None, offset=2), 999999999999, 2), + ], + ) + def test_merge_offset_stays_within_first_limit(self, first, second, limit, offset): + """The second Top skips rows of the first Top's window and never reaches past its limit.""" + merged = first.merge(second) + assert (merged.limit, merged.offset) == (limit, offset) + def test_merge_preserves_existing_order(self): """Merged Top preserves first Top's ordering.""" top1 = Top(limit=10, order_by=["col1 desc", "col2 asc"]) From ab4a030315bbb1bad75d93c06ba89d773843aea7 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 9 Nov 2026 12:54:24 -0600 Subject: [PATCH 18/37] fix(config): skip config files other users could place in shared directories The search for datajoint.json walks up from the working directory and the .secrets/ directory is read next to the file it finds. A file or directory owned by another user (other than root) is now skipped, with a warning, when it or a directory above it is writable by all users (for example /tmp). A world-writable file that is used produces a warning. To use such a file, name it explicitly: dj.config.load(path), or the new DJ_CONFIG_FILE environment variable, which loads the named file without searching. DJ_IGNORE_CONFIG_FILE=true still turns the search off. Platforms without os.getuid (Windows) are unchanged. fix(npy): keep the mmap download cache in a per-user private directory NpyRef.load(mmap_mode=...) on a remote store cached downloads in a directory shared by all users. The cache is now /datajoint_mmap_, created with mode 0700; an existing directory is used only if the current user owns it, and otherwise a new private directory is created for the session. On Windows the per-user temp directory keeps datajoint_mmap. --- src/datajoint/builtin_codecs/npy.py | 68 +++++++++- src/datajoint/settings.py | 95 +++++++++++++- tests/unit/test_npy_cache.py | 112 ++++++++++++++++ tests/unit/test_settings.py | 193 ++++++++++++++++++++++++++++ 4 files changed, 456 insertions(+), 12 deletions(-) create mode 100644 tests/unit/test_npy_cache.py diff --git a/src/datajoint/builtin_codecs/npy.py b/src/datajoint/builtin_codecs/npy.py index c6eab2118..a5be03773 100644 --- a/src/datajoint/builtin_codecs/npy.py +++ b/src/datajoint/builtin_codecs/npy.py @@ -4,11 +4,71 @@ from __future__ import annotations +import logging +import os +import stat +import tempfile +from pathlib import Path from typing import Any from ..errors import DataJointError from .schema import SchemaCodec +logger = logging.getLogger(__name__.split(".")[0]) + +# Private directory created for this process when the per-user cache path is unusable +_fallback_mmap_cache_dir: Path | None = None + + +def _mmap_cache_dir() -> Path: + """ + Return the current user's cache directory for remote arrays opened with ``mmap_mode``. + + On POSIX systems the directory is ``/datajoint_mmap_``, created + with mode 0700. An existing directory is used only if it is a directory (not + a symbolic link) owned by the current user; its permissions are reset to 0700 + if other users have access. If the path exists but cannot be used, a new + private directory is created for this process instead. + + Where ``os.getuid`` is unavailable (Windows), the temporary directory is + already per-user and ``/datajoint_mmap`` is used. + + Returns + ------- + Path + Directory for cached ``.npy`` files. + """ + global _fallback_mmap_cache_dir + + getuid = getattr(os, "getuid", None) + if getuid is None: + cache_dir = Path(tempfile.gettempdir()) / "datajoint_mmap" + cache_dir.mkdir(exist_ok=True) + return cache_dir + + if _fallback_mmap_cache_dir is not None and _fallback_mmap_cache_dir.is_dir(): + return _fallback_mmap_cache_dir + + uid = getuid() + cache_dir = Path(tempfile.gettempdir()) / f"datajoint_mmap_{uid}" + try: + cache_dir.mkdir(mode=0o700) + except FileExistsError: + pass + + st = os.lstat(cache_dir) + if stat.S_ISDIR(st.st_mode) and st.st_uid == uid: + if stat.S_IMODE(st.st_mode) & 0o077: + os.chmod(cache_dir, 0o700) + return cache_dir + + _fallback_mmap_cache_dir = Path(tempfile.mkdtemp(prefix="datajoint_mmap_")) + logger.warning( + f"Not using {cache_dir} to cache arrays: it is not a directory owned by the current user. " + f"Using {_fallback_mmap_cache_dir} for this session." + ) + return _fallback_mmap_cache_dir + class NpyRef: """ @@ -165,15 +225,11 @@ def load(self, mmap_mode=None): local_path = self._backend._full_path(self.path) return np.load(local_path, mmap_mode=mmap_mode, allow_pickle=False) else: - # Remote storage - download to local cache first + # Remote storage - download to the user's local cache first import hashlib - import tempfile - from pathlib import Path path_hash = hashlib.md5(self.path.encode()).hexdigest()[:12] - cache_dir = Path(tempfile.gettempdir()) / "datajoint_mmap" - cache_dir.mkdir(exist_ok=True) - cache_path = cache_dir / f"{path_hash}.npy" + cache_path = _mmap_cache_dir() / f"{path_hash}.npy" if not cache_path.exists(): buffer = self._backend.get_buffer(self.path) diff --git a/src/datajoint/settings.py b/src/datajoint/settings.py index 0929f301d..d04ca682b 100644 --- a/src/datajoint/settings.py +++ b/src/datajoint/settings.py @@ -16,6 +16,13 @@ ``datajoint.json`` takes precedence over ``.secrets/``: the secrets directory only supplies values the config file and environment leave unset. +The search for ``datajoint.json`` and ``.secrets/`` skips, with a warning, any +file or directory owned by another user that sits under a world-writable +directory such as ``/tmp``, since anyone on the machine could have placed it +there. To use such a file, name it explicitly: ``dj.config.load(path)`` or the +``DJ_CONFIG_FILE`` environment variable. ``DJ_IGNORE_CONFIG_FILE=true`` turns +the search off. + Examples -------- >>> import datajoint as dj @@ -47,6 +54,7 @@ import json import logging import os +import stat import warnings from contextlib import contextmanager from enum import Enum @@ -61,6 +69,7 @@ CONFIG_FILENAME = "datajoint.json" SECRETS_DIRNAME = ".secrets" SYSTEM_SECRETS_DIR = Path("/run/secrets/datajoint") +CONFIG_FILE_ENV_VAR = "DJ_CONFIG_FILE" DEFAULT_SUBFOLDING = (2, 2) # Mapping of config keys to environment variables @@ -93,12 +102,77 @@ logger = logging.getLogger(__name__.split(".")[0]) +_SECRETS_HINT = " Supply its values through environment variables instead." + + +def _is_world_writable(mode: int) -> bool: + return bool(mode & stat.S_IWOTH) + + +def _check_discovered_path(path: Path, hint: str = "") -> bool: + """ + Decide whether a config file or secrets path found by searching may be used. + + A path owned by another user (other than root) is rejected when it, or any + directory above it, is world-writable: anyone on the machine could have + created it there. A path owned by the current user or by root is used, as + is another user's path in a directory tree that only its owners can write + (e.g. a shared project directory). A world-writable path that is used + produces a warning. + + Platforms without POSIX ownership (``os.getuid`` absent, e.g. Windows) + accept every path. + + Parameters + ---------- + path : Path + File or directory found by the search. + hint : str, optional + Advice appended to the warning when the path is not used. + + Returns + ------- + bool + True if the path may be used. + """ + getuid = getattr(os, "getuid", None) + if getuid is None: + return True + try: + st = os.stat(path) + except OSError: + return False + + if st.st_uid not in (getuid(), 0): + # Check the directories the path was found in as well as those of its + # target, in case the path is a symbolic link. + found, resolved = path.absolute(), path.resolve() + locations = dict.fromkeys((found, *found.parents, resolved, *resolved.parents)) + for location in locations: + try: + mode = os.stat(location).st_mode + except OSError: + continue + if _is_world_writable(mode): + logger.warning( + f"Ignoring {path}: it is owned by another user (uid {st.st_uid}) and " + f"{location} is writable by all users.{hint}" + ) + return False + + if _is_world_writable(st.st_mode): + logger.warning(f"{path} is writable by all users; restrict its permissions (e.g. chmod o-w).") + return True + + def find_config_file(start: Path | None = None) -> Path | None: """ Search for datajoint.json in current and parent directories. Searches upward from ``start`` until finding the config file or hitting - a project boundary (``.git``, ``.hg``) or filesystem root. + a project boundary (``.git``, ``.hg``) or filesystem root. A file owned by + another user under a world-writable directory ends the search without a + result (see ``_check_discovered_path``). Parameters ---------- @@ -115,7 +189,8 @@ def find_config_file(start: Path | None = None) -> Path | None: while True: config_path = current / CONFIG_FILENAME if config_path.is_file(): - return config_path + hint = f" To use it, pass its path to dj.config.load() or set {CONFIG_FILE_ENV_VAR}." + return config_path if _check_discovered_path(config_path, hint) else None # Stop at project/repo root if (current / ".git").exists() or (current / ".hg").exists(): @@ -137,6 +212,9 @@ def find_secrets_dir(config_path: Path | None = None) -> Path | None: 1. ``.secrets/`` in same directory as datajoint.json (project secrets) 2. ``/run/secrets/datajoint/`` (Docker/Kubernetes secrets) + A directory owned by another user under a world-writable directory is not + used (see ``_check_discovered_path``). + Parameters ---------- config_path : Path, optional @@ -150,12 +228,12 @@ def find_secrets_dir(config_path: Path | None = None) -> Path | None: # Check project secrets directory (next to config file) if config_path is not None: project_secrets = config_path.parent / SECRETS_DIRNAME - if project_secrets.is_dir(): + if project_secrets.is_dir() and _check_discovered_path(project_secrets, _SECRETS_HINT): return project_secrets # Check system secrets directory (Docker/Kubernetes) if SYSTEM_SECRETS_DIR.is_dir(): - return SYSTEM_SECRETS_DIR + return SYSTEM_SECRETS_DIR if _check_discovered_path(SYSTEM_SECRETS_DIR, _SECRETS_HINT) else None return None @@ -180,7 +258,7 @@ def read_secret_file(secrets_dir: Path | None, name: str) -> str | None: return None secret_path = secrets_dir / name - if secret_path.is_file(): + if secret_path.is_file() and _check_discovered_path(secret_path, _SECRETS_HINT): return secret_path.read_text().strip() return None @@ -842,6 +920,8 @@ def _load_secrets(self, secrets_dir: Path) -> None: parts = secret_file.name.split(".") if len(parts) == 3 and parts[0] == "stores": + if not _check_discovered_path(secret_file, _SECRETS_HINT): + continue store_name, attr = parts[1], parts[2] value = secret_file.read_text().strip() # Initialize store dict if needed @@ -1131,7 +1211,10 @@ def _create_config() -> Config: config_path: Path | None = None if not cfg.ignore_config_file: - config_path = find_config_file() + # DJ_CONFIG_FILE names the config file explicitly; it is used as given, + # like dj.config.load(), without searching. + explicit_path = os.environ.get(CONFIG_FILE_ENV_VAR) + config_path = Path(explicit_path).expanduser() if explicit_path else find_config_file() if config_path is not None: try: cfg.load(config_path) diff --git a/tests/unit/test_npy_cache.py b/tests/unit/test_npy_cache.py new file mode 100644 index 000000000..e2d7546a3 --- /dev/null +++ b/tests/unit/test_npy_cache.py @@ -0,0 +1,112 @@ +"""Tests for the cache directory used by NpyRef.load(mmap_mode=...) on remote stores.""" + +import os +import stat +import tempfile + +import numpy as np +import pytest + +from datajoint.builtin_codecs import npy +from datajoint.builtin_codecs.npy import NpyRef + +posix_only = pytest.mark.skipif(not hasattr(os, "getuid"), reason="requires POSIX file ownership") + + +@pytest.fixture +def tempdir(monkeypatch, tmp_path): + """Point tempfile.gettempdir() at tmp_path and reset the per-process fallback.""" + monkeypatch.setattr(tempfile, "tempdir", str(tmp_path)) + monkeypatch.setattr(npy, "_fallback_mmap_cache_dir", None) + return tmp_path + + +@posix_only +def test_cache_dir_is_per_user_and_private(tempdir): + cache_dir = npy._mmap_cache_dir() + + assert cache_dir == tempdir / f"datajoint_mmap_{os.getuid()}" + st = os.lstat(cache_dir) + assert stat.S_ISDIR(st.st_mode) + assert stat.S_IMODE(st.st_mode) == 0o700 + assert st.st_uid == os.getuid() + + +@posix_only +def test_existing_cache_dir_permissions_tightened(tempdir): + cache_dir = tempdir / f"datajoint_mmap_{os.getuid()}" + cache_dir.mkdir() + os.chmod(cache_dir, 0o777) + + assert npy._mmap_cache_dir() == cache_dir + assert stat.S_IMODE(os.lstat(cache_dir).st_mode) == 0o700 + + +@posix_only +def test_foreign_cache_dir_not_used(tempdir, monkeypatch, caplog): + """A directory at the per-user path owned by someone else is replaced by a new private one.""" + cache_dir = tempdir / f"datajoint_mmap_{os.getuid()}" + cache_dir.mkdir(mode=0o777) + real_lstat = os.lstat + + def fake_lstat(path, *args, **kwargs): + st = real_lstat(path, *args, **kwargs) + if os.fspath(path) == os.fspath(cache_dir): + fields = list(st) + fields[stat.ST_UID] = os.getuid() + 54321 + return os.stat_result(fields) + return st + + monkeypatch.setattr(os, "lstat", fake_lstat) + + with caplog.at_level("WARNING", logger="datajoint"): + used = npy._mmap_cache_dir() + + assert used != cache_dir + assert used.parent == tempdir + st = real_lstat(used) + assert stat.S_IMODE(st.st_mode) == 0o700 + assert st.st_uid == os.getuid() + assert any("not a directory owned by the current user" in r.message for r in caplog.records) + # The replacement is reused for the rest of the session + assert npy._mmap_cache_dir() == used + + +@posix_only +def test_symlink_at_cache_path_not_followed(tempdir): + elsewhere = tempdir / "elsewhere" + elsewhere.mkdir() + cache_dir = tempdir / f"datajoint_mmap_{os.getuid()}" + cache_dir.symlink_to(elsewhere) + + used = npy._mmap_cache_dir() + + assert used not in (cache_dir, elsewhere) + assert stat.S_IMODE(os.lstat(used).st_mode) == 0o700 + + +def test_no_posix_ownership_uses_shared_name(tempdir, monkeypatch): + """Without os.getuid (Windows) the per-user temp directory holds datajoint_mmap.""" + monkeypatch.delattr(os, "getuid", raising=False) + + assert npy._mmap_cache_dir() == tempdir / "datajoint_mmap" + assert (tempdir / "datajoint_mmap").is_dir() + + +def test_remote_mmap_load_uses_cache_dir(tempdir, tmp_path): + arr = np.arange(5, dtype=np.int32) + np.save(tmp_path / "src.npy", arr) + payload = (tmp_path / "src.npy").read_bytes() + + class RemoteBackend: + protocol = "s3" + + def get_buffer(self, path): + return payload + + meta = {"path": "schema/table/key/arr.npy", "store": "s3-store", "dtype": "int32", "shape": [5]} + loaded = NpyRef(meta, RemoteBackend()).load(mmap_mode="r") + + np.testing.assert_array_equal(loaded, arr) + cached = list(npy._mmap_cache_dir().glob("*.npy")) + assert len(cached) == 1 diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index 1cb535d81..22c901f64 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -1197,3 +1197,196 @@ def test_backend_field_in_env_var_mapping(self): assert "database.backend" in ENV_VAR_MAPPING assert ENV_VAR_MAPPING["database.backend"] == "DJ_BACKEND" + + +class TestDiscoveredFileOwnership: + """The config search skips files another user could have placed in a world-writable directory.""" + + FOREIGN_UID = 54321 + + @pytest.fixture + def fs(self, monkeypatch, tmp_path): + """Patch ``os.stat`` so chosen paths report another owner or world-write permission. + + Returns a dict mapping a path to ``{"uid": ..., "world_writable": ...}``. + Paths not in the dict keep their real owner and lose any world-write bit, + so the host's own ``/tmp`` does not affect the outcome. + """ + import os + import stat as stat_mod + + real_stat = os.stat + overrides: dict[Path, dict] = {} + + def fake_stat(path, *args, **kwargs): + st = real_stat(path, *args, **kwargs) + if isinstance(path, int) or kwargs.get("dir_fd") is not None: + return st + fields = list(st) + spec = overrides.get(Path(os.path.realpath(path)), {}) + mode = fields[stat_mod.ST_MODE] & ~stat_mod.S_IWOTH + if spec.get("world_writable"): + mode |= stat_mod.S_IWOTH + fields[stat_mod.ST_MODE] = mode + if "uid" in spec: + fields[stat_mod.ST_UID] = spec["uid"] + return os.stat_result(fields) + + monkeypatch.setattr(os, "stat", fake_stat) + monkeypatch.setattr(settings, "SYSTEM_SECRETS_DIR", tmp_path / "nonexistent-system-secrets") + return overrides + + @pytest.fixture + def shared(self, tmp_path): + """A shared parent directory holding a config file, with the user's project below it.""" + shared = tmp_path / "shared" + project = shared / "project" + project.mkdir(parents=True) + (shared / CONFIG_FILENAME).write_text('{"database": {"host": "from-shared"}}') + return shared + + def test_foreign_config_in_world_writable_dir_skipped(self, fs, shared, caplog): + fs[shared] = {"world_writable": True} + fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} + + with caplog.at_level("WARNING", logger="datajoint"): + found = find_config_file(shared / "project") + + assert found is None + assert any("owned by another user" in r.message for r in caplog.records) + + def test_foreign_config_under_world_writable_ancestor_skipped(self, fs, shared, tmp_path): + """A world-writable directory anywhere above the file is enough to skip it.""" + fs[tmp_path] = {"world_writable": True} + fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} + + assert find_config_file(shared / "project") is None + + def test_foreign_config_in_protected_dir_used(self, fs, shared): + """Another user's file in a directory only its owners can write (e.g. a lab share) is used.""" + fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} + + assert find_config_file(shared / "project") == shared / CONFIG_FILENAME + + def test_root_owned_config_in_world_writable_dir_used(self, fs, shared): + fs[shared] = {"world_writable": True} + fs[shared / CONFIG_FILENAME] = {"uid": 0} + + assert find_config_file(shared / "project") == shared / CONFIG_FILENAME + + def test_own_config_in_world_writable_dir_used(self, fs, shared, caplog): + fs[shared] = {"world_writable": True} + + with caplog.at_level("WARNING", logger="datajoint"): + found = find_config_file(shared / "project") + + assert found == shared / CONFIG_FILENAME + assert not caplog.records + + def test_world_writable_own_config_warns(self, fs, shared, caplog): + fs[shared / CONFIG_FILENAME] = {"world_writable": True} + + with caplog.at_level("WARNING", logger="datajoint"): + found = find_config_file(shared / "project") + + assert found == shared / CONFIG_FILENAME + assert any("writable by all users" in r.message for r in caplog.records) + + def test_symlink_in_world_writable_dir_to_foreign_file_skipped(self, fs, tmp_path): + """A link placed in a world-writable directory is judged by where it was found.""" + protected = tmp_path / "protected" + protected.mkdir() + target = protected / CONFIG_FILENAME + target.write_text("{}") + shared = tmp_path / "shared" + (shared / "project").mkdir(parents=True) + (shared / CONFIG_FILENAME).symlink_to(target) + fs[shared] = {"world_writable": True} + fs[target] = {"uid": self.FOREIGN_UID} + + assert find_config_file(shared / "project") is None + + def test_foreign_secrets_dir_in_world_writable_dir_skipped(self, fs, tmp_path): + config_file = tmp_path / CONFIG_FILENAME + config_file.write_text("{}") + secrets_dir = tmp_path / SECRETS_DIRNAME + secrets_dir.mkdir() + fs[tmp_path] = {"world_writable": True} + fs[secrets_dir] = {"uid": self.FOREIGN_UID} + + assert find_secrets_dir(config_file) is None + + def test_foreign_secret_file_in_world_writable_secrets_dir_skipped(self, fs, tmp_path): + secrets_dir = tmp_path / SECRETS_DIRNAME + secrets_dir.mkdir() + (secrets_dir / "database.password").write_text("planted") + (secrets_dir / "stores.main.secret_key").write_text("planted") + (secrets_dir / "database.user").write_text("mine") + fs[secrets_dir] = {"world_writable": True} + fs[secrets_dir / "database.password"] = {"uid": self.FOREIGN_UID} + fs[secrets_dir / "stores.main.secret_key"] = {"uid": self.FOREIGN_UID} + + assert read_secret_file(secrets_dir, "database.password") is None + assert read_secret_file(secrets_dir, "database.user") == "mine" + + cfg = settings.Config() + cfg._load_secrets(secrets_dir) + assert cfg.database.password is None + assert "main" not in cfg.stores + + def test_no_posix_ownership_keeps_search(self, fs, shared, monkeypatch): + """Without os.getuid (Windows) the search behaves as before.""" + import os + + monkeypatch.delattr(os, "getuid") + fs[shared] = {"world_writable": True} + fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} + + assert find_config_file(shared / "project") == shared / CONFIG_FILENAME + + def test_create_config_skips_foreign_config(self, fs, shared, monkeypatch): + for var in ("DJ_HOST", "DJ_CONFIG_FILE", "DJ_IGNORE_CONFIG_FILE"): + monkeypatch.delenv(var, raising=False) + monkeypatch.chdir(shared / "project") + fs[shared] = {"world_writable": True} + fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} + + with pytest.warns(UserWarning, match="No datajoint.json found"): + cfg = settings._create_config() + + assert cfg.database.host == "localhost" + + def test_dj_config_file_names_file_explicitly(self, fs, shared, monkeypatch, tmp_path): + """DJ_CONFIG_FILE loads the named file, without searching and without the ownership check.""" + monkeypatch.delenv("DJ_HOST", raising=False) + monkeypatch.delenv("DJ_IGNORE_CONFIG_FILE", raising=False) + elsewhere = tmp_path / "elsewhere" + (elsewhere / ".git").mkdir(parents=True) + monkeypatch.chdir(elsewhere) + fs[shared] = {"world_writable": True} + fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} + monkeypatch.setenv("DJ_CONFIG_FILE", str(shared / CONFIG_FILENAME)) + + cfg = settings._create_config() + + assert cfg.database.host == "from-shared" + + def test_dj_config_file_ignored_with_ignore_config_file(self, fs, shared, monkeypatch): + monkeypatch.delenv("DJ_HOST", raising=False) + monkeypatch.setenv("DJ_CONFIG_FILE", str(shared / CONFIG_FILENAME)) + monkeypatch.setenv("DJ_IGNORE_CONFIG_FILE", "true") + + cfg = settings._create_config() + + assert cfg.database.host == "localhost" + + def test_explicit_load_uses_foreign_file(self, fs, shared, monkeypatch): + """dj.config.load(path) is an explicit choice and is not checked.""" + monkeypatch.delenv("DJ_HOST", raising=False) + fs[shared] = {"world_writable": True} + fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} + + cfg = settings.Config() + cfg.load(shared / CONFIG_FILENAME) + + assert cfg.database.host == "from-shared" From d2ae31c7f145806ef628c0f4672c8acb5ea86e37 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 9 Nov 2026 13:00:11 -0600 Subject: [PATCH 19/37] Parse foreign key references instead of evaluating them; cap blob decompression Foreign key references in table definitions are now parsed and looked up in the declaration context attribute by attribute. A reference is a dotted name (Parent, module.Parent, Master.Part), optionally projected with .proj(new_name="old_name"); anything else raises a DataJointError naming the supported forms. alter() re-parses the definition that describe() builds from the database catalog, and that text is now only ever read as a table name. describe() keeps each element of the definition on its own line: line breaks in table and attribute comments become spaces, and attribute names that are not plain identifiers raise a DataJointError. Compressed blobs now expand only up to the size declared in their header. A payload that holds more, or less, raises a DataJointError, as does a corrupt zlib stream. --- src/datajoint/blob.py | 33 ++++++- src/datajoint/declare.py | 104 ++++++++++++++++++++- src/datajoint/table.py | 46 +++++++-- tests/integration/test_alter.py | 49 ++++++++++ tests/unit/test_blob_decompression.py | 67 +++++++++++++ tests/unit/test_foreign_key_reference.py | 114 +++++++++++++++++++++++ 6 files changed, 396 insertions(+), 17 deletions(-) create mode 100644 tests/unit/test_blob_decompression.py create mode 100644 tests/unit/test_foreign_key_reference.py diff --git a/src/datajoint/blob.py b/src/datajoint/blob.py index 633f55b79..d8bf7a416 100644 --- a/src/datajoint/blob.py +++ b/src/datajoint/blob.py @@ -10,6 +10,7 @@ import collections import datetime +import sys import uuid import zlib from decimal import Decimal @@ -58,7 +59,32 @@ } -compression = {b"ZL123\0": zlib.decompress} +def _zlib_decompress(data, size): + """ + Decompress zlib ``data`` that is declared to expand to exactly ``size`` bytes. + + Output is capped at ``size`` bytes, so a payload that expands beyond its + declared size is rejected without being expanded in full. + """ + if size > sys.maxsize: + raise DataJointError(f"Blob size mismatch: declared size {size} is not supported") + decompressor = zlib.decompressobj() + try: + # max_length=0 would mean "no limit", so ask for at least one byte + blob = decompressor.decompress(data, max(size, 1)) + if not decompressor.eof: + # check whether the stream holds more than the declared size + blob += decompressor.decompress(decompressor.unconsumed_tail, 1) + except zlib.error as error: + raise DataJointError(f"Corrupt compressed blob: {error}") from None + if len(blob) > size: + raise DataJointError(f"Blob size mismatch: expected {size} bytes, compressed data holds more") + if len(blob) != size or not decompressor.eof: + raise DataJointError(f"Blob size mismatch: expected {size}, got {len(blob)}") + return blob + + +compression = {b"ZL123\0": _zlib_decompress} # runtime setting to read integers as 32-bit to read blobs created by the 32-bit # version of the mYm library for MATLAB @@ -161,10 +187,7 @@ def unpack(self, blob): else: self._pos += len(prefix) blob_size = self.read_value() - blob = compression[prefix](self._blob[self._pos :]) - if len(blob) != blob_size: - raise DataJointError(f"Blob size mismatch: expected {blob_size}, got {len(blob)}") - self._blob = blob + self._blob = compression[prefix](self._blob[self._pos :], int(blob_size)) self._pos = 0 blob_format = self.read_zero_terminated_string() if blob_format in ("mYm", "dj0"): diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index 438bb72b0..15f841e76 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -169,10 +169,109 @@ def build_attribute_parser() -> pp.ParserElement: return attribute_name + pp.Optional(default) + colon + data_type + comment +def build_reference_parser() -> pp.ParserElement: + """ + Build a pyparsing parser for the table reference in a foreign key line. + + Returns + ------- + pp.ParserElement + Parser for a dotted name such as ``Parent``, ``module.Parent`` or + ``Master.Part``, optionally followed by ``()`` or by a projection + ``.proj(new_name="old_name", ...)`` whose arguments are string literals. + """ + identifier = pp.Word(pp.alphas + "_", pp.alphanums + "_") + name = pp.Group(pp.DelimitedList(identifier, delim=".")).set_results_name("name") + string = pp.QuotedString('"', esc_char="\\") ^ pp.QuotedString("'", esc_char="\\") + keyword_arg = pp.Group(identifier + pp.Literal("=").suppress() + string) + positional_arg = pp.Group(string) + argument = keyword_arg ^ positional_arg + arguments = pp.Optional(pp.DelimitedList(argument, allow_trailing_delim=True)) + call = pp.Group(pp.Literal("(").suppress() + arguments + pp.Literal(")").suppress()).set_results_name("call") + return name + pp.Optional(call) + pp.Optional(pp.python_style_comment).suppress() + pp.StringEnd() + + foreign_key_parser = build_foreign_key_parser() +reference_parser = build_reference_parser() attribute_parser = build_attribute_parser() +def resolve_foreign_key_reference(ref_table: str, context: dict): + """ + Resolve the table reference of a foreign key line in a namespace. + + The reference is parsed, never evaluated: it must be a dotted name looked up + in ``context`` attribute by attribute, optionally instantiated with ``()`` + or projected with ``.proj(...)`` whose arguments are string literals. + + Parameters + ---------- + ref_table : str + The reference, e.g. ``"Parent"``, ``"Master.Part"`` or + ``"Parent.proj(new_id='parent_id')"``. + context : dict + Namespace containing referenced table objects. + + Returns + ------- + object + The referenced table class, table, or projection. + + Raises + ------ + DataJointError + If the reference is not of a supported form or cannot be resolved. + """ + from .expression import QueryExpression + from .table import Table + + try: + parsed = reference_parser.parse_string(ref_table.strip()) + except pp.ParseException: + raise DataJointError( + 'Foreign key reference "%s" is not supported. Use a table name such as ' + "Parent, module.Parent or Master.Part, optionally projected with " + "Parent.proj(new_name='old_name')." % ref_table.strip() + ) from None + path = list(parsed.name) + call = parsed.get("call") + if any(part.startswith("__") for part in path): + raise DataJointError('Foreign key reference "%s" is not supported.' % ref_table.strip()) + method = None + if call is not None and len(path) > 1 and path[-1] == "proj": + method = path.pop() + elif call is not None and len(call): + raise DataJointError( + 'Foreign key reference "%s" is not supported. Only .proj() may take arguments.' % ref_table.strip() + ) + if path[0] not in context: + raise DataJointError("Foreign key reference %s could not be resolved" % ref_table.strip()) + ref = context[path[0]] + for part in path[1:]: + try: + ref = getattr(ref, part) + except Exception: + raise DataJointError("Foreign key reference %s could not be resolved" % ref_table.strip()) from None + if not (isinstance(ref, QueryExpression) or (isinstance(ref, type) and issubclass(ref, Table))): + raise DataJointError("Foreign key reference %s does not name a table" % ref_table.strip()) + if call is None: + return ref + if method is None: # Parent() + if not isinstance(ref, type): + raise DataJointError('Foreign key reference "%s" is not supported.' % ref_table.strip()) + return ref() + if isinstance(ref, type): + ref = ref() + args = [arg[0] for arg in call if len(arg) == 1] + kwargs = {arg[0]: arg[1] for arg in call if len(arg) == 2} + try: + return ref.proj(*args, **kwargs) + except DataJointError: + raise + except Exception as error: + raise DataJointError("Foreign key reference %s could not be resolved: %s" % (ref_table.strip(), error)) from None + + def is_foreign_key(line: str) -> bool: """ Check if a definition line is a foreign key reference. @@ -254,10 +353,7 @@ def compile_foreign_key( except pp.ParseException as err: raise DataJointError('Parsing error in line "%s". %s.' % (line, err)) - try: - ref = eval(result.ref_table, context) - except Exception: - raise DataJointError("Foreign key reference %s could not be resolved" % result.ref_table) + ref = resolve_foreign_key_reference(result.ref_table, context) options = [opt.upper() for opt in result.options] for opt in options: # check for invalid options diff --git a/src/datajoint/table.py b/src/datajoint/table.py index 2c8a4adaa..9cef804cc 100644 --- a/src/datajoint/table.py +++ b/src/datajoint/table.py @@ -5,6 +5,7 @@ import itertools import json import logging +import re import uuid import warnings from dataclasses import dataclass, field @@ -1371,7 +1372,8 @@ def describe(self, context=None, printout=False): self.connection.dependencies.load() parents = self.parents(foreign_key_info=True) in_key = True - definition = "# " + self.heading.table_status["comment"] + "\n" if self.heading.table_status["comment"] else "" + table_comment = _one_line_comment(self.heading.table_status["comment"]) + definition = "# " + table_comment + "\n" if table_comment else "" attributes_thus_far = set() attributes_declared = set() indexes = self.heading.indexes.copy() if self.heading.indexes else {} @@ -1408,15 +1410,17 @@ def describe(self, context=None, printout=False): # simple foreign key definition += "->{options} {class_name}\n".format( options=options_str, - class_name=lookup_class_name(parent_name, context) or parent_name, + class_name=_definition_token(lookup_class_name(parent_name, context) or parent_name), ) else: # projected foreign key definition += "->{options} {class_name}.proj({proj_list})\n".format( options=options_str, - class_name=lookup_class_name(parent_name, context) or parent_name, + class_name=_definition_token(lookup_class_name(parent_name, context) or parent_name), proj_list=",".join( - '{}="{}"'.format(attr, ref) for attr, ref in fk_props["attr_map"].items() if ref != attr + '{}="{}"'.format(_attribute_name(attr), _attribute_name(ref)) + for attr, ref in fk_props["attr_map"].items() + if ref != attr ), ) attributes_declared.update(fk_props["attr_map"]) @@ -1424,14 +1428,18 @@ def describe(self, context=None, printout=False): attributes_declared.add(attr.name) # Use original_type (core type alias) if available, otherwise use type display_type = attr.original_type or attr.type + attr_name = _attribute_name(attr.name) + attr_comment = _one_line_comment(attr.comment) definition += "%-20s : %-28s %s\n" % ( - (attr.name if attr.default is None else "%s=%s" % (attr.name, attr.default)), - "%s%s" % (display_type, " auto_increment" if attr.autoincrement else ""), - "# " + attr.comment if attr.comment else "", + (attr_name if attr.default is None else "%s=%s" % (attr_name, _definition_token(str(attr.default)))), + "%s%s" % (_definition_token(display_type), " auto_increment" if attr.autoincrement else ""), + "# " + attr_comment if attr_comment else "", ) # add remaining indexes for k, v in indexes.items(): - definition += "{unique}INDEX ({attrs})\n".format(unique="UNIQUE " if v["unique"] else "", attrs=", ".join(k)) + definition += "{unique}INDEX ({attrs})\n".format( + unique="UNIQUE " if v["unique"] else "", attrs=", ".join(_attribute_name(a) for a in k) + ) if printout: logger.info("\n" + definition) return definition @@ -1663,6 +1671,28 @@ def check_fields(fields): return row_to_insert +_ATTRIBUTE_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") + + +def _attribute_name(name): + """Return ``name`` for a definition string, requiring a plain identifier.""" + if not _ATTRIBUTE_NAME.fullmatch(name): + raise DataJointError(f"Attribute name {name!r} cannot be written in a table definition.") + return name + + +def _definition_token(text): + """Return ``text`` for a definition string, requiring that it stays on one line.""" + if "\n" in text or "\r" in text: + raise DataJointError(f"{text!r} cannot be written in a table definition.") + return text + + +def _one_line_comment(comment): + """Return ``comment`` with line breaks replaced so it stays a single comment line.""" + return re.sub(r"[\r\n]+", " ", comment) if comment else comment + + def lookup_class_name(name, context, depth=3): """ Find a table's class in the context given its full table name. diff --git a/tests/integration/test_alter.py b/tests/integration/test_alter.py index c593dc30a..bf0939cc7 100644 --- a/tests/integration/test_alter.py +++ b/tests/integration/test_alter.py @@ -87,6 +87,14 @@ class Note(dj.Part): --- note : varchar(64) """ + + +@schema +class Link(dj.Manual): + definition = """ + -> Item + -> Item.proj(other_item='item') + """ ''' @@ -153,3 +161,44 @@ def test_alter_explicit_context(pipeline): """ pipeline.Measurement.alter(prompt=False, context={"Upstream": pipeline.Item}) assert pipeline.Measurement.heading.secondary_attributes == ["value", "unit"] + + +def test_alter_projected_foreign_key(pipeline): + """A projected foreign key round-trips through describe() and alter().""" + assert '-> Item.proj(other_item="item")' in pipeline.Link.describe(context=vars(pipeline)) + pipeline.Link.definition = """ + -> Item + -> Item.proj(other_item='item') + --- + weight = 1 : float32 + """ + pipeline.Link.alter(prompt=False) + assert pipeline.Link.heading.primary_key == ["item", "other_item"] + assert pipeline.Link.heading.secondary_attributes == ["weight"] + + +def test_alter_reads_catalog_text_as_data(pipeline, tmp_path): + """Text stored in the catalog is reproduced by describe() as data, never run by alter().""" + marker = tmp_path / "marker" + table = pipeline.Item() + comment = f"note\n-> __import__('pathlib').Path({str(marker)!r}).touch()" + if table.connection.adapter.backend == "postgresql": + sql = f"COMMENT ON TABLE {table.full_table_name} IS %s" + else: + sql = f"ALTER TABLE {table.full_table_name} COMMENT = %s" + table.connection.query(sql, args=(comment,)) + table.__class__._heading = dj.heading.Heading(table_info=table.heading.table_info) + described = table.describe(context=vars(pipeline)) + assert described.splitlines()[0].startswith("# note -> __import__") + # keep the comment unchanged so that only the new attribute is altered + table.definition = ( + described.splitlines()[0] + + """ + item : int32 + --- + label = "" : varchar(16) + """ + ) + table.alter(prompt=False) + assert not marker.exists() + assert table.heading.secondary_attributes == ["label"] diff --git a/tests/unit/test_blob_decompression.py b/tests/unit/test_blob_decompression.py new file mode 100644 index 000000000..876f03d1f --- /dev/null +++ b/tests/unit/test_blob_decompression.py @@ -0,0 +1,67 @@ +"""Compressed blobs expand only up to the size their header declares.""" + +import zlib + +import numpy as np +import pytest + +from datajoint.blob import len_u64, pack, unpack +from datajoint.errors import DataJointError + +PREFIX = b"ZL123\0" + + +def compressed_blob(payload, declared_size=None): + size = len(payload) if declared_size is None else declared_size + return PREFIX + np.uint64(size).tobytes() + zlib.compress(payload) + + +def test_round_trip_compressed(): + value = np.arange(10_000, dtype=np.float64) + blob = pack(value) + assert blob.startswith(PREFIX) + np.testing.assert_array_equal(unpack(blob), value) + + +def test_round_trip_uncompressed(): + assert unpack(pack({"a": [1, 2, 3]}, compress=False)) == {"a": [1, 2, 3]} + + +def test_payload_larger_than_declared_size_is_rejected(): + # a small header in front of ~100 MB of zeros that compress to ~100 kB + inner = pack(b"x", compress=False) + payload = inner + bytes(100_000_000) + blob = compressed_blob(payload, declared_size=len(inner)) + with pytest.raises(DataJointError, match="size mismatch"): + unpack(blob) + + +def test_payload_smaller_than_declared_size_is_rejected(): + payload = pack(np.arange(1000), compress=False) + with pytest.raises(DataJointError, match="size mismatch"): + unpack(compressed_blob(payload, declared_size=len(payload) + 1)) + + +def test_zero_declared_size_is_rejected(): + payload = pack(np.arange(1000), compress=False) + with pytest.raises(DataJointError, match="size mismatch"): + unpack(compressed_blob(payload, declared_size=0)) + + +def test_oversized_declared_size_is_rejected(): + payload = pack(np.arange(1000), compress=False) + with pytest.raises(DataJointError, match="size mismatch"): + unpack(compressed_blob(payload, declared_size=2**64 - 1)) + + +def test_truncated_stream_is_rejected(): + payload = pack(np.arange(1000), compress=False) + blob = compressed_blob(payload) + with pytest.raises(DataJointError): + unpack(blob[:-10]) + + +def test_corrupt_stream_is_rejected(): + payload = pack(np.arange(1000), compress=False) + with pytest.raises(DataJointError, match="Corrupt"): + unpack(PREFIX + len_u64(payload) + b"not zlib data") diff --git a/tests/unit/test_foreign_key_reference.py b/tests/unit/test_foreign_key_reference.py new file mode 100644 index 000000000..89c36a039 --- /dev/null +++ b/tests/unit/test_foreign_key_reference.py @@ -0,0 +1,114 @@ +"""Foreign key references are parsed and looked up, never evaluated. + +The text after ``->`` names a table in the declaration context: a dotted name +(``Parent``, ``module.Parent``, ``Master.Part``), optionally projected with +``.proj(new_name="old_name")``. ``Table.alter`` re-parses the definition that +``describe()`` builds from names read back from the database catalog, so that +text must not be able to do anything but name a table. +""" + +import types + +import pytest + +import datajoint as dj +from datajoint.adapters.mysql import MySQLAdapter +from datajoint.declare import prepare_declare, resolve_foreign_key_reference +from datajoint.errors import DataJointError +from datajoint.table import _attribute_name, _definition_token, _one_line_comment + + +class Parent(dj.Manual): + definition = """ + parent_id : int32 + """ + + class Part(dj.Part): + definition = """ + -> master + part_id : int32 + """ + + +module = types.SimpleNamespace(Parent=Parent) +CONTEXT = {"Parent": Parent, "module": module, "master": Parent, "os": __import__("os")} + + +@pytest.mark.parametrize( + "reference, expected", + [ + ("Parent", Parent), + (" Parent ", Parent), + ("module.Parent", Parent), + ("Parent.Part", Parent.Part), + ("master.Part", Parent.Part), + ("Parent # a trailing comment", Parent), + ], +) +def test_dotted_names_resolve(reference, expected): + assert resolve_foreign_key_reference(reference, CONTEXT) is expected + + +@pytest.mark.parametrize( + "reference", + [ + "__import__('os').system('true')", + "os.system('true')", + "Parent.proj(x=__import__('os').getcwd())", + "Parent.proj(x=y)", + "Parent.proj(**{'a': 'b'})", + "Parent.Part.__init__.__globals__", + "Parent.__class__", + "[c for c in ().__class__.__base__.__subclasses__()]", + "Parent; import os", + "Parent & 'parent_id=1'", + "lambda: 0", + "`schema`.`parent`", + '"schema"."parent"', + "Parent.delete()", + "Parent.Part('x')", + "", + ], +) +def test_expressions_are_rejected(reference, monkeypatch): + def fail(*args, **kwargs): + raise AssertionError("reference text was executed") + + monkeypatch.setattr("os.system", fail) + with pytest.raises(DataJointError): + resolve_foreign_key_reference(reference, CONTEXT) + + +@pytest.mark.parametrize("reference", ["os", "os.getcwd", "module", "Missing", "module.Missing"]) +def test_non_tables_are_rejected(reference): + with pytest.raises(DataJointError): + resolve_foreign_key_reference(reference, CONTEXT) + + +def test_resolution_reads_no_builtins(): + """eval() would add __builtins__ to the context it is given; lookup does not.""" + context = dict(CONTEXT) + resolve_foreign_key_reference("Parent", context) + assert "__builtins__" not in context + + +def test_definition_with_crafted_reference_is_rejected(): + definition = """ + -> __import__('os').system('true') + id : int32 + """ + with pytest.raises(DataJointError, match="not supported"): + prepare_declare(definition, dict(CONTEXT), MySQLAdapter()) + + +def test_describe_helpers(): + assert _attribute_name("subject_id") == "subject_id" + assert _attribute_name("_hidden") == "_hidden" + for name in ['a"); x', "a b", "a\nb", "", "1a"]: + with pytest.raises(DataJointError): + _attribute_name(name) + assert _definition_token("`s`.`t`") == "`s`.`t`" + with pytest.raises(DataJointError): + _definition_token("Parent\n-> other") + assert _one_line_comment("first\nsecond\r\nthird") == "first second third" + assert _one_line_comment("") == "" From b99f29166a7f1598cfefd5db6695e14f7e30be80 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 9 Nov 2026 13:06:25 -0600 Subject: [PATCH 20/37] Keep attachment and store paths inside their roots fetch now accepts only a plain stored file name (no directory part, "..", or NUL byte; on Windows, no drive or ":"), creates the file exclusively, and never opens or reuses a symbolic link, device, or pipe already in the download path. encode has always stored only the base name, so attachments written by DataJoint are unaffected. Store paths are confined to the store location: StorageBackend rejects paths with ".." components and, for file stores, absolute paths. This covers every store operation, including , , , and access, and pre-computed metadata on insert. checks its reserved sections and filepath_prefix on the normalized path. The new setting allow_filepath_outside_store (DJ_ALLOW_FILEPATH_OUTSIDE_STORE) lets values point outside their store, for data whose references deliberately do, such as rows migrated from DataJoint 0.14. --- src/datajoint/builtin_codecs/attach.py | 99 +++++-- src/datajoint/builtin_codecs/filepath.py | 42 ++- src/datajoint/builtin_codecs/object.py | 3 +- src/datajoint/settings.py | 9 + src/datajoint/storage.py | 33 +++ tests/integration/test_path_confinement.py | 168 ++++++++++++ tests/unit/test_path_confinement.py | 301 +++++++++++++++++++++ 7 files changed, 620 insertions(+), 35 deletions(-) create mode 100644 tests/integration/test_path_confinement.py create mode 100644 tests/unit/test_path_confinement.py diff --git a/src/datajoint/builtin_codecs/attach.py b/src/datajoint/builtin_codecs/attach.py index 8035810be..62ad25be5 100644 --- a/src/datajoint/builtin_codecs/attach.py +++ b/src/datajoint/builtin_codecs/attach.py @@ -4,9 +4,51 @@ from __future__ import annotations +import os +import stat +from pathlib import Path from typing import Any from ..codecs import Codec +from ..errors import DataJointError + + +def _check_file_name(filename: str) -> None: + """ + Raise unless ``filename`` is a plain file name with no directory part. + + ``encode`` stores only the base name of the attached file, so a stored name + with separators, ``..``, a NUL byte, or (on Windows) a drive or stream + marker ``:`` did not come from it. + """ + if ( + filename in ("", ".", "..") + or "/" in filename + or "\\" in filename + or "\x00" in filename + or (os.name == "nt" and ":" in filename) + ): + raise DataJointError(f" stored file name {filename!r} is not a plain file name.") + + +def _has_contents(path: Path, contents: bytes) -> bool: + """ + Check whether ``path`` is a regular file holding exactly ``contents``. + + Symbolic links, devices, and pipes are never opened, and a file is read only + when its size matches. + """ + try: + st = os.lstat(path) + except FileNotFoundError: + return False + if not stat.S_ISREG(st.st_mode) or st.st_size != len(contents): + return False + fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0)) + with os.fdopen(fd, "rb") as f: + if not stat.S_ISREG(os.fstat(f.fileno()).st_mode): + return False + return f.read(len(contents) + 1) == contents class AttachCodec(Codec): @@ -19,7 +61,9 @@ class AttachCodec(Codec): - ````: Stored in specific named store The filename is preserved and the file is extracted to the configured - download path on fetch. + download path on fetch. Only the base name is kept, and fetch refuses a + stored name that is not a plain file name, so extracted files always land + directly in the download path. Example:: @@ -70,8 +114,6 @@ def encode( bytes Filename (UTF-8) + null byte + file contents. """ - from pathlib import Path - path = Path(value) if not path.exists(): raise FileNotFoundError(f"Attachment file not found: {path}") @@ -97,13 +139,17 @@ def decode(self, stored: bytes, *, key: dict | None = None, context: dict | None ------- str Path to extracted file. - """ - from pathlib import Path + Raises + ------ + DataJointError + If the stored file name is not a plain file name. + """ # Split on first null byte null_pos = stored.index(b"\x00") filename = stored[:null_pos].decode("utf-8") contents = stored[null_pos + 1 :] + _check_file_name(filename) # Write to download path config = self._codec_config(key, context) @@ -113,28 +159,31 @@ def decode(self, stored: bytes, *, key: dict | None = None, context: dict | None download_path = Path(config.get("download_path", ".")) download_path.mkdir(parents=True, exist_ok=True) local_path = download_path / filename - - # Handle filename collision - if file exists with different content, add suffix - if local_path.exists(): - existing_contents = local_path.read_bytes() - if existing_contents != contents: - # Find unique filename - stem = local_path.stem - suffix = local_path.suffix - counter = 1 - while local_path.exists() and local_path.read_bytes() != contents: - local_path = download_path / f"{stem}_{counter}{suffix}" - counter += 1 - - # Only write if file doesn't exist or has different content - if not local_path.exists(): - local_path.write_bytes(contents) - - return str(local_path) + if local_path.parent != download_path: + raise DataJointError(f" file name {filename!r} leads outside the download path.") + + # Reuse a file with identical content; otherwise add a numeric suffix until + # a free name is found. New files are created exclusively, never through an + # existing file or link. + stem = local_path.stem + suffix = local_path.suffix + counter = 0 + while True: + if _has_contents(local_path, contents): + return str(local_path) + if not os.path.lexists(local_path): + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0) + try: + fd = os.open(local_path, flags, 0o666) + except FileExistsError: + continue # created concurrently; check it again + with os.fdopen(fd, "wb") as f: + f.write(contents) + return str(local_path) + counter += 1 + local_path = download_path / f"{stem}_{counter}{suffix}" def validate(self, value: Any) -> None: """Validate that value is a valid file path.""" - from pathlib import Path - if not isinstance(value, (str, Path)): raise TypeError(f" expects a file path, got {type(value).__name__}") diff --git a/src/datajoint/builtin_codecs/filepath.py b/src/datajoint/builtin_codecs/filepath.py index 9ba128c86..b41ed3bbf 100644 --- a/src/datajoint/builtin_codecs/filepath.py +++ b/src/datajoint/builtin_codecs/filepath.py @@ -59,6 +59,12 @@ class Recordings(dj.Manual): Paths cannot start with the store's reserved ``hash_prefix`` or ``schema_prefix`` sections (defaults ``_hash/`` and ``_schema/``). + Store Boundary: + Paths must stay inside the store location: absolute paths (for + ``file`` stores) and paths with ``..`` components are rejected on + insert and on access. Set ``dj.config.allow_filepath_outside_store`` + to accept references that point outside the store. + Warning: The file must exist in the store at the specified path. DataJoint does not manage the lifecycle of referenced files. @@ -99,13 +105,15 @@ def encode( ------ ValueError If path uses the store's reserved hash/schema sections. + DataJointError + If path leads outside the store location (see + ``allow_filepath_outside_store``). FileNotFoundError If file does not exist in the store. """ + import posixpath from datetime import datetime, timezone - from ..hash_registry import get_store_backend - config = self._codec_config(key, context) if config is None: from ..settings import config # type: ignore[assignment] @@ -117,8 +125,13 @@ def encode( # Use filepath_default if no store specified (filepath is not part of OAS) spec = config.get_store_spec(store_name, use_filepath_default=True) - # Validate path doesn't use reserved sections (hash and schema) - path_normalized = path.lstrip("/") + # Reject paths outside the store before any prefix checks + backend = self._get_backend(store_name, config) + backend._full_path(path) + + # Validate path doesn't use reserved sections (hash and schema). + # Normalize first so that "./_hash/x" or "//_hash/x" are caught too. + path_normalized = posixpath.normpath(path.replace("\\", "/")).lstrip("/") reserved_prefixes = [] hash_prefix = spec.get("hash_prefix") @@ -132,7 +145,7 @@ def encode( # Check if path starts with any reserved prefix for prefix_name, prefix_value in reserved_prefixes: prefix_normalized = prefix_value.strip("/") + "/" - if path_normalized.startswith(prefix_normalized): + if (path_normalized + "/").startswith(prefix_normalized): raise ValueError( f" cannot use reserved section '{prefix_value}' ({prefix_name}). " f"This section is managed by DataJoint. " @@ -147,7 +160,6 @@ def encode( raise ValueError(f" must use prefix '{filepath_prefix}' (filepath_prefix). Got path: {path}") # Verify file exists - backend = get_store_backend(store_name, config=config) if not backend.exists(path): raise FileNotFoundError(f"File not found in store '{store_name or 'default'}': {path}") @@ -187,13 +199,25 @@ def decode(self, stored: dict, *, key: dict | None = None, context: dict | None Handle for accessing the file. """ from ..objectref import ObjectRef - from ..hash_registry import get_store_backend config = self._codec_config(key, context) - store_name = stored.get("store") - backend = get_store_backend(store_name, config=config) + backend = self._get_backend(stored.get("store"), config) return ObjectRef.from_json(stored, backend=backend) + @staticmethod + def _get_backend(store_name: str | None, config): + """ + Get the store backend, confined to the store location unless + ``allow_filepath_outside_store`` is set. + """ + from ..hash_registry import get_store_backend + + if config is None: + from ..settings import config # type: ignore[assignment] + backend = get_store_backend(store_name, config=config) + backend.confine_paths = not config.get("allow_filepath_outside_store", False) + return backend + def validate(self, value: Any) -> None: """Validate that value is a path string or Path object.""" from pathlib import Path diff --git a/src/datajoint/builtin_codecs/object.py b/src/datajoint/builtin_codecs/object.py index 138f8a9c2..f3201878e 100644 --- a/src/datajoint/builtin_codecs/object.py +++ b/src/datajoint/builtin_codecs/object.py @@ -111,7 +111,8 @@ def encode( # Check for pre-computed metadata (from staged insert) if isinstance(value, dict) and "path" in value: - # Already encoded, pass through + # Already encoded, pass through once the path is known to stay in the store + self._get_backend(value.get("store"), config=config)._full_path(value["path"]) return value # Determine content type and extension diff --git a/src/datajoint/settings.py b/src/datajoint/settings.py index 0929f301d..abaa046aa 100644 --- a/src/datajoint/settings.py +++ b/src/datajoint/settings.py @@ -444,6 +444,15 @@ class Config(BaseSettings): # Download path for attachments and filepaths download_path: str = "." + allow_filepath_outside_store: bool = Field( + default=False, + description="If True, values may point outside the store location " + "(absolute paths on file stores, or paths with '..' components). " + "By default such paths are rejected on insert and on access. Enable only for " + "trusted data whose references deliberately point elsewhere, such as rows " + "migrated from DataJoint 0.14. Set via DJ_ALLOW_FILEPATH_OUTSIDE_STORE.", + ) + # Internal: track where config was loaded from _config_path: Path | None = None _secrets_dir: Path | None = None diff --git a/src/datajoint/storage.py b/src/datajoint/storage.py index 51e1d80cd..5834c962c 100644 --- a/src/datajoint/storage.py +++ b/src/datajoint/storage.py @@ -9,6 +9,7 @@ import json import logging +import re import secrets import urllib.parse from datetime import datetime, timezone @@ -45,6 +46,16 @@ def is_url(path: str) -> bool: return path.lower().startswith(URL_PROTOCOLS) +def _has_parent_reference(path: str) -> bool: + """ + Check whether a path has a ``..`` component. + + Both ``/`` and ``\\`` count as separators so the result does not depend on the + platform. + """ + return ".." in re.split(r"[\\/]", path) + + def _path_to_file_url(resolved_path: Path | PurePosixPath) -> str: """ Convert an already-resolved absolute path to a ``file://`` URL. @@ -309,8 +320,14 @@ class StorageBackend: Storage configuration dictionary. protocol : str Storage protocol (``'file'``, ``'s3'``, ``'gcs'``, ``'azure'``). + confine_paths : bool + If True (default), paths passed to the backend must stay inside the + store location: absolute paths (for ``file`` stores) and paths with + ``..`` components are rejected. """ + confine_paths: bool = True + def __init__(self, spec: dict[str, Any]) -> None: """ Initialize storage backend from configuration spec. @@ -429,8 +446,16 @@ def _full_path(self, path: str | PurePosixPath) -> str: ------- str Full path suitable for fsspec operations. + + Raises + ------ + DataJointError + If ``confine_paths`` is set and the path leads outside the store + location. """ path = str(path) + if self.confine_paths: + self._check_confined(path) if self.protocol == "s3": bucket = self.spec["bucket"] location = self.spec.get("location", "") @@ -451,6 +476,14 @@ def _full_path(self, path: str | PurePosixPath) -> str: else: return self._require_adapter().full_path(self.spec, path) + def _check_confined(self, path: str) -> None: + """Raise if ``path`` does not stay inside the store location.""" + if "\x00" in path or _has_parent_reference(path) or (self.protocol == "file" and Path(path).anchor): + raise errors.DataJointError( + f"Path {path!r} may lead outside the store location: " + "store paths must be relative and have no '..' components." + ) + def get_url(self, path: str | PurePosixPath) -> str: """ Get the full URL for a path in storage. diff --git a/tests/integration/test_path_confinement.py b/tests/integration/test_path_confinement.py new file mode 100644 index 000000000..52db92897 --- /dev/null +++ b/tests/integration/test_path_confinement.py @@ -0,0 +1,168 @@ +""" +Rows written directly to the database cannot direct fetches outside the store +or the download path. + +Each test inserts a valid row through DataJoint, then rewrites the stored value +with SQL, as anyone with write access to the table could, and fetches it. +""" + +import json +from pathlib import Path + +import pytest + +import datajoint as dj + + +class Document(dj.Manual): + definition = """ + doc_id : int32 + --- + inline_file : + stored_file : + """ + + +class Reference(dj.Manual): + definition = """ + ref_id : int32 + --- + file_ref : + """ + + +class Output(dj.Manual): + definition = """ + output_id : int32 + --- + result : + """ + + +@pytest.fixture +def schema_paths(connection_test, mock_stores, prefix): + schema = dj.Schema(prefix + "_path_confinement", connection=connection_test) + schema(Document) + schema(Reference) + schema(Output) + yield schema + schema.drop() + + +@pytest.fixture +def outside(tmp_path): + """A file outside every store and download path.""" + path = tmp_path / "outside" / "secret.txt" + path.parent.mkdir() + path.write_bytes(b"secret") + return path + + +def _overwrite(table, attr, value, **key): + """Rewrite one stored value with SQL, bypassing the codec.""" + q = table.connection.adapter.quote_identifier + (pk_name, pk_value) = next(iter(key.items())) + table.connection.query( + f"UPDATE {table.full_table_name} SET {q(attr)} = %s WHERE {q(pk_name)} = %s", + args=(value, pk_value), + ) + + +def _json(table, attr, **key): + q = table.connection.adapter.quote_identifier + (pk_name, pk_value) = next(iter(key.items())) + raw = table.connection.query( + f"SELECT {q(attr)} FROM {table.full_table_name} WHERE {q(pk_name)} = %s", args=(pk_value,) + ).fetchone()[0] + return json.loads(raw) if isinstance(raw, (str, bytes)) else dict(raw) + + +@pytest.mark.parametrize("name", ["../escaped.txt", "../../escaped.txt", "sub/escaped.txt", "/tmp/escaped-dj.txt"]) +def test_attach_fetch_refuses_name_with_directory(schema_paths, tmp_path, name): + source = tmp_path / "report.txt" + source.write_bytes(b"report") + Document.insert1(dict(doc_id=1, inline_file=source, stored_file=source)) + _overwrite(Document, "inline_file", name.encode() + b"\x00payload", doc_id=1) + + download = tmp_path / "a" / "b" / "downloads" + with dj.config.override(download_path=str(download)): + with pytest.raises(dj.DataJointError, match="not a plain file name"): + (Document & "doc_id=1").fetch1("inline_file") + assert not (tmp_path / "a" / "b" / "escaped.txt").exists() + assert not (tmp_path / "a" / "escaped.txt").exists() + assert not (download / "sub").exists() + + +def test_attach_fetch_still_round_trips(schema_paths, tmp_path): + source = tmp_path / "report.txt" + source.write_bytes(b"report") + Document.insert1(dict(doc_id=1, inline_file=source, stored_file=source)) + download = tmp_path / "downloads" + with dj.config.override(download_path=str(download)): + inline, stored = (Document & "doc_id=1").fetch1("inline_file", "stored_file") + assert Path(inline).parent == download + assert Path(inline).read_bytes() == b"report" + assert Path(stored).read_bytes() == b"report" + + +def test_hash_fetch_refuses_path_outside_store(schema_paths, tmp_path, outside): + source = tmp_path / "report.txt" + source.write_bytes(b"report") + Document.insert1(dict(doc_id=1, inline_file=source, stored_file=source)) + meta = _json(Document, "stored_file", doc_id=1) + meta["path"] = str(outside) + _overwrite(Document, "stored_file", json.dumps(meta), doc_id=1) + with dj.config.override(download_path=str(tmp_path / "downloads")): + with pytest.raises(dj.DataJointError, match="outside the store location"): + (Document & "doc_id=1").fetch1("stored_file") + + +def test_filepath_insert_refuses_path_outside_store(schema_paths, outside): + repo = Path(dj.config.stores["repo"]["location"]) + for path in (str(outside), "../" * len(repo.parts) + str(outside).lstrip("/")): + with pytest.raises(dj.DataJointError, match="outside the store location"): + Reference.insert1(dict(ref_id=1, file_ref=path)) + assert len(Reference()) == 0 + + +@pytest.mark.parametrize("hostile", ["absolute", "relative", "device"]) +def test_filepath_fetch_refuses_path_outside_store(schema_paths, outside, hostile): + repo = Path(dj.config.stores["repo"]["location"]) + (repo / "inside.txt").write_bytes(b"inside") + Reference.insert1(dict(ref_id=1, file_ref="inside.txt")) + assert (Reference & "ref_id=1").fetch1("file_ref").read() == b"inside" + + meta = _json(Reference, "file_ref", ref_id=1) + meta["path"] = { + "absolute": str(outside), + "relative": "../" * len(repo.parts) + str(outside).lstrip("/"), + "device": "/dev/zero", + }[hostile] + _overwrite(Reference, "file_ref", json.dumps(meta), ref_id=1) + ref = (Reference & "ref_id=1").fetch1("file_ref") + with pytest.raises(dj.DataJointError, match="outside the store location"): + ref.read() + + +def test_filepath_outside_store_when_allowed(schema_paths, outside): + with dj.config.override(allow_filepath_outside_store=True): + Reference.insert1(dict(ref_id=1, file_ref=str(outside))) + assert (Reference & "ref_id=1").fetch1("file_ref").read() == b"secret" + with pytest.raises(dj.DataJointError, match="outside the store location"): + (Reference & "ref_id=1").fetch1("file_ref").read() + + +def test_object_fetch_refuses_path_outside_store(schema_paths, outside): + Output.insert1(dict(output_id=1, result=b"result")) + assert (Output & "output_id=1").fetch1("result").read() == b"result" + meta = _json(Output, "result", output_id=1) + meta["path"] = str(outside) + _overwrite(Output, "result", json.dumps(meta), output_id=1) + with pytest.raises(dj.DataJointError, match="outside the store location"): + (Output & "output_id=1").fetch1("result").read() + + +def test_object_insert_refuses_metadata_outside_store(schema_paths, outside): + with pytest.raises(dj.DataJointError, match="outside the store location"): + Output.insert1(dict(output_id=1, result={"path": str(outside), "store": "local", "size": 6})) + assert len(Output()) == 0 diff --git a/tests/unit/test_path_confinement.py b/tests/unit/test_path_confinement.py new file mode 100644 index 000000000..f65c47865 --- /dev/null +++ b/tests/unit/test_path_confinement.py @@ -0,0 +1,301 @@ +"""Stored values cannot direct file access outside the store or the download path. + +Rows written by one user are fetched by others, so a path or file name read back +from the database must not reach files the store or ``download_path`` does not +cover: ```` names must be plain file names, and store paths used by +````, ````, and hash-addressed storage must stay inside the +store location. ``allow_filepath_outside_store`` lifts the store check for +```` only. +""" + +import importlib +import os +import sys + +import pytest + +posix_only = pytest.mark.skipif(sys.platform == "win32", reason="needs POSIX symlinks, devices, or pipes") + + +@pytest.fixture(autouse=True) +def _live_modules(): + """ + Bind the names below from the currently imported ``datajoint`` package. + + Some unit tests purge ``datajoint`` from ``sys.modules`` and import it again; + names bound at collection time would then refer to stale classes, and + ``pytest.raises(DataJointError)`` would miss the error actually raised. + """ + global AttachCodec, FilepathCodec, ObjectCodec, DataJointError, Config, StorageBackend + AttachCodec = importlib.import_module("datajoint.builtin_codecs.attach").AttachCodec + FilepathCodec = importlib.import_module("datajoint.builtin_codecs.filepath").FilepathCodec + ObjectCodec = importlib.import_module("datajoint.builtin_codecs.object").ObjectCodec + DataJointError = importlib.import_module("datajoint.errors").DataJointError + Config = importlib.import_module("datajoint.settings").Config + StorageBackend = importlib.import_module("datajoint.storage").StorageBackend + + +@pytest.fixture +def layout(tmp_path): + """A file store, a sibling directory sharing its name as a prefix, and a download path.""" + store = tmp_path / "store" + store.mkdir() + (store / "data").mkdir() + (store / "data" / "inside.txt").write_text("inside") + sibling = tmp_path / "store-evil" + sibling.mkdir() + (sibling / "secret.txt").write_text("secret") + (tmp_path / "outside.txt").write_text("outside") + downloads = tmp_path / "downloads" + return tmp_path, store, downloads + + +@pytest.fixture +def cfg(layout): + _, store, downloads = layout + config = Config() + config.stores["local"] = {"protocol": "file", "location": str(store)} + config.stores["default"] = "local" + config.download_path = str(downloads) + return config + + +HOSTILE_RELATIVE = [ + "../outside.txt", + "data/../../outside.txt", + "../store-evil/secret.txt", + "..\\outside.txt", + "data/..\\..\\outside.txt", + "data/x\x00y", + "data/sub/../inside.txt", + "data/..", +] + + +# --------------------------------------------------------------------------- # +# StorageBackend._full_path +# --------------------------------------------------------------------------- # +class TestStorePathConfinement: + @pytest.mark.parametrize("path", HOSTILE_RELATIVE) + def test_file_store_rejects_relative_escape(self, layout, path): + _, store, _ = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + with pytest.raises(DataJointError, match="outside the store location"): + backend._full_path(path) + + def test_file_store_rejects_absolute_paths(self, layout): + root, store, _ = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + for path in (str(root / "outside.txt"), str(store / "data" / "inside.txt"), "/dev/zero"): + with pytest.raises(DataJointError, match="outside the store location"): + backend._full_path(path) + + @pytest.mark.parametrize("path", ["data/inside.txt", "./data/inside.txt", "data//inside.txt", ""]) + def test_file_store_accepts_paths_inside(self, layout, path): + _, store, _ = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + assert backend._full_path(path) == (store / path).as_posix() + + def test_io_never_reaches_outside(self, layout): + root, store, _ = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + with pytest.raises(DataJointError): + backend.get_buffer("/dev/zero") + with pytest.raises(DataJointError): + backend.get_buffer("../outside.txt") + with pytest.raises(DataJointError): + backend.put_buffer(b"x", "../written.txt") + with pytest.raises(DataJointError): + backend.remove("../outside.txt") + assert not (root / "written.txt").exists() + assert (root / "outside.txt").exists() + + @pytest.mark.parametrize("protocol", ["s3", "gcs", "azure"]) + def test_object_store_rejects_parent_components(self, protocol): + spec = {"protocol": protocol, "endpoint": "localhost:9000", "bucket": "b", "container": "b", "location": "loc"} + backend = StorageBackend(spec) + for path in ("../x", "a/../../x", "../../other-bucket/x"): + with pytest.raises(DataJointError, match="outside the store location"): + backend._full_path(path) + # Paths inside the location are unchanged, including a leading slash + assert backend._full_path("a/b") == "b/loc/a/b" + assert backend._full_path("/a/b") == "b/loc//a/b" + + def test_confinement_can_be_lifted_per_backend(self, layout): + root, store, _ = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + backend.confine_paths = False + assert backend._full_path(str(root / "outside.txt")) == (root / "outside.txt").as_posix() + assert backend.get_buffer("../outside.txt") == b"outside" + # Other backends stay confined + assert StorageBackend.confine_paths is True + + +# --------------------------------------------------------------------------- # +# +# --------------------------------------------------------------------------- # +class TestFilepathConfinement: + @pytest.mark.parametrize("path", HOSTILE_RELATIVE[:3]) + def test_encode_rejects_relative_escape(self, cfg, path): + with pytest.raises(DataJointError, match="outside the store location"): + FilepathCodec().encode(path, store_name="local", context={"config": cfg}) + + def test_encode_rejects_absolute_paths(self, cfg, layout): + root, store, _ = layout + for path in (str(root / "outside.txt"), str(store / "data" / "inside.txt"), "/dev/zero"): + with pytest.raises(DataJointError, match="outside the store location"): + FilepathCodec().encode(path, store_name="local", context={"config": cfg}) + + @pytest.mark.parametrize("path", ["./_hash/x.bin", "././_schema/x", ".//_hash/x", "_hash"]) + def test_encode_reserved_sections_after_normalizing(self, cfg, path): + with pytest.raises(ValueError, match="reserved section"): + FilepathCodec().encode(path, store_name="local", context={"config": cfg}) + + def test_encode_filepath_prefix_after_normalizing(self, cfg, layout): + _, store, _ = layout + cfg.stores["local"]["filepath_prefix"] = "data" + (store / "other.txt").write_text("other") + with pytest.raises(DataJointError, match="outside the store location"): + FilepathCodec().encode("data/../other.txt", store_name="local", context={"config": cfg}) + with pytest.raises(ValueError, match="filepath_prefix"): + FilepathCodec().encode("other.txt", store_name="local", context={"config": cfg}) + for path in ("data/inside.txt", "./data/inside.txt"): + meta = FilepathCodec().encode(path, store_name="local", context={"config": cfg}) + assert meta["path"] == path + + def test_round_trip_inside_store(self, cfg): + codec = FilepathCodec() + meta = codec.encode("data/inside.txt", store_name="local", context={"config": cfg}) + assert codec.decode(meta, context={"config": cfg}).read() == b"inside" + + @pytest.mark.parametrize("kind", ["absolute", "relative", "sibling", "device"]) + def test_decode_of_hostile_row_does_not_read_outside(self, cfg, layout, kind): + root, _, _ = layout + path = { + "absolute": str(root / "outside.txt"), + "relative": "../outside.txt", + "sibling": "../store-evil/secret.txt", + "device": "/dev/zero", + }[kind] + ref = FilepathCodec().decode({"path": path, "store": "local", "size": None}, context={"config": cfg}) + with pytest.raises(DataJointError, match="outside the store location"): + ref.read() + with pytest.raises(DataJointError, match="outside the store location"): + ref.download(root / "dl") + + def test_escape_hatch_allows_outside_references(self, cfg, layout): + root, _, _ = layout + cfg.allow_filepath_outside_store = True + codec = FilepathCodec() + meta = codec.encode("../outside.txt", store_name="local", context={"config": cfg}) + assert codec.decode(meta, context={"config": cfg}).read() == b"outside" + absolute = {"path": str(root / "outside.txt"), "store": "local", "size": None} + assert codec.decode(absolute, context={"config": cfg}).read() == b"outside" + + def test_escape_hatch_does_not_apply_to_object(self, cfg, layout): + root, _, _ = layout + cfg.allow_filepath_outside_store = True + ref = ObjectCodec().decode({"path": str(root / "outside.txt"), "store": "local", "size": 7}, context={"config": cfg}) + with pytest.raises(DataJointError, match="outside the store location"): + ref.read() + + +# --------------------------------------------------------------------------- # +# +# --------------------------------------------------------------------------- # +class TestObjectConfinement: + @pytest.mark.parametrize("path", ["../outside.txt", "/dev/zero", "_schema/../../outside.txt"]) + def test_encode_rejects_precomputed_metadata_outside_store(self, cfg, path): + with pytest.raises(DataJointError, match="outside the store location"): + ObjectCodec().encode({"path": path, "store": "local", "size": 1}, context={"config": cfg}) + + def test_encode_passes_precomputed_metadata_inside_store(self, cfg): + meta = {"path": "_schema/s/t/k/f_tok", "store": "local", "size": 1} + assert ObjectCodec().encode(meta, context={"config": cfg}) is meta + + def test_decode_of_hostile_row_does_not_read_outside(self, cfg, layout): + root, _, _ = layout + ref = ObjectCodec().decode({"path": str(root / "outside.txt"), "store": "local", "size": 7}, context={"config": cfg}) + with pytest.raises(DataJointError, match="outside the store location"): + ref.read() + + +# --------------------------------------------------------------------------- # +# +# --------------------------------------------------------------------------- # +def _attach_blob(name: str, contents: bytes) -> bytes: + return name.encode("utf-8") + b"\x00" + contents + + +class TestAttachConfinement: + @pytest.mark.parametrize( + "name", + ["../evil.txt", "../../evil.txt", "sub/evil.txt", "..\\evil.txt", "..", ".", "", "/evil.txt"], + ) + def test_decode_rejects_names_that_are_not_plain(self, cfg, layout, name): + root, _, downloads = layout + with pytest.raises(DataJointError, match="not a plain file name"): + AttachCodec().decode(_attach_blob(name, b"payload"), context={"config": cfg}) + assert not (root / "evil.txt").exists() + assert not (downloads / "sub").exists() + + def test_decode_rejects_absolute_name(self, cfg, layout): + root, _, _ = layout + target = root / "absolute.txt" + with pytest.raises(DataJointError, match="not a plain file name"): + AttachCodec().decode(_attach_blob(str(target), b"payload"), context={"config": cfg}) + assert not target.exists() + + def test_round_trip(self, cfg, layout, tmp_path): + _, _, downloads = layout + source = tmp_path / "notes.txt" + source.write_bytes(b"hello") + codec = AttachCodec() + blob = codec.encode(source) + assert blob == _attach_blob("notes.txt", b"hello") + first = codec.decode(blob, context={"config": cfg}) + assert first == str(downloads / "notes.txt") + # Identical content reuses the file; different content gets a new name + assert codec.decode(blob, context={"config": cfg}) == first + second = codec.decode(_attach_blob("notes.txt", b"changed"), context={"config": cfg}) + assert second == str(downloads / "notes_1.txt") + assert (downloads / "notes.txt").read_bytes() == b"hello" + assert (downloads / "notes_1.txt").read_bytes() == b"changed" + + @posix_only + def test_decode_does_not_read_device_behind_link(self, cfg, layout): + _, _, downloads = layout + downloads.mkdir() + (downloads / "zero").symlink_to("/dev/zero") + result = AttachCodec().decode(_attach_blob("zero", b"payload"), context={"config": cfg}) + assert result == str(downloads / "zero_1") + assert os.readlink(downloads / "zero") == "/dev/zero" + + @posix_only + def test_decode_does_not_open_pipe(self, cfg, layout): + _, _, downloads = layout + downloads.mkdir() + os.mkfifo(downloads / "pipe") + result = AttachCodec().decode(_attach_blob("pipe", b"payload"), context={"config": cfg}) + assert result == str(downloads / "pipe_1") + + @posix_only + def test_decode_does_not_write_through_link(self, cfg, layout): + root, _, downloads = layout + downloads.mkdir() + (downloads / "outside.txt").symlink_to(root / "outside.txt") + result = AttachCodec().decode(_attach_blob("outside.txt", b"overwritten"), context={"config": cfg}) + assert result == str(downloads / "outside_1.txt") + assert (root / "outside.txt").read_text() == "outside" + # A link is not reused even when its target holds the same content + result = AttachCodec().decode(_attach_blob("outside.txt", b"outside"), context={"config": cfg}) + assert result == str(downloads / "outside_2.txt") + + @posix_only + def test_decode_does_not_follow_dangling_link(self, cfg, layout): + root, _, downloads = layout + downloads.mkdir() + (downloads / "new.txt").symlink_to(root / "created-through-link.txt") + result = AttachCodec().decode(_attach_blob("new.txt", b"payload"), context={"config": cfg}) + assert result == str(downloads / "new_1.txt") + assert not (root / "created-through-link.txt").exists() From 64eec34fa36d346bb125cca987803501dce2ec07 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 9 Nov 2026 13:09:14 -0600 Subject: [PATCH 21/37] Render values in mapping restrictions as quoted literals Values in dict restrictions are now rendered through one function that uses the backend adapter's string quoting, for strings, lists, dates, decimals and JSON objects alike. List values and JSON objects compared against a JSON path were previously placed between quotes without escaping, so a value containing a quote produced malformed SQL. - JSON return types after `:` (e.g. `attr.path:decimal(4,1)`) must be a known type name with optional length/precision. - A key that is neither an attribute name nor a valid JSON path is rejected instead of being quoted as an identifier. - Values of unsupported types (bytes, sets, objects) raise DataJointError instead of producing invalid SQL. - JSON path segments are quoted with the adapter's string quoting. Rendered SQL is unchanged for values that need no escaping. On PostgreSQL, backslashes in string values are still doubled, so string restrictions match the same rows as before. --- src/datajoint/adapters/mysql.py | 2 +- src/datajoint/adapters/postgres.py | 2 +- src/datajoint/condition.py | 45 +++- tests/integration/test_restriction_values.py | 126 +++++++++++ tests/unit/test_condition.py | 223 +++++++++++++++++++ 5 files changed, 387 insertions(+), 11 deletions(-) create mode 100644 tests/integration/test_restriction_values.py diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index 38e3ad1b1..3802007d3 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -892,7 +892,7 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) """ quoted_col = self.quote_identifier(column) return_clause = f" returning {return_type}" if return_type else "" - return f"json_value({quoted_col}, _utf8mb4'$.{path}'{return_clause})" + return f"json_value({quoted_col}, _utf8mb4{self.quote_string('$.' + path)}{return_clause})" def translate_expression(self, expr: str) -> str: """ diff --git a/src/datajoint/adapters/postgres.py b/src/datajoint/adapters/postgres.py index 91cc5311b..3bd1cd377 100644 --- a/src/datajoint/adapters/postgres.py +++ b/src/datajoint/adapters/postgres.py @@ -1136,7 +1136,7 @@ def json_path_expr(self, column: str, path: str, return_type: str | None = None) path_parts.extend(indices) else: path_parts.append(part) - path_args = ", ".join(f"'{part}'" for part in path_parts) + path_args = ", ".join(self.quote_string(part) for part in path_parts) expr = f"jsonb_extract_path_text({quoted_col}, {path_args})" # Add cast if return type specified if return_type: diff --git a/src/datajoint/condition.py b/src/datajoint/condition.py index 650015539..7f4c42560 100644 --- a/src/datajoint/condition.py +++ b/src/datajoint/condition.py @@ -13,6 +13,7 @@ import inspect import json import logging +import numbers import re import uuid from dataclasses import dataclass @@ -30,6 +31,18 @@ JSON_PATTERN = re.compile(r"^(?P\w+)(\.(?P[\w.*\[\]]+))?(:(?P[\w(,\s)]+))?$") +# Return types accepted after ``:`` in a JSON attribute key, e.g. ``"attr.path:decimal(10,2)"`` +JSON_TYPE_PATTERN = re.compile( + r"\s*(?:(?:un)?signed(?:\s+integer)?|integer|int|bigint|smallint|float|double(?:\s+precision)?|real" + r"|decimal|numeric|date|time|datetime|timestamp|year|char|varchar|binary|text|jsonb?|bool(?:ean)?)" + r"(?:\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\))?" + r"(?:\s+(?:character\s+set|charset)\s+\w+)?(?:\s+collate\s+\w+)?\s*", + re.IGNORECASE, +) + +# Text of a numeric value that may appear unquoted in a condition +NUMERIC_LITERAL_PATTERN = re.compile(r"[+-]?(?:(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?|nan|inf)|true|false", re.IGNORECASE) + def translate_attribute(key: str, adapter=None) -> tuple[dict | None, str]: """ @@ -56,6 +69,8 @@ def translate_attribute(key: str, adapter=None) -> tuple[dict | None, str]: if match["path"] is None: return match, match["attr"] else: + if match["type"] is not None and not JSON_TYPE_PATTERN.fullmatch(match["type"]): + raise DataJointError(f"Unsupported return type `{match['type']}` in JSON attribute `{key}`.") # Use adapter's json_path_expr if available, otherwise fall back to MySQL syntax if adapter is not None: return match, adapter.json_path_expr(match["attr"], match["path"], match["type"]) @@ -335,18 +350,25 @@ def make_condition( # Get adapter for backend-agnostic SQL generation adapter = query_expression.connection.adapter + def literal(text): + """quoted string literal; % is doubled for the driver's parameter substitution""" + return adapter.quote_string(text).replace("%", "%%") + def prep_value(k, v): """prepare SQL condition""" + key = k key_match, k = translate_attribute(k, adapter) - is_json_path = key_match is not None and key_match.get("path") is not None + if key_match is None: + raise DataJointError(f"Invalid attribute name `{key}` in restriction.") + is_json_path = key_match.get("path") is not None if not is_json_path: k = adapter.quote_identifier(k) if is_json_path and isinstance(v, dict): - return f"{k}='{json.dumps(v)}'" + return f"{k}={literal(json.dumps(v))}" if v is None: return f"{k} IS NULL" - if key_match is not None and query_expression.heading[key_match["attr"]].uuid: + if query_expression.heading[key_match["attr"]].uuid: if not isinstance(v, uuid.UUID): try: v = uuid.UUID(v) @@ -363,13 +385,18 @@ def prep_value(k, v): list, ), ): - # Use single quotes for string literals (works for both MySQL and PostgreSQL) - return f"{k}='{v}'" + return f"{k}={literal(str(v))}" if isinstance(v, str): - # Escape single quotes by doubling them, and escape % for driver - v = v.replace("'", "''").replace("%", "%%").replace("\\", "\\\\") - return f"{k}='{v}'" - return f"{k}={v}" + if adapter.backend == "postgresql": + # Backslashes are doubled as in previous releases so that string + # restrictions keep matching the same rows. + v = v.replace("\\", "\\\\") + return f"{k}={literal(v)}" + if isinstance(v, (numbers.Number, numpy.number, numpy.bool_)): + text = f"{v}" + if NUMERIC_LITERAL_PATTERN.fullmatch(text): + return f"{k}={text}" + raise DataJointError(f"Unsupported value of type {type(v).__name__} in restriction by `{key}`.") def combine_conditions(negate, conditions): return f"{'NOT ' if negate else ''} ({')AND('.join(conditions)})" diff --git a/tests/integration/test_restriction_values.py b/tests/integration/test_restriction_values.py new file mode 100644 index 000000000..19bf30f3d --- /dev/null +++ b/tests/integration/test_restriction_values.py @@ -0,0 +1,126 @@ +""" +Mapping restrictions with values that need quoting, on both backends. + +Values in dict restrictions are compared as literals: quotes, backslashes, ``%``, +and SQL fragments inside them select no extra rows. +""" + +import numpy as np +import pytest + +import datajoint as dj + +ROWS = [ + dict(item_id=1, name="alpha", data={"label": "alpha", "tags": [1, 2], "sub": {"k": 1}, "size": 3}), + dict(item_id=2, name="o'brien", data={"label": "o'brien", "tags": [3], "sub": {"k": 2}, "size": 4}), + dict(item_id=3, name="50% off", data={"label": "50% off", "tags": [], "sub": {"k": 3}, "size": 5}), + dict(item_id=4, name='say "hi"', data={"label": 'say "hi"', "tags": [4], "sub": {"k": "x"}, "size": 6}), +] + +HOSTILE = [ + "' OR 1=1 --", + "' OR '1'='1", + "x' OR 'a'='a", + "\\' OR 1=1 -- ", + "') OR ('1'='1", + '" OR ""="', + "'; DELETE FROM item; --", + "%' OR 1=1 --", +] + + +@pytest.fixture +def item(connection_by_backend, backend, prefix): + schema = dj.Schema(f"{prefix}_restriction_values_{backend}", connection=connection_by_backend) + + @schema + class Item(dj.Manual): + definition = """ + item_id : int32 + --- + name : varchar(64) + data = null : json + """ + + Item.insert(ROWS) + yield Item() + schema.drop(prompt=False) + + +def ids(query): + return sorted(query.to_arrays("item_id").tolist()) + + +@pytest.mark.parametrize("value", HOSTILE) +def test_hostile_string_values_match_nothing(item, value): + assert ids(item & {"name": value}) == [] + assert ids(item & {"data.label": value}) == [] + assert ids(item & {"data.sub": {"k": value}}) == [] + assert ids(item & {"name": [value, 'a"b', "c'd"]}) == [] + assert ids(item & [{"name": value}, {"item_id": 1}]) == [1] + assert ids(item - {"name": value}) == [1, 2, 3, 4] + assert len(item & {"name": value}) == 0 + + +@pytest.mark.parametrize("value", HOSTILE) +def test_hostile_values_do_not_delete(item, value): + (item & {"name": value}).delete_quick() + (item & {"data.label": value}).delete_quick() + (item & {"name": [value]}).delete_quick() + (item & {"data.sub": {"k": value}}).delete_quick() + assert len(item) == len(ROWS) + + +@pytest.mark.parametrize( + "key", + [ + "data.x') OR 1=1 -- ", + "data.x` OR 1=1 OR `y", + 'data.x" OR 1=1 OR "y', + "data.label'] OR 1=1 --", + ], +) +def test_invalid_json_keys_rejected(item, key): + with pytest.raises(dj.DataJointError): + item & {key: 1} + + +@pytest.mark.parametrize("type_spec", ["unsigned) OR (1", "char(20)) OR (1", "signed or 1", "nonsense"]) +def test_invalid_json_types_rejected(item, type_spec): + with pytest.raises(dj.DataJointError): + item & {f"data.size:{type_spec}": 1} + + +def test_unsupported_value_types_rejected(item): + with pytest.raises(dj.DataJointError): + item & {"name": b"' OR 1=1 --"} + with pytest.raises(dj.DataJointError): + item & {"name": {"a": "' OR 1=1 --"}} + + +def test_ordinary_values_still_match(item): + assert ids(item & {"item_id": 2}) == [2] + assert ids(item & {"item_id": np.int64(3)}) == [3] + assert ids(item & {"name": "alpha"}) == [1] + assert ids(item & {"name": "o'brien"}) == [2] + assert ids(item & {"name": "50% off"}) == [3] + assert ids(item & {"name": 'say "hi"'}) == [4] + assert ids(item & [{"name": "alpha"}, {"name": "o'brien"}]) == [1, 2] + assert ids(item - {"name": "o'brien"}) == [1, 3, 4] + assert ids(item & {"data.label": "o'brien"}) == [2] + assert ids(item & {"data.label": "50% off"}) == [3] + assert ids(item & {"data.tags": [1, 2]}) == [1] + assert ids(item & {"data.sub": {"k": 2}}) == [2] + assert ids(item & {"data.sub": {"k": "x"}}) == [4] + assert ids(item & {"data.size:unsigned": 5}) == [3] + assert ids(item & {"data.size:decimal(4, 1)": 6}) == [4] + assert ids(item & {"data": None}) == [] + + +def test_string_with_backslash(item, backend): + """On MySQL a backslash in a string value matches itself.""" + item.insert1(dict(item_id=5, name="back\\slash", data={"label": "back\\slash", "sub": {"k": "a\\b"}})) + assert ids(item & {"data.sub": {"k": "a\\b"}}) == [5] + if backend == "mysql": + assert ids(item & {"name": "back\\slash"}) == [5] + assert ids(item & {"data.label": "back\\slash"}) == [5] diff --git a/tests/unit/test_condition.py b/tests/unit/test_condition.py index 3200e34c4..ef168c3fc 100644 --- a/tests/unit/test_condition.py +++ b/tests/unit/test_condition.py @@ -93,3 +93,226 @@ def test_invalid_offset_type_raises(self): """Non-integer offset raises TypeError.""" with pytest.raises(TypeError): Top(offset="1") + + +# --------------------------------------------------------------------------- +# Rendering of values in mapping restrictions +# --------------------------------------------------------------------------- + +import datetime # noqa: E402 +import decimal # noqa: E402 +import importlib.util # noqa: E402 +import json # noqa: E402 +import uuid # noqa: E402 +from types import SimpleNamespace # noqa: E402 + +import numpy as np # noqa: E402 + +from datajoint.adapters import get_adapter # noqa: E402 +from datajoint.condition import make_condition, translate_attribute # noqa: E402 +from datajoint.errors import DataJointError # noqa: E402 + +BACKENDS = [ + "mysql", + pytest.param( + "postgresql", + marks=pytest.mark.skipif(importlib.util.find_spec("psycopg2") is None, reason="psycopg2 not installed"), + ), +] + +HOSTILE_STRINGS = [ + "' OR 1=1 --", + "x' OR '1'='1", + "\\' OR 1=1 -- ", + "\\", + "a\\'b", + "''", + 'it\'s "quoted"', + "50% off", + "%s", + "line\nbreak; DROP TABLE x; --", + "\x00\x1a", +] + + +def _fake_expression(backend, names=("name", "car", "uid")): + """Stand-in for a query expression: an adapter and a heading.""" + attributes = {n: SimpleNamespace(uuid=(n == "uid")) for n in names} + heading = type("Heading", (), {"names": list(names), "__getitem__": lambda self, k: attributes[k]})() + return SimpleNamespace(connection=SimpleNamespace(adapter=get_adapter(backend)), heading=heading) + + +def _condition(backend, restriction): + return make_condition(_fake_expression(backend), restriction, set()) + + +def _read_literal(backend, sql): + """ + Read one quoted string literal at the start of ``sql`` using the backend's rules + (MySQL with backslash escapes; PostgreSQL with standard_conforming_strings on). + + Returns the literal's value and the text that follows it. + """ + assert sql[0] == "'", sql + out, i = [], 1 + while i < len(sql): + c = sql[i] + if c == "\\" and backend == "mysql": + nxt = sql[i + 1] + out.append({"n": "\n", "r": "\r", "0": "\x00", "Z": "\x1a", "t": "\t", "b": "\b"}.get(nxt, nxt)) + i += 2 + elif c == "'": + if sql[i + 1 : i + 2] == "'": + out.append("'") + i += 2 + else: + return "".join(out), sql[i + 1 :] + else: + out.append(c) + i += 1 + raise AssertionError(f"unterminated literal in {sql!r}") + + +def _literal_value(backend, condition, lhs): + """Value of the single literal compared with ``lhs`` in a one-term condition.""" + sql = condition % () # the driver's parameter substitution turns %% into % + prefix = f" ({lhs}=" + assert sql.startswith(prefix), sql + value, rest = _read_literal(backend, sql[len(prefix) :]) + assert rest == ")", f"text after the literal: {rest!r}" + return value + + +def _quoted(backend, name): + return get_adapter(backend).quote_identifier(name) + + +def _json_lhs(backend, path): + return translate_attribute(f"car.{path}", get_adapter(backend))[1] + + +@pytest.mark.parametrize("backend", BACKENDS) +class TestRestrictionLiterals: + """Values in mapping restrictions are rendered as single, complete literals.""" + + @pytest.mark.parametrize("value", HOSTILE_STRINGS) + def test_string_value(self, backend, value): + cond = _condition(backend, {"name": value}) + expected = value if backend == "mysql" else value.replace("\\", "\\\\") + assert _literal_value(backend, cond, _quoted(backend, "name")) == expected + + @pytest.mark.parametrize("value", HOSTILE_STRINGS) + def test_json_path_string_value(self, backend, value): + cond = _condition(backend, {"car.name": value}) + expected = value if backend == "mysql" else value.replace("\\", "\\\\") + assert _literal_value(backend, cond, _json_lhs(backend, "name")) == expected + + @pytest.mark.parametrize("value", HOSTILE_STRINGS) + def test_list_value(self, backend, value): + items = [value, 1, 'a"b', "c'd"] + cond = _condition(backend, {"car.tags": items}) + assert _literal_value(backend, cond, _json_lhs(backend, "tags")) == str(items) + + @pytest.mark.parametrize("value", HOSTILE_STRINGS) + def test_json_dict_value(self, backend, value): + obj = {"side": value, value: True, "nested": {"k": [value]}} + cond = _condition(backend, {"car.headlights[1]": obj}) + assert _literal_value(backend, cond, _json_lhs(backend, "headlights[1]")) == json.dumps(obj) + + @pytest.mark.parametrize( + "key", + [ + "car.na'me", + 'car.na"me', + "car.x`) OR 1=1 -- ", + 'car.x") OR 1=1 -- ', + "car.a\\b", + "car.name'] OR 1=1 --", + "car.name OR 1=1", + "car.", + ], + ) + def test_invalid_json_key_rejected(self, backend, key): + with pytest.raises(DataJointError): + _condition(backend, {key: 1}) + + @pytest.mark.parametrize( + "type_spec", + [ + "unsigned) OR (1", + "char(20)) OR (1", + "unsigned) OR sleep(5", + "signed or 1", + "text, 1", + "decimal(4, 1) or 1", + "nonsense", + ], + ) + def test_invalid_json_type_rejected(self, backend, type_spec): + with pytest.raises(DataJointError): + _condition(backend, {f"car.length:{type_spec}": 1}) + + @pytest.mark.parametrize( + "type_spec", ["unsigned", "signed", "float", "double", "decimal(4, 1)", "decimal(10,2)", "char(20)", "DATETIME"] + ) + def test_valid_json_type_accepted(self, backend, type_spec): + cond = _condition(backend, {f"car.length:{type_spec}": 1}) + assert cond.endswith("=1)") + + @pytest.mark.parametrize("value", [b"x' OR 1=1 --", object(), {"a": 1}, (1, 2), np.datetime64("2020-01-01"), 1 + 2j]) + def test_unsupported_value_type_rejected(self, backend, value): + with pytest.raises(DataJointError): + _condition(backend, {"name": value}) + + def test_negated_hostile_value(self, backend): + from datajoint.condition import Not + + cond = make_condition(_fake_expression(backend), Not({"name": "' OR 1=1 --"}), set()) + assert cond.startswith("NOT ") + assert _literal_value(backend, cond[4:], _quoted(backend, "name")) == "' OR 1=1 --" + + +@pytest.mark.parametrize("backend", BACKENDS) +@pytest.mark.parametrize( + "restriction, expected", + [ + ({"name": "alpha"}, " ({name}='alpha')"), + ({"name": 5}, " ({name}=5)"), + ({"name": -2.5}, " ({name}=-2.5)"), + ({"name": 1e-20}, " ({name}=1e-20)"), + ({"name": True}, " ({name}=True)"), + ({"name": np.int64(7)}, " ({name}=7)"), + ({"name": np.float64(0.25)}, " ({name}=0.25)"), + ({"name": np.bool_(False)}, " ({name}=False)"), + ({"name": None}, " ({name} IS NULL)"), + ({"name": decimal.Decimal("1.50")}, " ({name}='1.50')"), + ({"name": datetime.date(2020, 1, 2)}, " ({name}='2020-01-02')"), + ({"name": datetime.datetime(2020, 1, 2, 3, 4, 5)}, " ({name}='2020-01-02 03:04:05')"), + ({"name": datetime.time(3, 4, 5)}, " ({name}='03:04:05')"), + ({"car.tire_pressure": [34, 30, 27, 32]}, " ({tire_pressure}='[34, 30, 27, 32]')"), + ({"uid": uuid.UUID(int=255)}, " ({uid}=X'000000000000000000000000000000ff')"), + ], +) +def test_ordinary_values_render_as_before(backend, restriction, expected): + """Values that do not need escaping are rendered exactly as in previous releases.""" + adapter = get_adapter(backend) + names = { + "name": adapter.quote_identifier("name"), + "uid": adapter.quote_identifier("uid"), + "tire_pressure": _json_lhs(backend, "tire_pressure"), + } + assert _condition(backend, restriction) == expected.format(**names) + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_json_path_expression_unchanged(backend): + """JSON paths render as in previous releases.""" + adapter = get_adapter(backend) + if backend == "mysql": + assert translate_attribute("car.headlights[0].side:char(20)", adapter)[1] == ( + "json_value(`car`, _utf8mb4'$.headlights[0].side' returning char(20))" + ) + else: + assert translate_attribute("car.headlights[0].side", adapter)[1] == ( + "jsonb_extract_path_text(\"car\", 'headlights', '0', 'side')" + ) From 0758f671c9cc317d032872d8e1e145145605e7e0 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 9 Nov 2026 13:07:31 -0600 Subject: [PATCH 22/37] fix(connection): require TLS when use_tls is set; honor use_tls certificate options MySQL: use_tls=True now requires TLS. It previously passed ssl={} to PyMySQL, which treats an empty dict as TLS not requested, so the connection was not encrypted. True and {} use TLS without certificate verification. A use_tls dict is passed to PyMySQL; with "ca", the server certificate is verified. When TLS is required and the server does not offer it, the connection is refused before the credentials are sent. PostgreSQL: a use_tls dict maps "ca", "cert", "key", "password" to sslrootcert, sslcert, sslkey, sslpassword. With "ca", sslmode is verify-full (verify-ca when "check_hostname" is False); otherwise require. These keys were ignored before. use_tls not set (default): the retry without TLS now happens only when TLS negotiation fails (the server does not support TLS, or the TLS handshake fails), not after authentication or other errors. On MySQL, the default now uses TLS when the server offers it, as documented. use_tls=False is unchanged. --- src/datajoint/adapters/base.py | 20 ++ src/datajoint/adapters/mysql.py | 66 ++++- src/datajoint/adapters/postgres.py | 57 ++++- src/datajoint/connection.py | 15 +- tests/unit/test_tls.py | 380 +++++++++++++++++++++++++++++ 5 files changed, 525 insertions(+), 13 deletions(-) create mode 100644 tests/unit/test_tls.py diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 1aa12f52f..55eb6b641 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -55,6 +55,26 @@ def connect( """ ... + def is_tls_negotiation_error(self, error: Exception) -> bool: + """ + Whether a connection attempt failed while negotiating TLS. + + When ``use_tls`` is not set, a connection that fails to negotiate TLS + (the server does not support it, or the TLS handshake fails) is retried + without TLS. Authentication and other errors are not retried. + + Parameters + ---------- + error : Exception + Exception raised by :meth:`connect`. + + Returns + ------- + bool + True if the failure is in TLS negotiation. Default False. + """ + return False + @abstractmethod def close(self, connection: Any) -> None: """ diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index 38e3ad1b1..68cf2dcb8 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -7,9 +7,11 @@ from __future__ import annotations +import ssl from typing import Any import pymysql as client +from pymysql.constants import CLIENT, CR from .. import errors from .base import DatabaseAdapter @@ -45,6 +47,39 @@ } +class _TLSUnavailableError(client.err.OperationalError): + """TLS is required but the server does not offer it.""" + + def __init__(self): + super().__init__( + CR.CR_SSL_CONNECTION_ERROR, + "TLS is required (use_tls) but the server does not support it", + ) + + +class _TLSRequiredConnection(client.connections.Connection): + """ + PyMySQL connection that does not authenticate without TLS. + + PyMySQL continues without TLS when the server does not offer it, even when + TLS is configured. This check runs after the server greeting, before the + credentials are sent. + """ + + def _request_authentication(self): + if not self.server_capabilities & CLIENT.SSL: + raise _TLSUnavailableError() + super()._request_authentication() + + +def _unverified_tls_context() -> ssl.SSLContext: + """TLS context that encrypts without verifying the server certificate.""" + context = ssl.create_default_context() + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + return context + + class MySQLAdapter(DatabaseAdapter): """MySQL database adapter implementation.""" @@ -76,7 +111,11 @@ def connect( **kwargs : Any Additional MySQL-specific parameters: - ssl: TLS/SSL configuration dict (deprecated, use use_tls) - - use_tls: bool or dict - DataJoint's SSL parameter (preferred) + - use_tls: bool or dict - DataJoint's SSL parameter (preferred). + True: TLS required, server certificate not verified. + dict: TLS required, configured with PyMySQL ``ssl`` keys + (``ca``, ``cert``, ``key``, ``check_hostname``, ...); with ``ca``, + the server certificate is verified. False: TLS disabled. - charset: Character set (default from kwargs) Returns @@ -86,9 +125,10 @@ def connect( """ # Handle both ssl (old) and use_tls (new) parameter names ssl_config = kwargs.get("use_tls", kwargs.get("ssl")) - # Convert boolean True to dict for PyMySQL (PyMySQL expects dict or SSLContext) - if ssl_config is True: - ssl_config = {} # Enable SSL with default settings + # PyMySQL treats an empty dict as "no TLS"; True and {} require TLS + # without verifying the server certificate. + if ssl_config is True or (isinstance(ssl_config, dict) and not ssl_config): + ssl_config = _unverified_tls_context() charset = kwargs.get("charset", "") # Prepare connection parameters @@ -108,13 +148,29 @@ def connect( # Explicitly disable SSL conn_params["ssl_disabled"] = True elif ssl_config is not None: - # Enable SSL with config dict (can be empty for defaults) + # Require SSL, configured by the dict or SSLContext conn_params["ssl"] = ssl_config # Explicitly enable SSL by setting ssl_disabled=False conn_params["ssl_disabled"] = False + connection = _TLSRequiredConnection(**conn_params) + # Checked again in case a PyMySQL version bypasses the hook above + if not connection.server_capabilities & CLIENT.SSL: + connection.close() + raise _TLSUnavailableError() + return connection return client.connect(**conn_params) + def is_tls_negotiation_error(self, error: Exception) -> bool: + """ + Whether a connection attempt failed while negotiating TLS. + + Matches a server that does not offer TLS, and a failed TLS handshake + (reported by PyMySQL as ``OperationalError`` carrying the ``SSLError``). + Both happen before the credentials are sent. + """ + return isinstance(error, _TLSUnavailableError) or isinstance(getattr(error, "original_exception", None), ssl.SSLError) + def close(self, connection: Any) -> None: """Close the MySQL connection.""" connection.close() diff --git a/src/datajoint/adapters/postgres.py b/src/datajoint/adapters/postgres.py index 91cc5311b..7e326e60e 100644 --- a/src/datajoint/adapters/postgres.py +++ b/src/datajoint/adapters/postgres.py @@ -7,6 +7,7 @@ from __future__ import annotations +import logging import re from typing import Any @@ -20,6 +21,34 @@ from .. import errors from .base import DatabaseAdapter +logger = logging.getLogger(__name__.split(".")[0]) + +# use_tls dict keys (PyMySQL ssl names, as for MySQL) → libpq connection parameters +_LIBPQ_TLS_KEYS = {"ca": "sslrootcert", "cert": "sslcert", "key": "sslkey", "password": "sslpassword"} + +# libpq messages for a server without SSL support and for a failed SSL handshake +_TLS_NEGOTIATION_MESSAGES = ("server does not support SSL", "SSL error:", "SSL SYSCALL error:") + + +def _libpq_tls_params(use_tls: dict) -> dict[str, Any]: + """ + Map a ``use_tls`` dict to libpq SSL connection parameters. + + With ``ca``, the server certificate is verified against it: sslmode + ``verify-full`` (certificate and host name), or ``verify-ca`` when + ``check_hostname`` is False. Without ``ca``, sslmode is ``require``. + """ + params = {_LIBPQ_TLS_KEYS[k]: v for k, v in use_tls.items() if k in _LIBPQ_TLS_KEYS and v is not None} + if "sslrootcert" in params: + params["sslmode"] = "verify-full" if use_tls.get("check_hostname", True) else "verify-ca" + else: + params["sslmode"] = "require" + ignored = sorted(set(use_tls) - set(_LIBPQ_TLS_KEYS) - {"check_hostname"}) + if ignored: + logger.warning("use_tls keys not supported for PostgreSQL are ignored: %s", ", ".join(ignored)) + return params + + # Core type mapping: DataJoint core types → PostgreSQL types CORE_TYPE_MAP = { "int64": "bigint", @@ -90,8 +119,13 @@ def connect( **kwargs : Any Additional PostgreSQL-specific parameters: - dbname: Database name - - sslmode: SSL mode ('disable', 'allow', 'prefer', 'require') - - use_tls: bool or dict - DataJoint's SSL parameter (converted to sslmode) + - sslmode: SSL mode ('disable', 'allow', 'prefer', 'require', + 'verify-ca', 'verify-full') + - use_tls: bool or dict - DataJoint's SSL parameter (converted to sslmode). + True: 'require'. False: 'disable'. None: 'prefer'. + dict: ``ca``, ``cert``, ``key``, ``password`` map to sslrootcert, + sslcert, sslkey, sslpassword; sslmode is 'verify-full' with ``ca`` + ('verify-ca' if ``check_hostname`` is False), otherwise 'require'. - connect_timeout: Connection timeout in seconds Returns @@ -105,14 +139,19 @@ def connect( # Handle use_tls parameter (from DataJoint Connection) # Convert to PostgreSQL's sslmode use_tls = kwargs.get("use_tls") + tls_params = {} if "sslmode" in kwargs: # Explicit sslmode takes precedence sslmode = kwargs["sslmode"] elif use_tls is False: # use_tls=False → disable SSL sslmode = "disable" - elif use_tls is True or isinstance(use_tls, dict): - # use_tls=True or dict → require SSL + elif isinstance(use_tls, dict): + # use_tls=dict → require SSL, verified when a CA is given + tls_params = _libpq_tls_params(use_tls) + sslmode = tls_params.pop("sslmode") + elif use_tls is True: + # use_tls=True → require SSL sslmode = "require" else: # use_tls=None (default) → prefer SSL but allow fallback @@ -126,6 +165,7 @@ def connect( dbname=dbname, sslmode=sslmode, connect_timeout=connect_timeout, + **tls_params, ) # DataJoint manages transactions explicitly via start_transaction() # Set autocommit=True to avoid implicit transactions @@ -136,6 +176,15 @@ def connect( return conn + def is_tls_negotiation_error(self, error: Exception) -> bool: + """ + Whether a connection attempt failed while negotiating TLS. + + Matches libpq's errors for a server without SSL support and for a failed + SSL handshake. Authentication errors do not match. + """ + return isinstance(error, client.OperationalError) and any(m in str(error) for m in _TLS_NEGOTIATION_MESSAGES) + def _register_numpy_adapters(self) -> None: """ Register psycopg2 adapters for numpy types. diff --git a/src/datajoint/connection.py b/src/datajoint/connection.py index 4e6252e0d..bd7c426e4 100644 --- a/src/datajoint/connection.py +++ b/src/datajoint/connection.py @@ -79,7 +79,9 @@ def conn( If True, reset existing connection. Default False. use_tls : bool or dict, optional TLS encryption option: True (required), False (no TLS), - None (preferred, default), or dict for manual configuration. + None (preferred, default), or dict for manual configuration + (TLS required; ``ca``, ``cert``, ``key``; with ``ca``, the server + certificate is verified). Returns ------- @@ -162,7 +164,10 @@ class Connection: port : int, optional Port number. Overridden if specified in host. use_tls : bool or dict, optional - TLS encryption option. + TLS encryption option: True (required), False (no TLS), + None (preferred, default), or dict for manual configuration + (TLS required; ``ca``, ``cert``, ``key``; with ``ca``, the server + certificate is verified). Attributes ---------- @@ -276,8 +281,10 @@ def connect(self) -> None: try: self._conn = self.adapter.connect(**self._build_connect_kwargs()) except Exception as ssl_error: - # If SSL fails, retry without SSL (if it was auto-detected) - if self.conn_info.get("ssl_input") is None: + # If SSL negotiation fails (server without SSL, or failed handshake), retry + # without SSL when it was auto-detected. Other errors, such as authentication + # failures, are not retried. + if self.conn_info.get("ssl_input") is None and self.adapter.is_tls_negotiation_error(ssl_error): logger.warning( "SSL connection failed (%s). Falling back to non-SSL connection. " "To require SSL, set use_tls=True explicitly.", diff --git a/tests/unit/test_tls.py b/tests/unit/test_tls.py new file mode 100644 index 000000000..09d648260 --- /dev/null +++ b/tests/unit/test_tls.py @@ -0,0 +1,380 @@ +""" +Unit tests for the ``use_tls`` connection option. + +The adapters' parameter mapping is checked with the driver's connect function +replaced. The handshake checks run the real drivers against a minimal local +server that answers the initial protocol exchange without offering TLS. +""" + +import socket +import ssl +import struct +import threading +from unittest import mock + +import pymysql +import pytest +from pymysql.constants import CLIENT, CR + +from datajoint.adapters import MySQLAdapter, PostgreSQLAdapter +from datajoint.adapters import mysql as mysql_adapter +from datajoint.connection import Connection + +CREDENTIALS = dict(host="localhost", port=3306, user="alice", password="secret") + + +# ============================================================================= +# Minimal servers for the initial protocol exchange +# ============================================================================= + + +class FakeServer: + """Accept connections on localhost and answer each with ``respond(sock, received)``.""" + + def __init__(self, respond): + self.respond = respond + self.received = [] # bytes received on each connection + self.listener = socket.create_server(("127.0.0.1", 0)) + self.listener.settimeout(0.05) + self.port = self.listener.getsockname()[1] + self.stopped = threading.Event() + self.thread = threading.Thread(target=self._serve, daemon=True) + self.thread.start() + + def _serve(self): + while not self.stopped.is_set(): + try: + sock, _ = self.listener.accept() + except socket.timeout: + continue + except OSError: + return + received = bytearray() + self.received.append(received) + with sock: + sock.settimeout(2) + try: + self.respond(sock, received) + while chunk := sock.recv(4096): + received.extend(chunk) + except OSError: + pass + + def close(self): + self.stopped.set() + self.thread.join(timeout=5) + self.listener.close() + + +def _mysql_packet(payload, seq): + return struct.pack("> 16) + + bytes([len(salt) + 1]) + + b"\x00" * 10 + + salt[8:] + + b"\x00" + + b"mysql_native_password\x00" + ) + return _mysql_packet(payload, 0) + + +MYSQL_CAPABILITIES = CLIENT.LONG_PASSWORD | CLIENT.PROTOCOL_41 | CLIENT.SECURE_CONNECTION | CLIENT.PLUGIN_AUTH + + +def _mysql_server_without_tls(sock, received): + """Greet without CLIENT_SSL; reject any authentication attempt.""" + sock.sendall(_mysql_greeting(MYSQL_CAPABILITIES)) + chunk = sock.recv(4096) + received.extend(chunk) + if chunk: + error = b"\xff" + struct.pack(" Date: Mon, 9 Nov 2026 13:32:00 -0600 Subject: [PATCH 23/37] Accept PostgreSQL JSON return types; reject non-finite numbers - The return types accepted after `:` in a JSON attribute key now include the PostgreSQL type names that worked before (integer, bigint, numeric(p,s), double precision, text, varchar(n), character varying(n), boolean, jsonb, timestamp[tz], with/without time zone, uuid, ...). Restrictions, projections and index declarations accept the same set. - NaN and infinite values in a mapping restriction raise DataJointError instead of rendering as bare `nan`/`inf`. - A malformed JSON key reports an invalid JSON path. - Pattern constants added to datajoint.condition are module-private. --- src/datajoint/condition.py | 24 +++-- tests/integration/test_restriction_values.py | 64 ++++++++++++-- tests/unit/test_condition.py | 93 ++++++++++++++++++-- 3 files changed, 156 insertions(+), 25 deletions(-) diff --git a/src/datajoint/condition.py b/src/datajoint/condition.py index 7f4c42560..47b2e9c60 100644 --- a/src/datajoint/condition.py +++ b/src/datajoint/condition.py @@ -31,17 +31,22 @@ JSON_PATTERN = re.compile(r"^(?P\w+)(\.(?P[\w.*\[\]]+))?(:(?P[\w(,\s)]+))?$") -# Return types accepted after ``:`` in a JSON attribute key, e.g. ``"attr.path:decimal(10,2)"`` -JSON_TYPE_PATTERN = re.compile( - r"\s*(?:(?:un)?signed(?:\s+integer)?|integer|int|bigint|smallint|float|double(?:\s+precision)?|real" - r"|decimal|numeric|date|time|datetime|timestamp|year|char|varchar|binary|text|jsonb?|bool(?:ean)?)" +# Return types accepted after ``:`` in a JSON attribute key, e.g. ``"attr.path:decimal(10,2)"``: +# type names understood by MySQL (``JSON_VALUE ... RETURNING``) or PostgreSQL (``::`` cast), +# with an optional length/precision, time zone qualifier, character set, and collation. +_JSON_TYPE_PATTERN = re.compile( + r"\s*(?:(?:un)?signed(?:\s+int(?:eger)?)?|int[248]?|integer|tinyint|smallint|mediumint|bigint" + r"|real|float[48]?|double(?:\s+precision)?|decimal|numeric|dec|bool(?:ean)?|bit" + r"|char(?:acter)?(?:\s+varying)?|varchar|nchar|text|binary|varbinary|bytea|jsonb?|uuid" + r"|date|datetime|year|time(?:tz)?|timestamp(?:tz)?|interval)" r"(?:\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\))?" + r"(?:\s+with(?:out)?\s+time\s+zone)?" r"(?:\s+(?:character\s+set|charset)\s+\w+)?(?:\s+collate\s+\w+)?\s*", re.IGNORECASE, ) -# Text of a numeric value that may appear unquoted in a condition -NUMERIC_LITERAL_PATTERN = re.compile(r"[+-]?(?:(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?|nan|inf)|true|false", re.IGNORECASE) +# Text of a finite numeric value that may appear unquoted in a condition +_NUMERIC_LITERAL_PATTERN = re.compile(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?|true|false", re.IGNORECASE) def translate_attribute(key: str, adapter=None) -> tuple[dict | None, str]: @@ -69,7 +74,7 @@ def translate_attribute(key: str, adapter=None) -> tuple[dict | None, str]: if match["path"] is None: return match, match["attr"] else: - if match["type"] is not None and not JSON_TYPE_PATTERN.fullmatch(match["type"]): + if match["type"] is not None and not _JSON_TYPE_PATTERN.fullmatch(match["type"]): raise DataJointError(f"Unsupported return type `{match['type']}` in JSON attribute `{key}`.") # Use adapter's json_path_expr if available, otherwise fall back to MySQL syntax if adapter is not None: @@ -359,7 +364,7 @@ def prep_value(k, v): key = k key_match, k = translate_attribute(k, adapter) if key_match is None: - raise DataJointError(f"Invalid attribute name `{key}` in restriction.") + raise DataJointError(f"Invalid JSON path `{key}` in restriction.") is_json_path = key_match.get("path") is not None if not is_json_path: @@ -394,8 +399,9 @@ def prep_value(k, v): return f"{k}={literal(v)}" if isinstance(v, (numbers.Number, numpy.number, numpy.bool_)): text = f"{v}" - if NUMERIC_LITERAL_PATTERN.fullmatch(text): + if _NUMERIC_LITERAL_PATTERN.fullmatch(text): return f"{k}={text}" + raise DataJointError(f"Cannot restrict by `{key}` with the non-finite or non-real value {text}.") raise DataJointError(f"Unsupported value of type {type(v).__name__} in restriction by `{key}`.") def combine_conditions(negate, conditions): diff --git a/tests/integration/test_restriction_values.py b/tests/integration/test_restriction_values.py index 19bf30f3d..bd9a8c86b 100644 --- a/tests/integration/test_restriction_values.py +++ b/tests/integration/test_restriction_values.py @@ -1,8 +1,8 @@ """ Mapping restrictions with values that need quoting, on both backends. -Values in dict restrictions are compared as literals: quotes, backslashes, ``%``, -and SQL fragments inside them select no extra rows. +Values in dict restrictions are compared as literals: quote characters, backslashes, +``%``, and SQL keywords inside a value are part of the value. """ import numpy as np @@ -17,7 +17,7 @@ dict(item_id=4, name='say "hi"', data={"label": 'say "hi"', "tags": [4], "sub": {"k": "x"}, "size": 6}), ] -HOSTILE = [ +SPECIAL_CHARACTER_VALUES = [ "' OR 1=1 --", "' OR '1'='1", "x' OR 'a'='a", @@ -51,8 +51,8 @@ def ids(query): return sorted(query.to_arrays("item_id").tolist()) -@pytest.mark.parametrize("value", HOSTILE) -def test_hostile_string_values_match_nothing(item, value): +@pytest.mark.parametrize("value", SPECIAL_CHARACTER_VALUES) +def test_values_with_quote_characters_match_nothing(item, value): assert ids(item & {"name": value}) == [] assert ids(item & {"data.label": value}) == [] assert ids(item & {"data.sub": {"k": value}}) == [] @@ -62,8 +62,8 @@ def test_hostile_string_values_match_nothing(item, value): assert len(item & {"name": value}) == 0 -@pytest.mark.parametrize("value", HOSTILE) -def test_hostile_values_do_not_delete(item, value): +@pytest.mark.parametrize("value", SPECIAL_CHARACTER_VALUES) +def test_values_with_quote_characters_delete_nothing(item, value): (item & {"name": value}).delete_quick() (item & {"data.label": value}).delete_quick() (item & {"name": [value]}).delete_quick() @@ -124,3 +124,53 @@ def test_string_with_backslash(item, backend): if backend == "mysql": assert ids(item & {"name": "back\\slash"}) == [5] assert ids(item & {"data.label": "back\\slash"}) == [5] + + +NUMERIC_JSON_TYPES = { + "mysql": ["unsigned", "signed", "decimal(4, 1)", "double", "float"], + "postgresql": ["integer", "int", "bigint", "numeric(10,2)", "double precision", "real", "unsigned", "double"], +} +TEXT_JSON_TYPES = { + "mysql": ["char(20)", "char(20) character set utf8mb4"], + "postgresql": ["text", "varchar(32)", "character varying(32)"], +} + + +def test_json_types_in_restriction_and_projection(item, backend): + for type_spec in NUMERIC_JSON_TYPES[backend]: + assert ids(item & {f"data.size:{type_spec}": 5}) == [3], type_spec + values = item.proj(size=f"data.size:{type_spec}").to_arrays("size", order_by="item_id") + assert [float(v) for v in values] == [3, 4, 5, 6], type_spec + for type_spec in TEXT_JSON_TYPES[backend]: + assert ids(item & {f"data.label:{type_spec}": "o'brien"}) == [2], type_spec + values = item.proj(label=f"data.label:{type_spec}").to_arrays("label", order_by="item_id") + assert list(values) == [row["data"]["label"] for row in ROWS], type_spec + + +def test_json_type_in_index_declaration(connection_by_backend, backend, prefix): + if backend == "postgresql": + pytest.skip("Indexes on JSON paths are not created on PostgreSQL (index name is derived from the expression)") + schema = dj.Schema(f"{prefix}_restriction_values_index_{backend}", connection=connection_by_backend) + numeric, text = NUMERIC_JSON_TYPES[backend][0], TEXT_JSON_TYPES[backend][0] + try: + + @schema + class Indexed(dj.Manual): + definition = f""" + item_id : int32 + --- + data = null : json + index(data.size:{numeric}) + index(data.label:{text}) + """ + + Indexed.insert(dict(item_id=r["item_id"], data=r["data"]) for r in ROWS) + assert sorted((Indexed & {f"data.size:{numeric}": 4}).to_arrays("item_id").tolist()) == [2] + finally: + schema.drop(prompt=False) + + +def test_non_finite_numbers_rejected(item): + for value in (float("nan"), float("inf"), np.float64("-inf")): + with pytest.raises(dj.DataJointError): + item & {"item_id": value} diff --git a/tests/unit/test_condition.py b/tests/unit/test_condition.py index ef168c3fc..9d26ecfb8 100644 --- a/tests/unit/test_condition.py +++ b/tests/unit/test_condition.py @@ -120,7 +120,7 @@ def test_invalid_offset_type_raises(self): ), ] -HOSTILE_STRINGS = [ +SPECIAL_CHARACTER_STRINGS = [ "' OR 1=1 --", "x' OR '1'='1", "\\' OR 1=1 -- ", @@ -135,6 +135,48 @@ def test_invalid_offset_type_raises(self): ] +# JSON return types accepted by previous releases on MySQL or PostgreSQL +VALID_JSON_TYPES = [ + # MySQL JSON_VALUE ... RETURNING + "unsigned", + "signed", + "UNSIGNED INTEGER", + "float", + "double", + "decimal(4, 1)", + "decimal(10,2)", + "char(20)", + "char(20) character set utf8mb4", + "DATETIME", + "datetime(6)", + "date", + "time", + "year", + "json", + # PostgreSQL casts + "integer", + "int", + "int4", + "bigint", + "smallint", + "numeric", + "numeric(10,2)", + "double precision", + "real", + "text", + "varchar(32)", + "character varying(32)", + "boolean", + "bool", + "jsonb", + "timestamp", + "timestamptz", + "timestamp with time zone", + "timestamp(3) without time zone", + "uuid", +] + + def _fake_expression(backend, names=("name", "car", "uid")): """Stand-in for a query expression: an adapter and a heading.""" attributes = {n: SimpleNamespace(uuid=(n == "uid")) for n in names} @@ -195,25 +237,25 @@ def _json_lhs(backend, path): class TestRestrictionLiterals: """Values in mapping restrictions are rendered as single, complete literals.""" - @pytest.mark.parametrize("value", HOSTILE_STRINGS) + @pytest.mark.parametrize("value", SPECIAL_CHARACTER_STRINGS) def test_string_value(self, backend, value): cond = _condition(backend, {"name": value}) expected = value if backend == "mysql" else value.replace("\\", "\\\\") assert _literal_value(backend, cond, _quoted(backend, "name")) == expected - @pytest.mark.parametrize("value", HOSTILE_STRINGS) + @pytest.mark.parametrize("value", SPECIAL_CHARACTER_STRINGS) def test_json_path_string_value(self, backend, value): cond = _condition(backend, {"car.name": value}) expected = value if backend == "mysql" else value.replace("\\", "\\\\") assert _literal_value(backend, cond, _json_lhs(backend, "name")) == expected - @pytest.mark.parametrize("value", HOSTILE_STRINGS) + @pytest.mark.parametrize("value", SPECIAL_CHARACTER_STRINGS) def test_list_value(self, backend, value): items = [value, 1, 'a"b', "c'd"] cond = _condition(backend, {"car.tags": items}) assert _literal_value(backend, cond, _json_lhs(backend, "tags")) == str(items) - @pytest.mark.parametrize("value", HOSTILE_STRINGS) + @pytest.mark.parametrize("value", SPECIAL_CHARACTER_STRINGS) def test_json_dict_value(self, backend, value): obj = {"side": value, value: True, "nested": {"k": [value]}} cond = _condition(backend, {"car.headlights[1]": obj}) @@ -252,19 +294,26 @@ def test_invalid_json_type_rejected(self, backend, type_spec): with pytest.raises(DataJointError): _condition(backend, {f"car.length:{type_spec}": 1}) - @pytest.mark.parametrize( - "type_spec", ["unsigned", "signed", "float", "double", "decimal(4, 1)", "decimal(10,2)", "char(20)", "DATETIME"] - ) + @pytest.mark.parametrize("type_spec", VALID_JSON_TYPES) def test_valid_json_type_accepted(self, backend, type_spec): cond = _condition(backend, {f"car.length:{type_spec}": 1}) assert cond.endswith("=1)") + @pytest.mark.parametrize("value", [float("nan"), float("inf"), -float("inf"), np.float64("nan"), np.float32("inf")]) + def test_non_finite_number_rejected(self, backend, value): + with pytest.raises(DataJointError, match="non-finite"): + _condition(backend, {"name": value}) + + def test_invalid_json_path_message(self, backend): + with pytest.raises(DataJointError, match="Invalid JSON path `car.na'me`"): + _condition(backend, {"car.na'me": 1}) + @pytest.mark.parametrize("value", [b"x' OR 1=1 --", object(), {"a": 1}, (1, 2), np.datetime64("2020-01-01"), 1 + 2j]) def test_unsupported_value_type_rejected(self, backend, value): with pytest.raises(DataJointError): _condition(backend, {"name": value}) - def test_negated_hostile_value(self, backend): + def test_negated_value_with_quote_characters(self, backend): from datajoint.condition import Not cond = make_condition(_fake_expression(backend), Not({"name": "' OR 1=1 --"}), set()) @@ -316,3 +365,29 @@ def test_json_path_expression_unchanged(backend): assert translate_attribute("car.headlights[0].side", adapter)[1] == ( "jsonb_extract_path_text(\"car\", 'headlights', '0', 'side')" ) + + +@pytest.mark.parametrize("backend", BACKENDS) +@pytest.mark.parametrize("type_spec", VALID_JSON_TYPES) +def test_json_type_in_projection_and_index(backend, type_spec): + """JSON return types accepted in restrictions are also accepted in projections and index declarations.""" + from datajoint.declare import compile_index + + adapter = get_adapter(backend) + expr = translate_attribute(f"car.length:{type_spec}", adapter)[1] + assert expr.startswith("json_value(" if backend == "mysql" else "(jsonb_extract_path_text(") + index_sql = [] + compile_index(f"index(car.length:{type_spec})", index_sql, adapter) + assert index_sql == [f"index (({expr}))"] + + +@pytest.mark.parametrize("backend", BACKENDS) +@pytest.mark.parametrize("type_spec", ["unsigned) OR (1", "nonsense"]) +def test_invalid_json_type_in_projection_and_index(backend, type_spec): + from datajoint.declare import compile_index + + adapter = get_adapter(backend) + with pytest.raises(DataJointError): + translate_attribute(f"car.length:{type_spec}", adapter) + with pytest.raises(DataJointError): + compile_index(f"index(car.length:{type_spec})", [], adapter) From ef113af3f6f7d017d7eaf822cdbf05a29ef0a896 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 9 Nov 2026 13:32:15 -0600 Subject: [PATCH 24/37] Accept in-store absolute file paths; confine ObjectRef paths and names accepts an absolute path that lies inside a file store's location again, as before the previous change: insert records it relative to the location, and existing rows holding such absolute paths stay readable. Absolute paths outside the location and paths with ".." components are still refused unless allow_filepath_outside_store is set, and the error message now names that setting. The reserved-section check for ignores case, so "_HASH/x" is refused like "_hash/x" on case-insensitive file systems. ObjectRef.full_path applies the same store confinement as file access. ObjectRef.download into a directory takes the local file name from the last path component, splitting on both "/" and "\", and refuses a name that is not a plain file name. fetch refuses stored names containing path separators, including backslashes, which are legal in POSIX file names; attachments with such names can no longer be fetched. The plain-file-name check is shared in datajoint.utils.is_plain_file_name. --- src/datajoint/builtin_codecs/attach.py | 15 +- src/datajoint/builtin_codecs/filepath.py | 22 ++- src/datajoint/objectref.py | 19 ++- src/datajoint/settings.py | 2 +- src/datajoint/storage.py | 51 +++++- src/datajoint/utils.py | 13 ++ tests/integration/test_path_confinement.py | 39 +++-- tests/unit/test_path_confinement.py | 173 ++++++++++++++------- 8 files changed, 243 insertions(+), 91 deletions(-) diff --git a/src/datajoint/builtin_codecs/attach.py b/src/datajoint/builtin_codecs/attach.py index 62ad25be5..5c6e9eb70 100644 --- a/src/datajoint/builtin_codecs/attach.py +++ b/src/datajoint/builtin_codecs/attach.py @@ -11,23 +11,18 @@ from ..codecs import Codec from ..errors import DataJointError +from ..utils import is_plain_file_name def _check_file_name(filename: str) -> None: """ Raise unless ``filename`` is a plain file name with no directory part. - ``encode`` stores only the base name of the attached file, so a stored name - with separators, ``..``, a NUL byte, or (on Windows) a drive or stream - marker ``:`` did not come from it. + ``encode`` stores only the base name of the attached file. A stored name + with path separators (``/`` or ``\\``), ``..``, a NUL byte, or (on Windows) + a drive or stream marker ``:`` is refused. """ - if ( - filename in ("", ".", "..") - or "/" in filename - or "\\" in filename - or "\x00" in filename - or (os.name == "nt" and ":" in filename) - ): + if not is_plain_file_name(filename): raise DataJointError(f" stored file name {filename!r} is not a plain file name.") diff --git a/src/datajoint/builtin_codecs/filepath.py b/src/datajoint/builtin_codecs/filepath.py index b41ed3bbf..abe14c0e6 100644 --- a/src/datajoint/builtin_codecs/filepath.py +++ b/src/datajoint/builtin_codecs/filepath.py @@ -60,10 +60,12 @@ class Recordings(dj.Manual): ``schema_prefix`` sections (defaults ``_hash/`` and ``_schema/``). Store Boundary: - Paths must stay inside the store location: absolute paths (for - ``file`` stores) and paths with ``..`` components are rejected on - insert and on access. Set ``dj.config.allow_filepath_outside_store`` - to accept references that point outside the store. + Paths must stay inside the store location: paths with ``..`` + components and, for ``file`` stores, absolute paths outside the + location are rejected on insert and on access. An absolute path + inside a ``file`` store's location is recorded relative to it. Set + ``dj.config.allow_filepath_outside_store`` to accept references that + point outside the store. Warning: The file must exist in the store at the specified path. @@ -114,6 +116,8 @@ def encode( import posixpath from datetime import datetime, timezone + from ..storage import path_in_location + config = self._codec_config(key, context) if config is None: from ..settings import config # type: ignore[assignment] @@ -125,9 +129,12 @@ def encode( # Use filepath_default if no store specified (filepath is not part of OAS) spec = config.get_store_spec(store_name, use_filepath_default=True) - # Reject paths outside the store before any prefix checks + # Reject paths outside the store before any prefix checks. An absolute + # path inside a file store's location is recorded relative to it. backend = self._get_backend(store_name, config) backend._full_path(path) + if spec.get("protocol") == "file": + path = path_in_location(spec["location"], path) or path # Validate path doesn't use reserved sections (hash and schema). # Normalize first so that "./_hash/x" or "//_hash/x" are caught too. @@ -142,10 +149,11 @@ def encode( if schema_prefix: reserved_prefixes.append(("schema_prefix", schema_prefix)) - # Check if path starts with any reserved prefix + # Check if path starts with any reserved prefix. Compare without case: + # on case-insensitive file systems "_HASH/x" is the same as "_hash/x". for prefix_name, prefix_value in reserved_prefixes: prefix_normalized = prefix_value.strip("/") + "/" - if (path_normalized + "/").startswith(prefix_normalized): + if (path_normalized + "/").casefold().startswith(prefix_normalized.casefold()): raise ValueError( f" cannot use reserved section '{prefix_value}' ({prefix_name}). " f"This section is managed by DataJoint. " diff --git a/src/datajoint/objectref.py b/src/datajoint/objectref.py index c312e0c5d..670f45307 100644 --- a/src/datajoint/objectref.py +++ b/src/datajoint/objectref.py @@ -7,6 +7,7 @@ """ import json +import re from dataclasses import dataclass from datetime import datetime from pathlib import Path @@ -17,6 +18,7 @@ from .errors import DataJointError from .hash_registry import compute_hash from .storage import StorageBackend +from .utils import is_plain_file_name class IntegrityError(DataJointError): @@ -169,8 +171,15 @@ def full_path(self) -> str: Return full URI (e.g., 's3://bucket/path'). This is the complete path including protocol and bucket/location. + + Raises + ------ + DataJointError + If the stored path leads outside the store location. """ self._ensure_backend() + if getattr(self._backend, "confine_paths", False): + self._backend._check_confined(self.path) protocol = self._backend.protocol if protocol == "file": return str(Path(self._backend.spec.get("location", "")) / self.path) @@ -285,6 +294,12 @@ def download(self, destination: Path | str, subpath: str | None = None) -> Path: ------- Path Path to downloaded file/directory. + + Raises + ------ + DataJointError + If ``destination`` is a directory and the last component of the + stored path is not a plain file name. """ self._ensure_backend() destination = Path(destination) @@ -304,7 +319,9 @@ def download(self, destination: Path | str, subpath: str | None = None) -> Path: else: # Download single file if destination.is_dir(): - filename = remote_path.split("/")[-1] + filename = re.split(r"[\\/]", remote_path)[-1] + if not is_plain_file_name(filename): + raise DataJointError(f"Cannot download {remote_path!r}: {filename!r} is not a plain file name.") destination = destination / filename destination.parent.mkdir(parents=True, exist_ok=True) self._backend.get_file(remote_path, destination) diff --git a/src/datajoint/settings.py b/src/datajoint/settings.py index abaa046aa..0b8c1dd21 100644 --- a/src/datajoint/settings.py +++ b/src/datajoint/settings.py @@ -447,7 +447,7 @@ class Config(BaseSettings): allow_filepath_outside_store: bool = Field( default=False, description="If True, values may point outside the store location " - "(absolute paths on file stores, or paths with '..' components). " + "(absolute paths outside a file store's location, or paths with '..' components). " "By default such paths are rejected on insert and on access. Enable only for " "trusted data whose references deliberately point elsewhere, such as rows " "migrated from DataJoint 0.14. Set via DJ_ALLOW_FILEPATH_OUTSIDE_STORE.", diff --git a/src/datajoint/storage.py b/src/datajoint/storage.py index 5834c962c..bf83b8d9d 100644 --- a/src/datajoint/storage.py +++ b/src/datajoint/storage.py @@ -9,6 +9,7 @@ import json import logging +import os import re import secrets import urllib.parse @@ -56,6 +57,35 @@ def _has_parent_reference(path: str) -> bool: return ".." in re.split(r"[\\/]", path) +def path_in_location(location: str, path: str) -> str | None: + """ + Express an absolute local path inside ``location`` relative to it. + + The comparison is lexical: symbolic links are not resolved. + + Parameters + ---------- + location : str + Local directory (a ``file`` store's location). + path : str + Path to express relative to ``location``. + + Returns + ------- + str or None + The path relative to ``location`` with POSIX separators, or None if + ``path`` is not absolute, has ``..`` components, or lies outside + ``location``. + """ + if not Path(path).anchor or _has_parent_reference(path): + return None + root = Path(os.path.abspath(location or ".")) + try: + return Path(os.path.abspath(path)).relative_to(root).as_posix() + except ValueError: + return None + + def _path_to_file_url(resolved_path: Path | PurePosixPath) -> str: """ Convert an already-resolved absolute path to a ``file://`` URL. @@ -322,8 +352,8 @@ class StorageBackend: Storage protocol (``'file'``, ``'s3'``, ``'gcs'``, ``'azure'``). confine_paths : bool If True (default), paths passed to the backend must stay inside the - store location: absolute paths (for ``file`` stores) and paths with - ``..`` components are rejected. + store location: paths with ``..`` components and, for ``file`` stores, + absolute paths outside the location are rejected. """ confine_paths: bool = True @@ -478,12 +508,23 @@ def _full_path(self, path: str | PurePosixPath) -> str: def _check_confined(self, path: str) -> None: """Raise if ``path`` does not stay inside the store location.""" - if "\x00" in path or _has_parent_reference(path) or (self.protocol == "file" and Path(path).anchor): + if ( + "\x00" in path + or _has_parent_reference(path) + or (self.protocol == "file" and Path(path).anchor and self._path_in_location(path) is None) + ): raise errors.DataJointError( - f"Path {path!r} may lead outside the store location: " - "store paths must be relative and have no '..' components." + f"Path {path!r} may lead outside the store location. Use a path relative to the " + "store location, without '..' components. For references that " + "deliberately point outside the store, set dj.config.allow_filepath_outside_store = True." ) + def _path_in_location(self, path: str) -> str | None: + """Express an absolute path inside a ``file`` store's location relative to it (see :func:`path_in_location`).""" + if self.protocol != "file": + return None + return path_in_location(self.spec.get("location", ""), path) + def get_url(self, path: str | PurePosixPath) -> str: """ Get the full URL for a path in storage. diff --git a/src/datajoint/utils.py b/src/datajoint/utils.py index e36267936..ad20a6b74 100644 --- a/src/datajoint/utils.py +++ b/src/datajoint/utils.py @@ -1,5 +1,6 @@ """General-purpose utilities""" +import os import re import shutil import warnings @@ -8,6 +9,18 @@ from .errors import DataJointError +def is_plain_file_name(name: str) -> bool: + """ + Check that ``name`` is a plain file name with no directory part. + + Rejects empty names, ``.`` and ``..``, the separators ``/`` and ``\\`` (on + every platform), NUL bytes, and on Windows any ``:`` (drives and alternate + data streams). A name that passes always names an entry directly inside + the directory it is joined to. + """ + return not (name in ("", ".", "..") or "/" in name or "\\" in name or "\x00" in name or (os.name == "nt" and ":" in name)) + + def user_choice(prompt, choices=("yes", "no"), default=None): """ Prompt the user for confirmation. diff --git a/tests/integration/test_path_confinement.py b/tests/integration/test_path_confinement.py index 52db92897..1eaf240e5 100644 --- a/tests/integration/test_path_confinement.py +++ b/tests/integration/test_path_confinement.py @@ -52,9 +52,9 @@ def schema_paths(connection_test, mock_stores, prefix): @pytest.fixture def outside(tmp_path): """A file outside every store and download path.""" - path = tmp_path / "outside" / "secret.txt" + path = tmp_path / "outside" / "outside.txt" path.parent.mkdir() - path.write_bytes(b"secret") + path.write_bytes(b"outside") return path @@ -77,8 +77,12 @@ def _json(table, attr, **key): return json.loads(raw) if isinstance(raw, (str, bytes)) else dict(raw) -@pytest.mark.parametrize("name", ["../escaped.txt", "../../escaped.txt", "sub/escaped.txt", "/tmp/escaped-dj.txt"]) -def test_attach_fetch_refuses_name_with_directory(schema_paths, tmp_path, name): +@pytest.mark.parametrize( + "name", + ["../outside.txt", "../../outside.txt", "sub/outside.txt", "/outside-of-download-path.txt"], + ids=["parent_ref", "parent_ref_twice", "subdir", "absolute"], +) +def test_attach_fetch_refuses_stored_name_with_directory(schema_paths, tmp_path, name): source = tmp_path / "report.txt" source.write_bytes(b"report") Document.insert1(dict(doc_id=1, inline_file=source, stored_file=source)) @@ -88,8 +92,8 @@ def test_attach_fetch_refuses_name_with_directory(schema_paths, tmp_path, name): with dj.config.override(download_path=str(download)): with pytest.raises(dj.DataJointError, match="not a plain file name"): (Document & "doc_id=1").fetch1("inline_file") - assert not (tmp_path / "a" / "b" / "escaped.txt").exists() - assert not (tmp_path / "a" / "escaped.txt").exists() + assert not (tmp_path / "a" / "b" / "outside.txt").exists() + assert not (tmp_path / "a" / "outside.txt").exists() assert not (download / "sub").exists() @@ -125,8 +129,8 @@ def test_filepath_insert_refuses_path_outside_store(schema_paths, outside): assert len(Reference()) == 0 -@pytest.mark.parametrize("hostile", ["absolute", "relative", "device"]) -def test_filepath_fetch_refuses_path_outside_store(schema_paths, outside, hostile): +@pytest.mark.parametrize("kind", ["absolute", "parent_ref"]) +def test_filepath_fetch_refuses_path_outside_store(schema_paths, outside, kind): repo = Path(dj.config.stores["repo"]["location"]) (repo / "inside.txt").write_bytes(b"inside") Reference.insert1(dict(ref_id=1, file_ref="inside.txt")) @@ -135,19 +139,30 @@ def test_filepath_fetch_refuses_path_outside_store(schema_paths, outside, hostil meta = _json(Reference, "file_ref", ref_id=1) meta["path"] = { "absolute": str(outside), - "relative": "../" * len(repo.parts) + str(outside).lstrip("/"), - "device": "/dev/zero", - }[hostile] + "parent_ref": "../" * len(repo.parts) + str(outside).lstrip("/"), + }[kind] _overwrite(Reference, "file_ref", json.dumps(meta), ref_id=1) ref = (Reference & "ref_id=1").fetch1("file_ref") with pytest.raises(dj.DataJointError, match="outside the store location"): ref.read() +def test_filepath_absolute_path_inside_store(schema_paths): + repo = Path(dj.config.stores["repo"]["location"]) + (repo / "inside.txt").write_bytes(b"inside") + Reference.insert1(dict(ref_id=1, file_ref=str(repo / "inside.txt"))) + assert _json(Reference, "file_ref", ref_id=1)["path"] == "inside.txt" + # Rows written before paths were recorded relative to the store stay readable + meta = _json(Reference, "file_ref", ref_id=1) + meta["path"] = str(repo / "inside.txt") + _overwrite(Reference, "file_ref", json.dumps(meta), ref_id=1) + assert (Reference & "ref_id=1").fetch1("file_ref").read() == b"inside" + + def test_filepath_outside_store_when_allowed(schema_paths, outside): with dj.config.override(allow_filepath_outside_store=True): Reference.insert1(dict(ref_id=1, file_ref=str(outside))) - assert (Reference & "ref_id=1").fetch1("file_ref").read() == b"secret" + assert (Reference & "ref_id=1").fetch1("file_ref").read() == b"outside" with pytest.raises(dj.DataJointError, match="outside the store location"): (Reference & "ref_id=1").fetch1("file_ref").read() diff --git a/tests/unit/test_path_confinement.py b/tests/unit/test_path_confinement.py index f65c47865..dbf252af1 100644 --- a/tests/unit/test_path_confinement.py +++ b/tests/unit/test_path_confinement.py @@ -6,6 +6,8 @@ ````, ````, and hash-addressed storage must stay inside the store location. ``allow_filepath_outside_store`` lifts the store check for ```` only. + +No test reads a device or opens a pipe: a regression must fail, not hang. """ import importlib @@ -14,7 +16,7 @@ import pytest -posix_only = pytest.mark.skipif(sys.platform == "win32", reason="needs POSIX symlinks, devices, or pipes") +posix_only = pytest.mark.skipif(sys.platform == "win32", reason="needs POSIX paths and symlinks") @pytest.fixture(autouse=True) @@ -26,10 +28,11 @@ def _live_modules(): names bound at collection time would then refer to stale classes, and ``pytest.raises(DataJointError)`` would miss the error actually raised. """ - global AttachCodec, FilepathCodec, ObjectCodec, DataJointError, Config, StorageBackend + global AttachCodec, FilepathCodec, ObjectCodec, ObjectRef, DataJointError, Config, StorageBackend AttachCodec = importlib.import_module("datajoint.builtin_codecs.attach").AttachCodec FilepathCodec = importlib.import_module("datajoint.builtin_codecs.filepath").FilepathCodec ObjectCodec = importlib.import_module("datajoint.builtin_codecs.object").ObjectCodec + ObjectRef = importlib.import_module("datajoint.objectref").ObjectRef DataJointError = importlib.import_module("datajoint.errors").DataJointError Config = importlib.import_module("datajoint.settings").Config StorageBackend = importlib.import_module("datajoint.storage").StorageBackend @@ -37,14 +40,14 @@ def _live_modules(): @pytest.fixture def layout(tmp_path): - """A file store, a sibling directory sharing its name as a prefix, and a download path.""" + """A file store, a sibling directory whose name extends the store's, a file outside both, and a download path.""" store = tmp_path / "store" store.mkdir() (store / "data").mkdir() (store / "data" / "inside.txt").write_text("inside") - sibling = tmp_path / "store-evil" - sibling.mkdir() - (sibling / "secret.txt").write_text("secret") + sibling_prefix = tmp_path / "store-sibling" + sibling_prefix.mkdir() + (sibling_prefix / "sibling.txt").write_text("sibling") (tmp_path / "outside.txt").write_text("outside") downloads = tmp_path / "downloads" return tmp_path, store, downloads @@ -60,38 +63,54 @@ def cfg(layout): return config -HOSTILE_RELATIVE = [ +PATHS_WITH_PARENT_REF = [ "../outside.txt", "data/../../outside.txt", - "../store-evil/secret.txt", + "../store-sibling/sibling.txt", "..\\outside.txt", "data/..\\..\\outside.txt", - "data/x\x00y", "data/sub/../inside.txt", "data/..", ] +def _outside_paths(root, store): + """Absolute paths outside the store: a plain outside file and a sibling directory sharing the store's name prefix.""" + return [str(root / "outside.txt"), str(root / "store-sibling" / "sibling.txt"), str(store) + "-sibling/sibling.txt"] + + # --------------------------------------------------------------------------- # # StorageBackend._full_path # --------------------------------------------------------------------------- # class TestStorePathConfinement: - @pytest.mark.parametrize("path", HOSTILE_RELATIVE) - def test_file_store_rejects_relative_escape(self, layout, path): + @pytest.mark.parametrize("path", PATHS_WITH_PARENT_REF + ["data/x\x00y"]) + def test_file_store_rejects_parent_ref_and_nul(self, layout, path): _, store, _ = layout backend = StorageBackend({"protocol": "file", "location": str(store)}) with pytest.raises(DataJointError, match="outside the store location"): backend._full_path(path) - def test_file_store_rejects_absolute_paths(self, layout): + @posix_only + def test_file_store_rejects_absolute_paths_outside_location(self, layout): root, store, _ = layout backend = StorageBackend({"protocol": "file", "location": str(store)}) - for path in (str(root / "outside.txt"), str(store / "data" / "inside.txt"), "/dev/zero"): - with pytest.raises(DataJointError, match="outside the store location"): + for path in _outside_paths(root, store) + [str(store / "data" / ".." / ".." / "outside.txt")]: + with pytest.raises(DataJointError, match="allow_filepath_outside_store"): backend._full_path(path) + @posix_only + def test_file_store_accepts_absolute_paths_inside_location(self, layout): + _, store, _ = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + inside = str(store / "data" / "inside.txt") + assert backend._full_path(inside) == inside + assert backend._full_path(str(store) + "/./data//inside.txt") + assert backend.get_buffer(inside) == b"inside" + assert backend._path_in_location(inside) == "data/inside.txt" + assert backend._path_in_location(str(store) + "-sibling/sibling.txt") is None + @pytest.mark.parametrize("path", ["data/inside.txt", "./data/inside.txt", "data//inside.txt", ""]) - def test_file_store_accepts_paths_inside(self, layout, path): + def test_file_store_accepts_relative_paths_inside(self, layout, path): _, store, _ = layout backend = StorageBackend({"protocol": "file", "location": str(store)}) assert backend._full_path(path) == (store / path).as_posix() @@ -100,7 +119,7 @@ def test_io_never_reaches_outside(self, layout): root, store, _ = layout backend = StorageBackend({"protocol": "file", "location": str(store)}) with pytest.raises(DataJointError): - backend.get_buffer("/dev/zero") + backend.get_buffer(str(root / "outside.txt")) with pytest.raises(DataJointError): backend.get_buffer("../outside.txt") with pytest.raises(DataJointError): @@ -135,18 +154,45 @@ def test_confinement_can_be_lifted_per_backend(self, layout): # # --------------------------------------------------------------------------- # class TestFilepathConfinement: - @pytest.mark.parametrize("path", HOSTILE_RELATIVE[:3]) - def test_encode_rejects_relative_escape(self, cfg, path): + @pytest.mark.parametrize("path", PATHS_WITH_PARENT_REF[:3]) + def test_encode_rejects_parent_ref(self, cfg, path): with pytest.raises(DataJointError, match="outside the store location"): FilepathCodec().encode(path, store_name="local", context={"config": cfg}) - def test_encode_rejects_absolute_paths(self, cfg, layout): + @posix_only + def test_encode_rejects_absolute_paths_outside_store(self, cfg, layout): root, store, _ = layout - for path in (str(root / "outside.txt"), str(store / "data" / "inside.txt"), "/dev/zero"): + for path in _outside_paths(root, store): with pytest.raises(DataJointError, match="outside the store location"): FilepathCodec().encode(path, store_name="local", context={"config": cfg}) - @pytest.mark.parametrize("path", ["./_hash/x.bin", "././_schema/x", ".//_hash/x", "_hash"]) + @posix_only + def test_encode_records_absolute_path_inside_store_as_relative(self, cfg, layout): + _, store, _ = layout + codec = FilepathCodec() + meta = codec.encode(str(store / "data" / "inside.txt"), store_name="local", context={"config": cfg}) + assert meta["path"] == "data/inside.txt" + assert codec.decode(meta, context={"config": cfg}).read() == b"inside" + + @posix_only + def test_decode_of_existing_absolute_path_inside_store(self, cfg, layout): + _, store, _ = layout + stored = {"path": str(store / "data" / "inside.txt"), "store": "local", "size": 6} + ref = FilepathCodec().decode(stored, context={"config": cfg}) + assert ref.read() == b"inside" + assert ref.full_path == stored["path"] + + @posix_only + def test_encode_absolute_path_into_reserved_section(self, cfg, layout): + _, store, _ = layout + (store / "_hash").mkdir() + (store / "_hash" / "x.bin").write_bytes(b"x") + with pytest.raises(ValueError, match="reserved section"): + FilepathCodec().encode(str(store / "_hash" / "x.bin"), store_name="local", context={"config": cfg}) + + @pytest.mark.parametrize( + "path", ["./_hash/x.bin", "././_schema/x", ".//_hash/x", "_hash", "_HASH/x.bin", "_Schema/x", "./_Hash"] + ) def test_encode_reserved_sections_after_normalizing(self, cfg, path): with pytest.raises(ValueError, match="reserved section"): FilepathCodec().encode(path, store_name="local", context={"config": cfg}) @@ -168,18 +214,19 @@ def test_round_trip_inside_store(self, cfg): meta = codec.encode("data/inside.txt", store_name="local", context={"config": cfg}) assert codec.decode(meta, context={"config": cfg}).read() == b"inside" - @pytest.mark.parametrize("kind", ["absolute", "relative", "sibling", "device"]) - def test_decode_of_hostile_row_does_not_read_outside(self, cfg, layout, kind): - root, _, _ = layout + @pytest.mark.parametrize("kind", ["absolute", "parent_ref", "sibling_prefix"]) + def test_decode_of_row_outside_store_does_not_reach_it(self, cfg, layout, kind): + root, store, _ = layout path = { "absolute": str(root / "outside.txt"), - "relative": "../outside.txt", - "sibling": "../store-evil/secret.txt", - "device": "/dev/zero", + "parent_ref": "../outside.txt", + "sibling_prefix": str(store) + "-sibling/sibling.txt", }[kind] ref = FilepathCodec().decode({"path": path, "store": "local", "size": None}, context={"config": cfg}) with pytest.raises(DataJointError, match="outside the store location"): ref.read() + with pytest.raises(DataJointError, match="outside the store location"): + ref.full_path with pytest.raises(DataJointError, match="outside the store location"): ref.download(root / "dl") @@ -201,10 +248,10 @@ def test_escape_hatch_does_not_apply_to_object(self, cfg, layout): # --------------------------------------------------------------------------- # -# +# and ObjectRef # --------------------------------------------------------------------------- # class TestObjectConfinement: - @pytest.mark.parametrize("path", ["../outside.txt", "/dev/zero", "_schema/../../outside.txt"]) + @pytest.mark.parametrize("path", ["../outside.txt", "/outside.txt", "_schema/../../outside.txt"]) def test_encode_rejects_precomputed_metadata_outside_store(self, cfg, path): with pytest.raises(DataJointError, match="outside the store location"): ObjectCodec().encode({"path": path, "store": "local", "size": 1}, context={"config": cfg}) @@ -213,11 +260,35 @@ def test_encode_passes_precomputed_metadata_inside_store(self, cfg): meta = {"path": "_schema/s/t/k/f_tok", "store": "local", "size": 1} assert ObjectCodec().encode(meta, context={"config": cfg}) is meta - def test_decode_of_hostile_row_does_not_read_outside(self, cfg, layout): + def test_decode_of_row_outside_store_does_not_reach_it(self, cfg, layout): root, _, _ = layout ref = ObjectCodec().decode({"path": str(root / "outside.txt"), "store": "local", "size": 7}, context={"config": cfg}) with pytest.raises(DataJointError, match="outside the store location"): ref.read() + with pytest.raises(DataJointError, match="outside the store location"): + ref.full_path + + @pytest.mark.parametrize( + "subpath", + ["sub/C:\\x\\y.dll", "sub/\\\\server\\share\\y.dll", "sub\\..", "sub/x:y"], + ids=["drive", "unc", "parent_ref", "colon"], + ) + def test_download_into_directory_uses_last_component_only(self, cfg, layout, subpath): + """The local file name is the last component, split on both separators, and must be plain.""" + _, store, downloads = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + backend.confine_paths = False # isolate the local-name check + downloads.mkdir() + ref = ObjectRef(path="data", size=None, hash=None, ext=None, is_dir=True, timestamp=None, _backend=backend) + name = subpath.replace("\\", "/").split("/")[-1] + if name in ("", ".", "..") or (os.name == "nt" and ":" in name): + with pytest.raises(DataJointError, match="not a plain file name"): + ref.download(downloads, subpath=subpath) + else: + # Missing source file: the error comes from the store, after the name was accepted + with pytest.raises(FileNotFoundError): + ref.download(downloads, subpath=subpath) + assert not any(downloads.iterdir()) # --------------------------------------------------------------------------- # @@ -230,16 +301,18 @@ def _attach_blob(name: str, contents: bytes) -> bytes: class TestAttachConfinement: @pytest.mark.parametrize( "name", - ["../evil.txt", "../../evil.txt", "sub/evil.txt", "..\\evil.txt", "..", ".", "", "/evil.txt"], + ["../outside.txt", "../../outside.txt", "sub/outside.txt", "..\\outside.txt", "back\\slash.txt", "..", ".", ""], + ids=["parent_ref", "parent_ref_twice", "subdir", "backslash_parent_ref", "backslash", "dotdot", "dot", "empty"], ) - def test_decode_rejects_names_that_are_not_plain(self, cfg, layout, name): + def test_decode_rejects_stored_name_that_is_not_plain(self, cfg, layout, name): root, _, downloads = layout + (root / "outside.txt").unlink() with pytest.raises(DataJointError, match="not a plain file name"): AttachCodec().decode(_attach_blob(name, b"payload"), context={"config": cfg}) - assert not (root / "evil.txt").exists() + assert not (root / "outside.txt").exists() assert not (downloads / "sub").exists() - def test_decode_rejects_absolute_name(self, cfg, layout): + def test_decode_rejects_absolute_stored_name(self, cfg, layout): root, _, _ = layout target = root / "absolute.txt" with pytest.raises(DataJointError, match="not a plain file name"): @@ -262,34 +335,24 @@ def test_round_trip(self, cfg, layout, tmp_path): assert (downloads / "notes.txt").read_bytes() == b"hello" assert (downloads / "notes_1.txt").read_bytes() == b"changed" - @posix_only - def test_decode_does_not_read_device_behind_link(self, cfg, layout): + def test_decode_skips_directory_with_the_same_name(self, cfg, layout): + """A non-regular file in the way is never opened; the next free name is used.""" _, _, downloads = layout - downloads.mkdir() - (downloads / "zero").symlink_to("/dev/zero") - result = AttachCodec().decode(_attach_blob("zero", b"payload"), context={"config": cfg}) - assert result == str(downloads / "zero_1") - assert os.readlink(downloads / "zero") == "/dev/zero" - - @posix_only - def test_decode_does_not_open_pipe(self, cfg, layout): - _, _, downloads = layout - downloads.mkdir() - os.mkfifo(downloads / "pipe") - result = AttachCodec().decode(_attach_blob("pipe", b"payload"), context={"config": cfg}) - assert result == str(downloads / "pipe_1") + (downloads / "notes.txt").mkdir(parents=True) + result = AttachCodec().decode(_attach_blob("notes.txt", b"payload"), context={"config": cfg}) + assert result == str(downloads / "notes_1.txt") @posix_only - def test_decode_does_not_write_through_link(self, cfg, layout): + def test_decode_does_not_reuse_or_write_through_link(self, cfg, layout): root, _, downloads = layout downloads.mkdir() - (downloads / "outside.txt").symlink_to(root / "outside.txt") - result = AttachCodec().decode(_attach_blob("outside.txt", b"overwritten"), context={"config": cfg}) - assert result == str(downloads / "outside_1.txt") + (downloads / "linked.txt").symlink_to(root / "outside.txt") + result = AttachCodec().decode(_attach_blob("linked.txt", b"changed"), context={"config": cfg}) + assert result == str(downloads / "linked_1.txt") assert (root / "outside.txt").read_text() == "outside" # A link is not reused even when its target holds the same content - result = AttachCodec().decode(_attach_blob("outside.txt", b"outside"), context={"config": cfg}) - assert result == str(downloads / "outside_2.txt") + result = AttachCodec().decode(_attach_blob("linked.txt", b"outside"), context={"config": cfg}) + assert result == str(downloads / "linked_2.txt") @posix_only def test_decode_does_not_follow_dangling_link(self, cfg, layout): From 631b8c347d382a808a0d56853b093acd687aa1e0 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 9 Nov 2026 13:33:04 -0600 Subject: [PATCH 25/37] fix(config): check the opened file and allow group directories under sticky roots Files found by the config search are now opened first and checked through the open descriptor (os.fstat), then read from it, so the file that is checked is the file that is read. The final path component is opened without following symbolic links, and a link owned by another user is judged by the directory it was found in. Secret files are read the same way. The directory rule now matches how shared directories are set up: another user's file is skipped when the directory it is in is world-writable (such as /tmp), or when a directory above it is world-writable without the sticky bit. A group directory under a sticky world-writable root such as /scratch is used. A skipped config file now produces one warning naming the file, DJ_CONFIG_FILE and dj.config.load(), without the "No datajoint.json found" warning. DJ_CONFIG_FILE naming a missing file raises FileNotFoundError. fix(npy): clear the mmap cache directory when restricting its permissions A per-user cache directory that other users had access to is reset to 0700 and emptied, so files written while it was open are not reused. Tests requiring POSIX ownership are skipped on Windows. --- src/datajoint/builtin_codecs/npy.py | 33 +++- src/datajoint/settings.py | 271 +++++++++++++++++++--------- tests/unit/test_npy_cache.py | 18 +- tests/unit/test_settings.py | 224 ++++++++++++++--------- 4 files changed, 373 insertions(+), 173 deletions(-) diff --git a/src/datajoint/builtin_codecs/npy.py b/src/datajoint/builtin_codecs/npy.py index a5be03773..df9d00b85 100644 --- a/src/datajoint/builtin_codecs/npy.py +++ b/src/datajoint/builtin_codecs/npy.py @@ -6,6 +6,7 @@ import logging import os +import shutil import stat import tempfile from pathlib import Path @@ -26,9 +27,10 @@ def _mmap_cache_dir() -> Path: On POSIX systems the directory is ``/datajoint_mmap_``, created with mode 0700. An existing directory is used only if it is a directory (not - a symbolic link) owned by the current user; its permissions are reset to 0700 - if other users have access. If the path exists but cannot be used, a new - private directory is created for this process instead. + a symbolic link) owned by the current user. If other users have access to + it, its permissions are reset to 0700 and its contents are removed, since + they may not have been written by the current user. If the path exists but + cannot be used, a new private directory is created for this process instead. Where ``os.getuid`` is unavailable (Windows), the temporary directory is already per-user and ``/datajoint_mmap`` is used. @@ -58,15 +60,25 @@ def _mmap_cache_dir() -> Path: st = os.lstat(cache_dir) if stat.S_ISDIR(st.st_mode) and st.st_uid == uid: - if stat.S_IMODE(st.st_mode) & 0o077: + if not stat.S_IMODE(st.st_mode) & 0o077: + return cache_dir + try: os.chmod(cache_dir, 0o700) - return cache_dir + for entry in os.scandir(cache_dir): + if entry.is_dir(follow_symlinks=False): + shutil.rmtree(entry.path) + else: + os.unlink(entry.path) + except OSError as e: + reason = f"its contents could not be removed after other users had access to it ({e})" + else: + logger.info(f"Cleared {cache_dir} and restricted it to the current user.") + return cache_dir + else: + reason = "it is not a directory owned by the current user" _fallback_mmap_cache_dir = Path(tempfile.mkdtemp(prefix="datajoint_mmap_")) - logger.warning( - f"Not using {cache_dir} to cache arrays: it is not a directory owned by the current user. " - f"Using {_fallback_mmap_cache_dir} for this session." - ) + logger.warning(f"Not using {cache_dir} to cache arrays: {reason}. Using {_fallback_mmap_cache_dir} for this session.") return _fallback_mmap_cache_dir @@ -195,7 +207,8 @@ def load(self, mmap_mode=None): For local filesystem stores, memory mapping accesses the file directly with no download. For remote stores (S3, etc.), the file is downloaded - to a local cache (``{tempdir}/datajoint_mmap/``) before memory mapping. + to a per-user local cache (``{tempdir}/datajoint_mmap_{uid}/``, or + ``{tempdir}/datajoint_mmap/`` on Windows) before memory mapping. Examples -------- diff --git a/src/datajoint/settings.py b/src/datajoint/settings.py index d04ca682b..c6ccd65fe 100644 --- a/src/datajoint/settings.py +++ b/src/datajoint/settings.py @@ -16,12 +16,14 @@ ``datajoint.json`` takes precedence over ``.secrets/``: the secrets directory only supplies values the config file and environment leave unset. -The search for ``datajoint.json`` and ``.secrets/`` skips, with a warning, any -file or directory owned by another user that sits under a world-writable -directory such as ``/tmp``, since anyone on the machine could have placed it -there. To use such a file, name it explicitly: ``dj.config.load(path)`` or the -``DJ_CONFIG_FILE`` environment variable. ``DJ_IGNORE_CONFIG_FILE=true`` turns -the search off. +The search for ``datajoint.json`` and ``.secrets/`` skips, with a warning, a +file or directory owned by another user (other than root) that anyone on the +machine could have placed there: one in a world-writable directory such as +``/tmp``, or below a world-writable directory that lacks the sticky bit. Files +in a shared project directory (e.g. a group directory under a sticky +``/scratch``) are still used. To use a skipped file, name it explicitly: +``dj.config.load(path)`` or the ``DJ_CONFIG_FILE`` environment variable. +``DJ_IGNORE_CONFIG_FILE=true`` turns the search off. Examples -------- @@ -59,7 +61,7 @@ from contextlib import contextmanager from enum import Enum from pathlib import Path -from typing import Any, Iterator, Literal +from typing import Any, Iterable, Iterator, Literal from pydantic import Field, SecretStr, field_validator, model_validator from pydantic_settings import BaseSettings, SettingsConfigDict @@ -103,106 +105,200 @@ _SECRETS_HINT = " Supply its values through environment variables instead." +_CONFIG_HINT = " To use it, pass its path to dj.config.load() or set " + CONFIG_FILE_ENV_VAR + "." -def _is_world_writable(mode: int) -> bool: - return bool(mode & stat.S_IWOTH) +def _is_foreign(uid: int) -> bool: + """True if ``uid`` is neither the current user nor root.""" + return uid not in (os.getuid(), 0) -def _check_discovered_path(path: Path, hint: str = "") -> bool: +def _open_location(directory: Path) -> Path | None: """ - Decide whether a config file or secrets path found by searching may be used. + Find a directory that lets any user create or replace entries in ``directory``. - A path owned by another user (other than root) is rejected when it, or any - directory above it, is world-writable: anyone on the machine could have - created it there. A path owned by the current user or by root is used, as - is another user's path in a directory tree that only its owners can write - (e.g. a shared project directory). A world-writable path that is used - produces a warning. + That is ``directory`` itself if it is world-writable (sticky or not), or an + ancestor that is world-writable without the sticky bit. A world-writable + ancestor with the sticky bit (``/tmp``, ``/scratch``) does not count: other + users cannot rename or remove the entries below it that they do not own. - Platforms without POSIX ownership (``os.getuid`` absent, e.g. Windows) - accept every path. + Returns + ------- + Path or None + The directory that makes the location writable by all users, or None. + """ + for location in (directory, *directory.parents): + try: + mode = os.stat(location).st_mode + except OSError: + continue + if mode & stat.S_IWOTH and (location == directory or not mode & stat.S_ISVTX): + return location + return None + + +def _reject_foreign(path: Path, uid: int, directories: Iterable[Path], hint: str) -> bool: + """ + Decide whether a path owned by another user is ignored, and say so if it is. + + The path is ignored if any of ``directories`` (where it was found, and + where it resolves to) is a location any user can write + (see ``_open_location``). + """ + for directory in dict.fromkeys(directories): + location = _open_location(directory) + if location is not None: + logger.warning( + f"Ignoring {path}: it is owned by another user (uid {uid}) and {location} is writable by all users.{hint}" + ) + return True + return False + + +def _read_found_file(path: Path, hint: str = "") -> str | None: + """ + Read a config or secret file found by searching, if it may be used. + + A file owned by the current user or by root is read. A file owned by another + user is read only if the directory it was found in, or the one it resolves + to, is not a location any user can write (see ``_open_location``); a shared + project directory qualifies, ``/tmp`` does not. A symbolic link owned by + another user is judged the same way. The ownership check uses the open file + descriptor, and the contents are read from that descriptor. A world-writable + file that is read produces a warning. + + Platforms without POSIX ownership (``os.getuid`` absent, e.g. Windows) read + every file. Parameters ---------- path : Path - File or directory found by the search. + File found by the search. hint : str, optional - Advice appended to the warning when the path is not used. + Advice appended to the warning when the file is ignored. Returns ------- - bool - True if the path may be used. + str or None + File contents, or None if the file is missing, not a regular file, or + ignored. """ - getuid = getattr(os, "getuid", None) - if getuid is None: - return True + if not hasattr(os, "getuid"): + try: + return path.read_text() + except OSError: + return None + + found_in = path.absolute().parent try: - st = os.stat(path) + link_st = os.lstat(path) except OSError: - return False + return None + if stat.S_ISLNK(link_st.st_mode) and _is_foreign(link_st.st_uid): + if _reject_foreign(path, link_st.st_uid, [found_in], hint): + return None - if st.st_uid not in (getuid(), 0): - # Check the directories the path was found in as well as those of its - # target, in case the path is a symbolic link. - found, resolved = path.absolute(), path.resolve() - locations = dict.fromkeys((found, *found.parents, resolved, *resolved.parents)) - for location in locations: - try: - mode = os.stat(location).st_mode - except OSError: - continue - if _is_world_writable(mode): - logger.warning( - f"Ignoring {path}: it is owned by another user (uid {st.st_uid}) and " - f"{location} is writable by all users.{hint}" - ) - return False + resolved = Path(os.path.realpath(path)) + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) + try: + fd = os.open(resolved, flags) + except FileNotFoundError: + return None + except OSError as e: + logger.warning(f"Could not read {path}: {e}") + return None + with os.fdopen(fd) as f: + st = os.fstat(f.fileno()) + if not stat.S_ISREG(st.st_mode): + return None + if _is_foreign(st.st_uid) and _reject_foreign(path, st.st_uid, [found_in, resolved.parent], hint): + return None + if st.st_mode & stat.S_IWOTH: + logger.warning(f"{path} is writable by all users; restrict its permissions (e.g. chmod o-w).") + return f.read() - if _is_world_writable(st.st_mode): - logger.warning(f"{path} is writable by all users; restrict its permissions (e.g. chmod o-w).") - return True +def _use_found_dir(path: Path, hint: str = "") -> bool: + """ + Decide whether a secrets directory found by searching may be used. -def find_config_file(start: Path | None = None) -> Path | None: + The rules of ``_read_found_file`` apply to the directory. The files in a + directory that is used are each checked again when read. """ - Search for datajoint.json in current and parent directories. + if not hasattr(os, "getuid"): + return path.is_dir() + found_in = path.absolute().parent + try: + link_st = os.lstat(path) + st = os.stat(path) + except OSError: + return False + if not stat.S_ISDIR(st.st_mode): + return False + if stat.S_ISLNK(link_st.st_mode) and _is_foreign(link_st.st_uid): + if _reject_foreign(path, link_st.st_uid, [found_in], hint): + return False + if _is_foreign(st.st_uid): + if _reject_foreign(path, st.st_uid, [found_in, Path(os.path.realpath(path)).parent], hint): + return False + if st.st_mode & stat.S_IWOTH: + logger.warning(f"{path} is writable by all users; restrict its permissions (e.g. chmod o-w).") + return True - Searches upward from ``start`` until finding the config file or hitting - a project boundary (``.git``, ``.hg``) or filesystem root. A file owned by - another user under a world-writable directory ends the search without a - result (see ``_check_discovered_path``). - Parameters - ---------- - start : Path, optional - Directory to start search from. Defaults to current working directory. +def _search_config_file(start: Path | None = None) -> tuple[Path | None, str | None]: + """ + Search for datajoint.json and read it. Returns ------- - Path or None - Path to config file if found, None otherwise. + tuple + ``(path, text)``: ``(None, None)`` if no file was found, ``(path, None)`` + if the file found was ignored (see ``_read_found_file``), otherwise the + path and its contents. """ current = (start or Path.cwd()).resolve() while True: config_path = current / CONFIG_FILENAME if config_path.is_file(): - hint = f" To use it, pass its path to dj.config.load() or set {CONFIG_FILE_ENV_VAR}." - return config_path if _check_discovered_path(config_path, hint) else None + return config_path, _read_found_file(config_path, _CONFIG_HINT) # Stop at project/repo root if (current / ".git").exists() or (current / ".hg").exists(): - return None + return None, None # Stop at filesystem root if current == current.parent: - return None + return None, None current = current.parent +def find_config_file(start: Path | None = None) -> Path | None: + """ + Search for datajoint.json in current and parent directories. + + Searches upward from ``start`` until finding the config file or hitting + a project boundary (``.git``, ``.hg``) or filesystem root. A file that + another user could have placed there ends the search without a result: + one owned by another user (not root) in a world-writable directory such as + ``/tmp``, or below a world-writable directory without the sticky bit. + + Parameters + ---------- + start : Path, optional + Directory to start search from. Defaults to current working directory. + + Returns + ------- + Path or None + Path to config file if found, None otherwise. + """ + config_path, text = _search_config_file(start) + return config_path if text is not None else None + + def find_secrets_dir(config_path: Path | None = None) -> Path | None: """ Find the secrets directory. @@ -212,8 +308,8 @@ def find_secrets_dir(config_path: Path | None = None) -> Path | None: 1. ``.secrets/`` in same directory as datajoint.json (project secrets) 2. ``/run/secrets/datajoint/`` (Docker/Kubernetes secrets) - A directory owned by another user under a world-writable directory is not - used (see ``_check_discovered_path``). + A directory that another user could have placed there is not used, under + the same rule as ``find_config_file``. Parameters ---------- @@ -228,12 +324,12 @@ def find_secrets_dir(config_path: Path | None = None) -> Path | None: # Check project secrets directory (next to config file) if config_path is not None: project_secrets = config_path.parent / SECRETS_DIRNAME - if project_secrets.is_dir() and _check_discovered_path(project_secrets, _SECRETS_HINT): + if project_secrets.is_dir() and _use_found_dir(project_secrets, _SECRETS_HINT): return project_secrets # Check system secrets directory (Docker/Kubernetes) if SYSTEM_SECRETS_DIR.is_dir(): - return SYSTEM_SECRETS_DIR if _check_discovered_path(SYSTEM_SECRETS_DIR, _SECRETS_HINT) else None + return SYSTEM_SECRETS_DIR if _use_found_dir(SYSTEM_SECRETS_DIR, _SECRETS_HINT) else None return None @@ -242,6 +338,9 @@ def read_secret_file(secrets_dir: Path | None, name: str) -> str | None: """ Read a secret value from a file in the secrets directory. + A file that another user could have placed there is ignored, under the + same rule as ``find_config_file``. + Parameters ---------- secrets_dir : Path or None @@ -257,11 +356,8 @@ def read_secret_file(secrets_dir: Path | None, name: str) -> str | None: if secrets_dir is None: return None - secret_path = secrets_dir / name - if secret_path.is_file() and _check_discovered_path(secret_path, _SECRETS_HINT): - return secret_path.read_text().strip() - - return None + value = _read_found_file(secrets_dir / name, _SECRETS_HINT) + return value.strip() if value is not None else None class DatabaseSettings(BaseSettings): @@ -827,12 +923,15 @@ def load(self, filename: str | Path) -> None: if not filepath.exists(): raise FileNotFoundError(f"Config file not found: {filepath}") - logger.info(f"Loading configuration from {filepath.absolute()}") - with open(filepath) as f: - data = json.load(f) + text = f.read() + + self._load_text(text, filepath) - self._update_from_flat_dict(data) + def _load_text(self, text: str, filepath: Path) -> None: + """Apply the JSON settings in ``text``, read from ``filepath``.""" + logger.info(f"Loading configuration from {filepath.absolute()}") + self._update_from_flat_dict(json.loads(text)) self._config_path = filepath def _update_from_flat_dict(self, data: dict[str, Any]) -> None: @@ -920,10 +1019,11 @@ def _load_secrets(self, secrets_dir: Path) -> None: parts = secret_file.name.split(".") if len(parts) == 3 and parts[0] == "stores": - if not _check_discovered_path(secret_file, _SECRETS_HINT): + text = _read_found_file(secret_file, _SECRETS_HINT) + if text is None: continue store_name, attr = parts[1], parts[2] - value = secret_file.read_text().strip() + value = text.strip() # Initialize store dict if needed if store_name not in self.stores: self.stores[store_name] = {} @@ -1214,12 +1314,21 @@ def _create_config() -> Config: # DJ_CONFIG_FILE names the config file explicitly; it is used as given, # like dj.config.load(), without searching. explicit_path = os.environ.get(CONFIG_FILE_ENV_VAR) - config_path = Path(explicit_path).expanduser() if explicit_path else find_config_file() - if config_path is not None: + if explicit_path: + config_path = Path(explicit_path).expanduser() + if not config_path.is_file(): + raise FileNotFoundError(f"{CONFIG_FILE_ENV_VAR} is set to {explicit_path!r}, which is not a file.") + text: str | None = config_path.read_text() + else: + config_path, text = _search_config_file() + if text is not None and config_path is not None: try: - cfg.load(config_path) + cfg._load_text(text, config_path) except Exception as e: warnings.warn(f"Failed to load config from {config_path}: {e}") + elif config_path is not None: + # The file found was not read; _read_found_file logged why. + config_path = None else: warnings.warn( f"No {CONFIG_FILENAME} found. Using defaults and environment variables. " diff --git a/tests/unit/test_npy_cache.py b/tests/unit/test_npy_cache.py index e2d7546a3..f94771327 100644 --- a/tests/unit/test_npy_cache.py +++ b/tests/unit/test_npy_cache.py @@ -33,13 +33,29 @@ def test_cache_dir_is_per_user_and_private(tempdir): @posix_only -def test_existing_cache_dir_permissions_tightened(tempdir): +def test_private_cache_dir_keeps_contents(tempdir): + cache_dir = tempdir / f"datajoint_mmap_{os.getuid()}" + cache_dir.mkdir(mode=0o700) + (cache_dir / "abc.npy").write_bytes(b"cached") + + assert npy._mmap_cache_dir() == cache_dir + assert (cache_dir / "abc.npy").read_bytes() == b"cached" + + +@posix_only +def test_open_cache_dir_restricted_and_cleared(tempdir): + """Files in a directory others could write to are not reused once it is made private.""" cache_dir = tempdir / f"datajoint_mmap_{os.getuid()}" cache_dir.mkdir() os.chmod(cache_dir, 0o777) + (cache_dir / "abc.npy").write_bytes(b"from-another-user") + (cache_dir / "subdir").mkdir() + (cache_dir / "link.npy").symlink_to(tempdir) assert npy._mmap_cache_dir() == cache_dir assert stat.S_IMODE(os.lstat(cache_dir).st_mode) == 0o700 + assert list(cache_dir.iterdir()) == [] + assert tempdir.is_dir() @posix_only diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index 22c901f64..1473a6438 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -1,5 +1,8 @@ """Tests for DataJoint settings module.""" +import os +import stat +import warnings from pathlib import Path import pytest @@ -1199,83 +1202,110 @@ def test_backend_field_in_env_var_mapping(self): assert ENV_VAR_MAPPING["database.backend"] == "DJ_BACKEND" +@pytest.mark.skipif(not hasattr(os, "getuid"), reason="requires POSIX file ownership") class TestDiscoveredFileOwnership: - """The config search skips files another user could have placed in a world-writable directory.""" + """The config search skips files another user could have placed where they are found.""" FOREIGN_UID = 54321 @pytest.fixture - def fs(self, monkeypatch, tmp_path): - """Patch ``os.stat`` so chosen paths report another owner or world-write permission. - - Returns a dict mapping a path to ``{"uid": ..., "world_writable": ...}``. - Paths not in the dict keep their real owner and lose any world-write bit, - so the host's own ``/tmp`` does not affect the outcome. + def mark(self, monkeypatch, tmp_path): + """Patch ``os.stat``/``lstat``/``fstat`` to report chosen owners and permissions. + + Returns ``mark(path, uid=None, world_writable=False, sticky=False, only=None)``, + which applies to the directory entry at ``path`` itself (a symbolic link + is marked, not its target). ``only`` limits the change to the named + functions. Entries not marked keep their real owner and lose any + world-write and sticky bits, so the host's own ``/tmp`` does not affect + the outcome. """ - import os - import stat as stat_mod - - real_stat = os.stat - overrides: dict[Path, dict] = {} - - def fake_stat(path, *args, **kwargs): - st = real_stat(path, *args, **kwargs) - if isinstance(path, int) or kwargs.get("dir_fd") is not None: - return st - fields = list(st) - spec = overrides.get(Path(os.path.realpath(path)), {}) - mode = fields[stat_mod.ST_MODE] & ~stat_mod.S_IWOTH - if spec.get("world_writable"): - mode |= stat_mod.S_IWOTH - fields[stat_mod.ST_MODE] = mode - if "uid" in spec: - fields[stat_mod.ST_UID] = spec["uid"] - return os.stat_result(fields) - - monkeypatch.setattr(os, "stat", fake_stat) + real = {name: getattr(os, name) for name in ("stat", "lstat", "fstat")} + overrides: dict[tuple[int, int], dict] = {} + + def wrap(name): + def fake(*args, **kwargs): + st = real[name](*args, **kwargs) + fields = list(st) + mode = fields[stat.ST_MODE] & ~(stat.S_IWOTH | stat.S_ISVTX) + spec = overrides.get((st.st_dev, st.st_ino)) + if spec is not None and name in spec["only"]: + mode |= spec["bits"] + if spec["uid"] is not None: + fields[stat.ST_UID] = spec["uid"] + fields[stat.ST_MODE] = mode + return os.stat_result(fields) + + return fake + + for name in real: + monkeypatch.setattr(os, name, wrap(name)) monkeypatch.setattr(settings, "SYSTEM_SECRETS_DIR", tmp_path / "nonexistent-system-secrets") - return overrides + + def mark(path, *, uid=None, world_writable=False, sticky=False, only=("stat", "lstat", "fstat")): + st = real["lstat"](path) + bits = (stat.S_IWOTH if world_writable else 0) | (stat.S_ISVTX if sticky else 0) + overrides[(st.st_dev, st.st_ino)] = {"uid": uid, "bits": bits, "only": only} + + return mark @pytest.fixture def shared(self, tmp_path): - """A shared parent directory holding a config file, with the user's project below it.""" + """A shared directory holding a config file, with the user's project below it.""" shared = tmp_path / "shared" project = shared / "project" project.mkdir(parents=True) (shared / CONFIG_FILENAME).write_text('{"database": {"host": "from-shared"}}') return shared - def test_foreign_config_in_world_writable_dir_skipped(self, fs, shared, caplog): - fs[shared] = {"world_writable": True} - fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} + def test_foreign_config_in_world_writable_dir_skipped(self, mark, shared, caplog): + """Another user's datajoint.json directly in /tmp (world-writable, sticky) is skipped.""" + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) with caplog.at_level("WARNING", logger="datajoint"): found = find_config_file(shared / "project") assert found is None - assert any("owned by another user" in r.message for r in caplog.records) - - def test_foreign_config_under_world_writable_ancestor_skipped(self, fs, shared, tmp_path): - """A world-writable directory anywhere above the file is enough to skip it.""" - fs[tmp_path] = {"world_writable": True} - fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} - - assert find_config_file(shared / "project") is None - - def test_foreign_config_in_protected_dir_used(self, fs, shared): + messages = [r.message for r in caplog.records] + assert any(str(shared / CONFIG_FILENAME) in m and "DJ_CONFIG_FILE" in m for m in messages) + + def test_group_config_under_sticky_world_writable_root_used(self, mark, tmp_path): + """/scratch (1777) / lab (2770, PI-owned) / datajoint.json owned by the PI is used.""" + scratch = tmp_path / "scratch" + lab = scratch / "lab" + (lab / "project").mkdir(parents=True) + (lab / CONFIG_FILENAME).write_text("{}") + mark(scratch, world_writable=True, sticky=True) + mark(lab, uid=self.FOREIGN_UID) + mark(lab / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + assert find_config_file(lab / "project") == lab / CONFIG_FILENAME + + def test_foreign_config_below_non_sticky_world_writable_dir_skipped(self, mark, tmp_path): + """A world-writable ancestor without the sticky bit lets anyone replace what is below it.""" + open_dir = tmp_path / "open" + lab = open_dir / "lab" + (lab / "project").mkdir(parents=True) + (lab / CONFIG_FILENAME).write_text("{}") + mark(open_dir, world_writable=True) + mark(lab / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + assert find_config_file(lab / "project") is None + + def test_foreign_config_in_protected_dir_used(self, mark, shared): """Another user's file in a directory only its owners can write (e.g. a lab share) is used.""" - fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) assert find_config_file(shared / "project") == shared / CONFIG_FILENAME - def test_root_owned_config_in_world_writable_dir_used(self, fs, shared): - fs[shared] = {"world_writable": True} - fs[shared / CONFIG_FILENAME] = {"uid": 0} + def test_root_owned_config_in_world_writable_dir_used(self, mark, shared): + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=0) assert find_config_file(shared / "project") == shared / CONFIG_FILENAME - def test_own_config_in_world_writable_dir_used(self, fs, shared, caplog): - fs[shared] = {"world_writable": True} + def test_own_config_in_world_writable_dir_used(self, mark, shared, caplog): + mark(shared, world_writable=True, sticky=True) with caplog.at_level("WARNING", logger="datajoint"): found = find_config_file(shared / "project") @@ -1283,8 +1313,8 @@ def test_own_config_in_world_writable_dir_used(self, fs, shared, caplog): assert found == shared / CONFIG_FILENAME assert not caplog.records - def test_world_writable_own_config_warns(self, fs, shared, caplog): - fs[shared / CONFIG_FILENAME] = {"world_writable": True} + def test_world_writable_own_config_warns(self, mark, shared, caplog): + mark(shared / CONFIG_FILENAME, world_writable=True) with caplog.at_level("WARNING", logger="datajoint"): found = find_config_file(shared / "project") @@ -1292,8 +1322,23 @@ def test_world_writable_own_config_warns(self, fs, shared, caplog): assert found == shared / CONFIG_FILENAME assert any("writable by all users" in r.message for r in caplog.records) - def test_symlink_in_world_writable_dir_to_foreign_file_skipped(self, fs, tmp_path): - """A link placed in a world-writable directory is judged by where it was found.""" + def test_foreign_symlink_to_own_file_skipped(self, mark, tmp_path): + """A link owned by another user in a world-writable directory is skipped, whatever it points at.""" + own = tmp_path / "own" + own.mkdir() + target = own / "mine.json" + target.write_text("{}") + shared = tmp_path / "shared" + (shared / "project").mkdir(parents=True) + link = shared / CONFIG_FILENAME + link.symlink_to(target) + mark(shared, world_writable=True, sticky=True) + mark(link, uid=self.FOREIGN_UID) + + assert find_config_file(shared / "project") is None + + def test_own_symlink_to_foreign_file_skipped(self, mark, tmp_path): + """A link in a world-writable directory to another user's file is judged by where it was found.""" protected = tmp_path / "protected" protected.mkdir() target = protected / CONFIG_FILENAME @@ -1301,30 +1346,37 @@ def test_symlink_in_world_writable_dir_to_foreign_file_skipped(self, fs, tmp_pat shared = tmp_path / "shared" (shared / "project").mkdir(parents=True) (shared / CONFIG_FILENAME).symlink_to(target) - fs[shared] = {"world_writable": True} - fs[target] = {"uid": self.FOREIGN_UID} + mark(shared, world_writable=True, sticky=True) + mark(target, uid=self.FOREIGN_UID) + + assert find_config_file(shared / "project") is None + + def test_owner_checked_on_opened_file(self, mark, shared): + """The owner is taken from the opened file, so a file replaced after the search is still checked.""" + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID, only=("fstat",)) assert find_config_file(shared / "project") is None - def test_foreign_secrets_dir_in_world_writable_dir_skipped(self, fs, tmp_path): + def test_foreign_secrets_dir_in_world_writable_dir_skipped(self, mark, tmp_path): config_file = tmp_path / CONFIG_FILENAME config_file.write_text("{}") secrets_dir = tmp_path / SECRETS_DIRNAME secrets_dir.mkdir() - fs[tmp_path] = {"world_writable": True} - fs[secrets_dir] = {"uid": self.FOREIGN_UID} + mark(tmp_path, world_writable=True, sticky=True) + mark(secrets_dir, uid=self.FOREIGN_UID) assert find_secrets_dir(config_file) is None - def test_foreign_secret_file_in_world_writable_secrets_dir_skipped(self, fs, tmp_path): + def test_foreign_secret_file_in_world_writable_secrets_dir_skipped(self, mark, tmp_path): secrets_dir = tmp_path / SECRETS_DIRNAME secrets_dir.mkdir() - (secrets_dir / "database.password").write_text("planted") - (secrets_dir / "stores.main.secret_key").write_text("planted") + (secrets_dir / "database.password").write_text("from-other-user") + (secrets_dir / "stores.main.secret_key").write_text("from-other-user") (secrets_dir / "database.user").write_text("mine") - fs[secrets_dir] = {"world_writable": True} - fs[secrets_dir / "database.password"] = {"uid": self.FOREIGN_UID} - fs[secrets_dir / "stores.main.secret_key"] = {"uid": self.FOREIGN_UID} + mark(secrets_dir, world_writable=True) + mark(secrets_dir / "database.password", uid=self.FOREIGN_UID) + mark(secrets_dir / "stores.main.secret_key", uid=self.FOREIGN_UID) assert read_secret_file(secrets_dir, "database.password") is None assert read_secret_file(secrets_dir, "database.user") == "mine" @@ -1334,44 +1386,54 @@ def test_foreign_secret_file_in_world_writable_secrets_dir_skipped(self, fs, tmp assert cfg.database.password is None assert "main" not in cfg.stores - def test_no_posix_ownership_keeps_search(self, fs, shared, monkeypatch): + def test_no_posix_ownership_keeps_search(self, mark, shared, monkeypatch): """Without os.getuid (Windows) the search behaves as before.""" - import os - - monkeypatch.delattr(os, "getuid") - fs[shared] = {"world_writable": True} - fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + monkeypatch.delattr(os, "getuid", raising=False) assert find_config_file(shared / "project") == shared / CONFIG_FILENAME - def test_create_config_skips_foreign_config(self, fs, shared, monkeypatch): + def test_create_config_skips_foreign_config_with_one_warning(self, mark, shared, monkeypatch, caplog): for var in ("DJ_HOST", "DJ_CONFIG_FILE", "DJ_IGNORE_CONFIG_FILE"): monkeypatch.delenv(var, raising=False) monkeypatch.chdir(shared / "project") - fs[shared] = {"world_writable": True} - fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) - with pytest.warns(UserWarning, match="No datajoint.json found"): + with warnings.catch_warnings(record=True) as caught, caplog.at_level("WARNING", logger="datajoint"): + warnings.simplefilter("always") cfg = settings._create_config() assert cfg.database.host == "localhost" + assert not [w for w in caught if "No datajoint.json found" in str(w.message)] + skipped = [r.message for r in caplog.records if "Ignoring" in r.message] + assert len(skipped) == 1 + assert "DJ_CONFIG_FILE" in skipped[0] and "dj.config.load()" in skipped[0] - def test_dj_config_file_names_file_explicitly(self, fs, shared, monkeypatch, tmp_path): + def test_dj_config_file_names_file_explicitly(self, mark, shared, monkeypatch, tmp_path): """DJ_CONFIG_FILE loads the named file, without searching and without the ownership check.""" monkeypatch.delenv("DJ_HOST", raising=False) monkeypatch.delenv("DJ_IGNORE_CONFIG_FILE", raising=False) elsewhere = tmp_path / "elsewhere" (elsewhere / ".git").mkdir(parents=True) monkeypatch.chdir(elsewhere) - fs[shared] = {"world_writable": True} - fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) monkeypatch.setenv("DJ_CONFIG_FILE", str(shared / CONFIG_FILENAME)) cfg = settings._create_config() assert cfg.database.host == "from-shared" - def test_dj_config_file_ignored_with_ignore_config_file(self, fs, shared, monkeypatch): + def test_dj_config_file_missing_raises(self, mark, monkeypatch, tmp_path): + monkeypatch.delenv("DJ_IGNORE_CONFIG_FILE", raising=False) + monkeypatch.setenv("DJ_CONFIG_FILE", str(tmp_path / "missing.json")) + + with pytest.raises(FileNotFoundError, match="DJ_CONFIG_FILE"): + settings._create_config() + + def test_dj_config_file_ignored_with_ignore_config_file(self, mark, shared, monkeypatch): monkeypatch.delenv("DJ_HOST", raising=False) monkeypatch.setenv("DJ_CONFIG_FILE", str(shared / CONFIG_FILENAME)) monkeypatch.setenv("DJ_IGNORE_CONFIG_FILE", "true") @@ -1380,11 +1442,11 @@ def test_dj_config_file_ignored_with_ignore_config_file(self, fs, shared, monkey assert cfg.database.host == "localhost" - def test_explicit_load_uses_foreign_file(self, fs, shared, monkeypatch): + def test_explicit_load_uses_foreign_file(self, mark, shared, monkeypatch): """dj.config.load(path) is an explicit choice and is not checked.""" monkeypatch.delenv("DJ_HOST", raising=False) - fs[shared] = {"world_writable": True} - fs[shared / CONFIG_FILENAME] = {"uid": self.FOREIGN_UID} + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) cfg = settings.Config() cfg.load(shared / CONFIG_FILENAME) From 7a812f89f69348d8a239947105ddb6997d24e33d Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 9 Nov 2026 13:34:33 -0600 Subject: [PATCH 26/37] fix(connection): apply use_tls on every path; one connection by default on MySQL dj.conn(use_tls=...) now creates the shared connection with use_tls even when no credentials are passed, and reconnects an existing shared connection that was made with weaker TLS settings (True is met by True or a dict; a dict only by the same dict). datajoint.connection.conn does the same. use_tls=False now reaches the adapters: MySQL disables TLS, PostgreSQL uses sslmode=disable. Before, both received None. use_tls not set (default): - MySQL makes one connection that uses TLS when the server offers it and continues without TLS otherwise. No second connection, no warning; errors during the TLS handshake are not retried. - PostgreSQL connects with sslmode=require, then with sslmode=disable only if the server does not support SSL or pg_hba.conf has no entry for SSL connections from this client. Authentication and other errors are not retried. libpq's sslmode=prefer is not used because it also retries without SSL after an authentication failure. PostgreSQL use_tls dict keys that are ignored, including check_hostname without ca, are now reported in a warning. --- src/datajoint/__init__.py | 16 +- src/datajoint/adapters/base.py | 20 -- src/datajoint/adapters/mysql.py | 66 +++--- src/datajoint/adapters/postgres.py | 55 +++-- src/datajoint/connection.py | 68 +++--- tests/integration/test_tls.py | 19 +- tests/unit/test_tls.py | 330 ++++++++++++++++++++--------- 7 files changed, 361 insertions(+), 213 deletions(-) diff --git a/src/datajoint/__init__.py b/src/datajoint/__init__.py index 69c6df269..7a514674a 100644 --- a/src/datajoint/__init__.py +++ b/src/datajoint/__init__.py @@ -134,7 +134,11 @@ def conn( reset : bool, optional If True, reset existing connection. Default False. use_tls : bool or dict, optional - TLS encryption option. + TLS encryption option: True (required), False (no TLS), None (from + config; TLS if the server supports it by default), or dict (TLS + required; ``ca``, ``cert``, ``key``; with ``ca``, the server + certificate is verified). If the singleton connection exists and was + made with weaker TLS settings, it is reconnected with these. Returns ------- @@ -152,10 +156,12 @@ def conn( _check_thread_safe() # If reset requested, always recreate - # If credentials provided and no singleton exists, create one - # If credentials provided and singleton exists, return existing singleton + # If credentials or use_tls provided and no singleton exists, create one + # If credentials provided and singleton exists, return existing singleton, + # reconnected if use_tls asks for stronger TLS than it was made with if reset or ( - instance_module._singleton_connection is None and (host is not None or user is not None or password is not None) + instance_module._singleton_connection is None + and (host is not None or user is not None or password is not None or use_tls is not None) ): # Use provided values or fall back to config host = host if host is not None else _global_config.database.host @@ -177,6 +183,8 @@ def conn( ) instance_module._singleton_connection = Connection(host, user, password, port, use_tls, config_override=_global_config) + elif instance_module._singleton_connection is not None: + instance_module._singleton_connection._ensure_tls(use_tls) return _get_singleton_connection() diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 55eb6b641..1aa12f52f 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -55,26 +55,6 @@ def connect( """ ... - def is_tls_negotiation_error(self, error: Exception) -> bool: - """ - Whether a connection attempt failed while negotiating TLS. - - When ``use_tls`` is not set, a connection that fails to negotiate TLS - (the server does not support it, or the TLS handshake fails) is retried - without TLS. Authentication and other errors are not retried. - - Parameters - ---------- - error : Exception - Exception raised by :meth:`connect`. - - Returns - ------- - bool - True if the failure is in TLS negotiation. Default False. - """ - return False - @abstractmethod def close(self, connection: Any) -> None: """ diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index 68cf2dcb8..0c7e05e4b 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -61,17 +61,29 @@ class _TLSRequiredConnection(client.connections.Connection): """ PyMySQL connection that does not authenticate without TLS. - PyMySQL continues without TLS when the server does not offer it, even when - TLS is configured. This check runs after the server greeting, before the - credentials are sent. + Depending on its version, PyMySQL continues without TLS or fails with a + handshake error when TLS is configured and the server does not offer it. + This check runs after the server greeting, before the credentials are sent. """ + tls_required = True + def _request_authentication(self): if not self.server_capabilities & CLIENT.SSL: - raise _TLSUnavailableError() + if self.tls_required: + raise _TLSUnavailableError() + # Continue without TLS: do not announce TLS in the handshake response + self.ssl = False + self.client_flag &= ~CLIENT.SSL super()._request_authentication() +class _TLSPreferredConnection(_TLSRequiredConnection): + """PyMySQL connection that uses TLS when the server offers it and continues without TLS otherwise.""" + + tls_required = False + + def _unverified_tls_context() -> ssl.SSLContext: """TLS context that encrypts without verifying the server certificate.""" context = ssl.create_default_context() @@ -112,6 +124,8 @@ def connect( Additional MySQL-specific parameters: - ssl: TLS/SSL configuration dict (deprecated, use use_tls) - use_tls: bool or dict - DataJoint's SSL parameter (preferred). + None: TLS if the server offers it, otherwise no TLS; server + certificate not verified. True: TLS required, server certificate not verified. dict: TLS required, configured with PyMySQL ``ssl`` keys (``ca``, ``cert``, ``key``, ``check_hostname``, ...); with ``ca``, @@ -125,9 +139,10 @@ def connect( """ # Handle both ssl (old) and use_tls (new) parameter names ssl_config = kwargs.get("use_tls", kwargs.get("ssl")) - # PyMySQL treats an empty dict as "no TLS"; True and {} require TLS + tls_required = ssl_config is not None + # PyMySQL treats an empty dict as "no TLS"; None, True, and {} use TLS # without verifying the server certificate. - if ssl_config is True or (isinstance(ssl_config, dict) and not ssl_config): + if ssl_config is None or ssl_config is True or (isinstance(ssl_config, dict) and not ssl_config): ssl_config = _unverified_tls_context() charset = kwargs.get("charset", "") @@ -147,29 +162,22 @@ def connect( if ssl_config is False: # Explicitly disable SSL conn_params["ssl_disabled"] = True - elif ssl_config is not None: - # Require SSL, configured by the dict or SSLContext - conn_params["ssl"] = ssl_config - # Explicitly enable SSL by setting ssl_disabled=False - conn_params["ssl_disabled"] = False - connection = _TLSRequiredConnection(**conn_params) - # Checked again in case a PyMySQL version bypasses the hook above - if not connection.server_capabilities & CLIENT.SSL: - connection.close() - raise _TLSUnavailableError() - return connection - - return client.connect(**conn_params) - - def is_tls_negotiation_error(self, error: Exception) -> bool: - """ - Whether a connection attempt failed while negotiating TLS. - - Matches a server that does not offer TLS, and a failed TLS handshake - (reported by PyMySQL as ``OperationalError`` carrying the ``SSLError``). - Both happen before the credentials are sent. - """ - return isinstance(error, _TLSUnavailableError) or isinstance(getattr(error, "original_exception", None), ssl.SSLError) + return client.connect(**conn_params) + + conn_params["ssl"] = ssl_config + # Explicitly enable SSL by setting ssl_disabled=False + conn_params["ssl_disabled"] = False + if not tls_required: + # use_tls=None: one connection, with TLS if the server offers it + return _TLSPreferredConnection(**conn_params) + + # Require SSL, configured by the dict or SSLContext + connection = _TLSRequiredConnection(**conn_params) + # Checked again in case a PyMySQL version bypasses the hook above + if not connection.server_capabilities & CLIENT.SSL: + connection.close() + raise _TLSUnavailableError() + return connection def close(self, connection: Any) -> None: """Close the MySQL connection.""" diff --git a/src/datajoint/adapters/postgres.py b/src/datajoint/adapters/postgres.py index 7e326e60e..2bff35607 100644 --- a/src/datajoint/adapters/postgres.py +++ b/src/datajoint/adapters/postgres.py @@ -26,8 +26,21 @@ # use_tls dict keys (PyMySQL ssl names, as for MySQL) → libpq connection parameters _LIBPQ_TLS_KEYS = {"ca": "sslrootcert", "cert": "sslcert", "key": "sslkey", "password": "sslpassword"} -# libpq messages for a server without SSL support and for a failed SSL handshake -_TLS_NEGOTIATION_MESSAGES = ("server does not support SSL", "SSL error:", "SSL SYSCALL error:") + +def _tls_rejected(error: Exception) -> bool: + """ + Whether a connection attempt with sslmode=require was refused before authentication + because of SSL: the server does not support SSL, or pg_hba.conf has no entry + for SSL connections from this client. + + psycopg2 does not report a SQLSTATE for connection failures, so the libpq and + server messages are matched. Authentication failures do not match. + """ + message = str(error) + if "server does not support SSL" in message: + return True + # SQLSTATE 28000 from pg_hba.conf; "SSL encryption" (PostgreSQL 14+) or "SSL on" (earlier) + return "pg_hba.conf" in message and ("SSL encryption" in message or "SSL on" in message) def _libpq_tls_params(use_tls: dict) -> dict[str, Any]: @@ -39,13 +52,19 @@ def _libpq_tls_params(use_tls: dict) -> dict[str, Any]: ``check_hostname`` is False. Without ``ca``, sslmode is ``require``. """ params = {_LIBPQ_TLS_KEYS[k]: v for k, v in use_tls.items() if k in _LIBPQ_TLS_KEYS and v is not None} + supported = set(_LIBPQ_TLS_KEYS) if "sslrootcert" in params: params["sslmode"] = "verify-full" if use_tls.get("check_hostname", True) else "verify-ca" + supported.add("check_hostname") else: params["sslmode"] = "require" - ignored = sorted(set(use_tls) - set(_LIBPQ_TLS_KEYS) - {"check_hostname"}) + # Keys set to None or False request nothing; other unused keys are reported + ignored = sorted(k for k in set(use_tls) - supported if use_tls[k] not in (None, False)) if ignored: - logger.warning("use_tls keys not supported for PostgreSQL are ignored: %s", ", ".join(ignored)) + logger.warning( + "use_tls keys ignored for PostgreSQL: %s. Supported: ca, cert, key, password, and check_hostname with ca.", + ", ".join(ignored), + ) return params @@ -122,7 +141,9 @@ def connect( - sslmode: SSL mode ('disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full') - use_tls: bool or dict - DataJoint's SSL parameter (converted to sslmode). - True: 'require'. False: 'disable'. None: 'prefer'. + True: 'require'. False: 'disable'. + None: 'require', then 'disable' only if the server does not support + SSL or pg_hba.conf does not accept SSL connections from this client. dict: ``ca``, ``cert``, ``key``, ``password`` map to sslrootcert, sslcert, sslkey, sslpassword; sslmode is 'verify-full' with ``ca`` ('verify-ca' if ``check_hostname`` is False), otherwise 'require'. @@ -154,19 +175,26 @@ def connect( # use_tls=True → require SSL sslmode = "require" else: - # use_tls=None (default) → prefer SSL but allow fallback - sslmode = "prefer" + # use_tls=None (default) → require SSL, then fall back below. libpq's + # sslmode=prefer also retries without SSL after an authentication failure. + sslmode = "require" - conn = client.connect( + params = dict( host=host, port=port, user=user, password=password, dbname=dbname, - sslmode=sslmode, connect_timeout=connect_timeout, **tls_params, ) + try: + conn = client.connect(sslmode=sslmode, **params) + except client.OperationalError as error: + if "sslmode" in kwargs or use_tls is not None or not _tls_rejected(error): + raise + logger.debug("Connecting without SSL: %s", str(error).strip()) + conn = client.connect(sslmode="disable", **params) # DataJoint manages transactions explicitly via start_transaction() # Set autocommit=True to avoid implicit transactions conn.autocommit = True @@ -176,15 +204,6 @@ def connect( return conn - def is_tls_negotiation_error(self, error: Exception) -> bool: - """ - Whether a connection attempt failed while negotiating TLS. - - Matches libpq's errors for a server without SSL support and for a failed - SSL handshake. Authentication errors do not match. - """ - return isinstance(error, client.OperationalError) and any(m in str(error) for m in _TLS_NEGOTIATION_MESSAGES) - def _register_numpy_adapters(self) -> None: """ Register psycopg2 adapters for numpy types. diff --git a/src/datajoint/connection.py b/src/datajoint/connection.py index bd7c426e4..58a4bd523 100644 --- a/src/datajoint/connection.py +++ b/src/datajoint/connection.py @@ -81,7 +81,8 @@ def conn( TLS encryption option: True (required), False (no TLS), None (preferred, default), or dict for manual configuration (TLS required; ``ca``, ``cert``, ``key``; with ``ca``, the server - certificate is verified). + certificate is verified). If the existing connection was made with + weaker TLS settings, it is reconnected with these. Returns ------- @@ -107,6 +108,8 @@ def conn( ) use_tls = use_tls if use_tls is not None else config["database.use_tls"] conn.connection = Connection(host, user, password, None, use_tls) + else: + conn.connection._ensure_tls(use_tls) return conn.connection @@ -201,17 +204,7 @@ def __init__( if database_name is None: database_name = self._config.get("database.name") self.conn_info = dict(host=host, port=port, user=user, passwd=password, database_name=database_name) - if use_tls is not False: - # use_tls can be: None (auto-detect), True (enable), False (disable), or dict (custom config) - if isinstance(use_tls, dict): - self.conn_info["ssl"] = use_tls - elif use_tls is None: - # Auto-detect: try SSL, fallback to non-SSL if server doesn't support it - self.conn_info["ssl"] = True - else: - # use_tls=True: enable SSL with default settings - self.conn_info["ssl"] = True - self.conn_info["ssl_input"] = use_tls + self._set_use_tls(use_tls) self._conn = None self._query_cache = None self._is_closed = True # Mark as closed until connect() succeeds @@ -260,7 +253,36 @@ def __repr__(self): db_str = f"/{db}" if db else "" return f"DataJoint connection ({connected}) {user}@{host}:{port}{db_str}" - def _build_connect_kwargs(self, use_tls=None): + def _set_use_tls(self, use_tls: bool | dict | None) -> None: + """Record the use_tls option in conn_info.""" + # use_tls can be: None (TLS if the server supports it), True (required), False (disabled), + # or dict (required, custom config) + self.conn_info.pop("ssl", None) + if use_tls is not False: + self.conn_info["ssl"] = use_tls if isinstance(use_tls, dict) else True + self.conn_info["ssl_input"] = use_tls + + def _ensure_tls(self, use_tls: bool | dict | None) -> None: + """ + Reconnect with ``use_tls`` if the connection was made with weaker TLS settings. + + ``use_tls=True`` is met by a connection made with True or a dict; + a dict is met only by a connection made with the same dict. + None and False request nothing beyond the existing connection. + """ + current = self.conn_info.get("ssl_input") + if use_tls is None or use_tls is False or current == use_tls: + return + if use_tls is True and isinstance(current, dict): + return + if self.in_transaction: + raise errors.DataJointError("Cannot change use_tls of a connection during a transaction.") + logger.info("Reconnecting with use_tls=%r (connection was made with use_tls=%r).", use_tls, current) + self.close() + self._set_use_tls(use_tls) + self.connect() + + def _build_connect_kwargs(self): """Build kwargs dict for adapter.connect().""" kwargs = dict( host=self.conn_info["host"], @@ -268,7 +290,7 @@ def _build_connect_kwargs(self, use_tls=None): user=self.conn_info["user"], password=self.conn_info["passwd"], charset=self._config["connection.charset"], - use_tls=use_tls if use_tls is not None else self.conn_info.get("ssl"), + use_tls=self.conn_info["ssl_input"], ) if self.conn_info.get("database_name"): kwargs["dbname"] = self.conn_info["database_name"] @@ -278,21 +300,9 @@ def connect(self) -> None: """Establish or re-establish connection to the database server.""" with warnings.catch_warnings(): warnings.filterwarnings("ignore", ".*deprecated.*") - try: - self._conn = self.adapter.connect(**self._build_connect_kwargs()) - except Exception as ssl_error: - # If SSL negotiation fails (server without SSL, or failed handshake), retry - # without SSL when it was auto-detected. Other errors, such as authentication - # failures, are not retried. - if self.conn_info.get("ssl_input") is None and self.adapter.is_tls_negotiation_error(ssl_error): - logger.warning( - "SSL connection failed (%s). Falling back to non-SSL connection. " - "To require SSL, set use_tls=True explicitly.", - ssl_error, - ) - self._conn = self.adapter.connect(**self._build_connect_kwargs(use_tls=False)) - else: - raise + # With use_tls=None, the adapter uses TLS if the server supports it and + # continues without TLS otherwise; it does not retry after other errors. + self._conn = self.adapter.connect(**self._build_connect_kwargs()) self._is_closed = False # Mark as connected after successful connection def set_query_cache(self, query_cache: str | None = None) -> None: diff --git a/tests/integration/test_tls.py b/tests/integration/test_tls.py index 8f2681dd9..fc8a70c77 100644 --- a/tests/integration/test_tls.py +++ b/tests/integration/test_tls.py @@ -1,4 +1,3 @@ -import logging import os import pytest @@ -22,19 +21,11 @@ def test_explicit_ssl_connection(db_creds_test, connection_test): @requires_ssl -def test_ssl_auto_detect(db_creds_test, connection_test, caplog): - """When use_tls is not specified, SSL is preferred but fallback is allowed with warning.""" - with caplog.at_level(logging.WARNING): - conn = dj.conn(reset=True, **db_creds_test) - result = conn.query("SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] - - if len(result) > 0: - # SSL connected successfully - assert "SSL connection failed" not in caplog.text - else: - # SSL failed and fell back - warning should be logged - assert "SSL connection failed" in caplog.text - assert "Falling back to non-SSL" in caplog.text +def test_ssl_auto_detect(db_creds_test, connection_test): + """When use_tls is not specified, SSL is used if the server supports it.""" + conn = dj.conn(reset=True, **db_creds_test) + result = conn.query("SHOW STATUS LIKE 'Ssl_cipher';").fetchone()[1] + assert len(result) > 0, "SSL should be active when the server supports it" def test_insecure_connection(db_creds_test, connection_test): diff --git a/tests/unit/test_tls.py b/tests/unit/test_tls.py index 09d648260..a5a1acfb2 100644 --- a/tests/unit/test_tls.py +++ b/tests/unit/test_tls.py @@ -4,8 +4,10 @@ The adapters' parameter mapping is checked with the driver's connect function replaced. The handshake checks run the real drivers against a minimal local server that answers the initial protocol exchange without offering TLS. +Connection and dj.conn are checked with a mock adapter. """ +import importlib import socket import ssl import struct @@ -18,7 +20,6 @@ from datajoint.adapters import MySQLAdapter, PostgreSQLAdapter from datajoint.adapters import mysql as mysql_adapter -from datajoint.connection import Connection CREDENTIALS = dict(host="localhost", port=3306, user="alice", password="secret") @@ -113,6 +114,11 @@ def _mysql_server_failing_handshake(sock, received): sock.sendall(b"\x00" * 64) +def _mysql_client_flags(received): + """Capability flags of the client's handshake response (first packet sent).""" + return struct.unpack(" Date: Mon, 9 Nov 2026 13:40:11 -0600 Subject: [PATCH 27/37] Keep describe() output total; accept parenthesized and instantiated references describe() no longer raises on names, defaults or types it cannot write as plain tokens: line breaks become spaces and projection names are written as escaped string literals, so describe() and Diagram work for every table. Foreign key references also accept the forms that worked before and only name a table: a reference in parentheses, Parent().proj(...), and identifiers with non-ASCII letters. Calls, expressions, ** arguments and dunder names are still refused. Every refused or unknown reference reports that it "could not be resolved", with the supported forms, so alter() keeps its message for a parent missing from the context. Tests: projection arguments are passed through as strings; a reference that names a function does not call it; decompression of a blob larger than its declared size stays within a fixed memory bound; test_long_table_name checks the length message. --- src/datajoint/declare.py | 239 ++++++++++++++++------- src/datajoint/table.py | 42 ++-- tests/integration/test_alter.py | 34 +++- tests/integration/test_declare.py | 2 +- tests/unit/test_blob_decompression.py | 18 +- tests/unit/test_foreign_key_reference.py | 158 ++++++++++----- 6 files changed, 335 insertions(+), 158 deletions(-) diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index 15f841e76..87cef4619 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -7,6 +7,7 @@ from __future__ import annotations +import ast import logging import re @@ -169,40 +170,150 @@ def build_attribute_parser() -> pp.ParserElement: return attribute_name + pp.Optional(default) + colon + data_type + comment -def build_reference_parser() -> pp.ParserElement: +foreign_key_parser = build_foreign_key_parser() +attribute_parser = build_attribute_parser() + +_REFERENCE_TOKEN = re.compile( + r"""\s*(?: + (?P\#.*) + | (?P[^\W\d]\w*) + | (?P"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*') + | (?P[.(),=]) + )""", + re.VERBOSE, +) + +_REFERENCE_FORMS = ( + "use a table name such as Parent, module.Parent or Master.Part, " + "optionally projected with Parent.proj(new_name='old_name')" +) + + +def _tokenize_reference(text: str) -> list[tuple[str, str]]: + """Split a foreign key reference into (kind, value) tokens, dropping a trailing comment.""" + tokens = [] + pos = 0 + while pos < len(text): + match = _REFERENCE_TOKEN.match(text, pos) + if match is None: + if text[pos:].strip(): + raise ValueError(f"unexpected text {text[pos:].strip()!r}") + break + pos = match.end() + kind = match.lastgroup + value = match.group(kind) + if kind == "comment": + break + if kind == "name" and not value.isidentifier(): + raise ValueError(f"{value!r} is not a name") + if kind == "string": + value = ast.literal_eval(value) + tokens.append((kind, value)) + return tokens + + +def parse_foreign_key_reference(text: str) -> list[tuple]: """ - Build a pyparsing parser for the table reference in a foreign key line. + Parse the table reference of a foreign key line into lookup steps. + + The supported forms are a dotted name (``Parent``, ``module.Parent``, + ``Master.Part``), optionally in parentheses, instantiated with ``()``, or + projected with ``.proj(...)`` whose arguments are string literals. The + text is only parsed; nothing in it is evaluated. + + Parameters + ---------- + text : str + The reference, e.g. ``"Parent.proj(new_id='parent_id')"``. Returns ------- - pp.ParserElement - Parser for a dotted name such as ``Parent``, ``module.Parent`` or - ``Master.Part``, optionally followed by ``()`` or by a projection - ``.proj(new_name="old_name", ...)`` whose arguments are string literals. - """ - identifier = pp.Word(pp.alphas + "_", pp.alphanums + "_") - name = pp.Group(pp.DelimitedList(identifier, delim=".")).set_results_name("name") - string = pp.QuotedString('"', esc_char="\\") ^ pp.QuotedString("'", esc_char="\\") - keyword_arg = pp.Group(identifier + pp.Literal("=").suppress() + string) - positional_arg = pp.Group(string) - argument = keyword_arg ^ positional_arg - arguments = pp.Optional(pp.DelimitedList(argument, allow_trailing_delim=True)) - call = pp.Group(pp.Literal("(").suppress() + arguments + pp.Literal(")").suppress()).set_results_name("call") - return name + pp.Optional(call) + pp.Optional(pp.python_style_comment).suppress() + pp.StringEnd() + list[tuple] + Steps ``("name", name)``, ``("attr", name)``, ``("instance",)`` and + ``("proj", args, kwargs)``, applied in order by + :func:`resolve_foreign_key_reference`. + Raises + ------ + ValueError + If the text is not one of the supported forms. + """ + tokens = _tokenize_reference(text) + pos = 0 + + def peek(value=None): + if pos >= len(tokens): + return False + return value is None or tokens[pos] == ("punct", value) + + def expect(kind, value=None): + nonlocal pos + if pos >= len(tokens) or tokens[pos][0] != kind or (value is not None and tokens[pos][1] != value): + found = repr(tokens[pos][1]) if pos < len(tokens) else "end of line" + raise ValueError(f"expected {value or kind}, found {found}") + pos += 1 + return tokens[pos - 1][1] + + def arguments(): + args, kwargs = [], {} + while not peek(")"): + if pos + 1 < len(tokens) and tokens[pos][0] == "name" and tokens[pos + 1] == ("punct", "="): + key = expect("name") + expect("punct", "=") + if key in kwargs: + raise ValueError(f"repeated argument {key!r}") + kwargs[key] = expect("string") + elif kwargs: + raise ValueError("positional argument follows keyword argument") + else: + args.append(expect("string")) + if not peek(")"): + expect("punct", ",") + expect("punct", ")") + return args, kwargs + + def reference(): + nonlocal pos + if peek("("): + pos += 1 + steps = reference() + expect("punct", ")") + else: + name = expect("name") + if name.startswith("__"): + raise ValueError(f"name {name!r} is not a table") + steps = [("name", name)] + while peek("(") or peek("."): + if peek("."): + pos += 1 + attr = expect("name") + if attr.startswith("__"): + raise ValueError(f"attribute {attr!r} is not a table") + if attr == "proj" and peek("("): + pos += 1 + steps.append(("proj", *arguments())) + else: + steps.append(("attr", attr)) + else: + pos += 1 + expect("punct", ")") + steps.append(("instance",)) + return steps -foreign_key_parser = build_foreign_key_parser() -reference_parser = build_reference_parser() -attribute_parser = build_attribute_parser() + steps = reference() + if pos < len(tokens): + raise ValueError(f"unexpected {tokens[pos][1]!r}") + return steps def resolve_foreign_key_reference(ref_table: str, context: dict): """ Resolve the table reference of a foreign key line in a namespace. - The reference is parsed, never evaluated: it must be a dotted name looked up - in ``context`` attribute by attribute, optionally instantiated with ``()`` - or projected with ``.proj(...)`` whose arguments are string literals. + The reference is parsed by :func:`parse_foreign_key_reference`, never + evaluated: names are looked up in ``context`` attribute by attribute, a + table class may be instantiated with ``()``, and ``.proj(...)`` is called + with the parsed string arguments. Parameters ---------- @@ -225,51 +336,47 @@ def resolve_foreign_key_reference(ref_table: str, context: dict): from .expression import QueryExpression from .table import Table + text = ref_table.strip() + + def unresolved(reason): + return DataJointError(f"Foreign key reference {text} could not be resolved: {reason}") + + def is_table_class(obj): + return isinstance(obj, type) and issubclass(obj, Table) + try: - parsed = reference_parser.parse_string(ref_table.strip()) - except pp.ParseException: - raise DataJointError( - 'Foreign key reference "%s" is not supported. Use a table name such as ' - "Parent, module.Parent or Master.Part, optionally projected with " - "Parent.proj(new_name='old_name')." % ref_table.strip() - ) from None - path = list(parsed.name) - call = parsed.get("call") - if any(part.startswith("__") for part in path): - raise DataJointError('Foreign key reference "%s" is not supported.' % ref_table.strip()) - method = None - if call is not None and len(path) > 1 and path[-1] == "proj": - method = path.pop() - elif call is not None and len(call): - raise DataJointError( - 'Foreign key reference "%s" is not supported. Only .proj() may take arguments.' % ref_table.strip() - ) - if path[0] not in context: - raise DataJointError("Foreign key reference %s could not be resolved" % ref_table.strip()) - ref = context[path[0]] - for part in path[1:]: - try: - ref = getattr(ref, part) - except Exception: - raise DataJointError("Foreign key reference %s could not be resolved" % ref_table.strip()) from None - if not (isinstance(ref, QueryExpression) or (isinstance(ref, type) and issubclass(ref, Table))): - raise DataJointError("Foreign key reference %s does not name a table" % ref_table.strip()) - if call is None: - return ref - if method is None: # Parent() - if not isinstance(ref, type): - raise DataJointError('Foreign key reference "%s" is not supported.' % ref_table.strip()) - return ref() - if isinstance(ref, type): - ref = ref() - args = [arg[0] for arg in call if len(arg) == 1] - kwargs = {arg[0]: arg[1] for arg in call if len(arg) == 2} - try: - return ref.proj(*args, **kwargs) - except DataJointError: - raise - except Exception as error: - raise DataJointError("Foreign key reference %s could not be resolved: %s" % (ref_table.strip(), error)) from None + steps = parse_foreign_key_reference(text) + except ValueError as error: + raise unresolved(f"{error}; {_REFERENCE_FORMS}") from None + ref = None + for step in steps: + if step[0] == "name": + if step[1] not in context: + raise unresolved(f"{step[1]} is not defined in the declaration context") + ref = context[step[1]] + elif step[0] == "attr": + try: + ref = getattr(ref, step[1]) + except Exception: + raise unresolved(f"no attribute {step[1]}") from None + elif step[0] == "instance": + if not is_table_class(ref): + raise unresolved(f"only a table class can be instantiated; {_REFERENCE_FORMS}") + ref = ref() + else: # proj + if is_table_class(ref): + ref = ref() + if not isinstance(ref, QueryExpression): + raise unresolved("only a table can be projected") + try: + ref = ref.proj(*step[1], **step[2]) + except DataJointError: + raise + except Exception as error: + raise unresolved(str(error)) from None + if not (isinstance(ref, QueryExpression) or is_table_class(ref)): + raise unresolved("it does not name a table") + return ref def is_foreign_key(line: str) -> bool: diff --git a/src/datajoint/table.py b/src/datajoint/table.py index 9cef804cc..dd6e979f8 100644 --- a/src/datajoint/table.py +++ b/src/datajoint/table.py @@ -1372,7 +1372,7 @@ def describe(self, context=None, printout=False): self.connection.dependencies.load() parents = self.parents(foreign_key_info=True) in_key = True - table_comment = _one_line_comment(self.heading.table_status["comment"]) + table_comment = _one_line(self.heading.table_status["comment"]) definition = "# " + table_comment + "\n" if table_comment else "" attributes_thus_far = set() attributes_declared = set() @@ -1410,15 +1410,15 @@ def describe(self, context=None, printout=False): # simple foreign key definition += "->{options} {class_name}\n".format( options=options_str, - class_name=_definition_token(lookup_class_name(parent_name, context) or parent_name), + class_name=_one_line(lookup_class_name(parent_name, context) or parent_name), ) else: # projected foreign key definition += "->{options} {class_name}.proj({proj_list})\n".format( options=options_str, - class_name=_definition_token(lookup_class_name(parent_name, context) or parent_name), + class_name=_one_line(lookup_class_name(parent_name, context) or parent_name), proj_list=",".join( - '{}="{}"'.format(_attribute_name(attr), _attribute_name(ref)) + "{}={}".format(_one_line(attr), _quoted(ref)) for attr, ref in fk_props["attr_map"].items() if ref != attr ), @@ -1428,17 +1428,17 @@ def describe(self, context=None, printout=False): attributes_declared.add(attr.name) # Use original_type (core type alias) if available, otherwise use type display_type = attr.original_type or attr.type - attr_name = _attribute_name(attr.name) - attr_comment = _one_line_comment(attr.comment) + attr_name = _one_line(attr.name) + attr_comment = _one_line(attr.comment) definition += "%-20s : %-28s %s\n" % ( - (attr_name if attr.default is None else "%s=%s" % (attr_name, _definition_token(str(attr.default)))), - "%s%s" % (_definition_token(display_type), " auto_increment" if attr.autoincrement else ""), + (attr_name if attr.default is None else "%s=%s" % (attr_name, _one_line(str(attr.default)))), + "%s%s" % (_one_line(display_type), " auto_increment" if attr.autoincrement else ""), "# " + attr_comment if attr_comment else "", ) # add remaining indexes for k, v in indexes.items(): definition += "{unique}INDEX ({attrs})\n".format( - unique="UNIQUE " if v["unique"] else "", attrs=", ".join(_attribute_name(a) for a in k) + unique="UNIQUE " if v["unique"] else "", attrs=", ".join(_one_line(a) for a in k) ) if printout: logger.info("\n" + definition) @@ -1671,26 +1671,14 @@ def check_fields(fields): return row_to_insert -_ATTRIBUTE_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") +def _one_line(text): + """Return ``text`` with line breaks replaced, so it stays on its line of a definition.""" + return re.sub(r"[\r\n]+", " ", text) if text else text -def _attribute_name(name): - """Return ``name`` for a definition string, requiring a plain identifier.""" - if not _ATTRIBUTE_NAME.fullmatch(name): - raise DataJointError(f"Attribute name {name!r} cannot be written in a table definition.") - return name - - -def _definition_token(text): - """Return ``text`` for a definition string, requiring that it stays on one line.""" - if "\n" in text or "\r" in text: - raise DataJointError(f"{text!r} cannot be written in a table definition.") - return text - - -def _one_line_comment(comment): - """Return ``comment`` with line breaks replaced so it stays a single comment line.""" - return re.sub(r"[\r\n]+", " ", comment) if comment else comment +def _quoted(text): + """Return ``text`` as a double-quoted string literal on one line.""" + return '"{}"'.format(_one_line(text).replace("\\", "\\\\").replace('"', '\\"')) def lookup_class_name(name, context, depth=3): diff --git a/tests/integration/test_alter.py b/tests/integration/test_alter.py index bf0939cc7..2bbfaaa5e 100644 --- a/tests/integration/test_alter.py +++ b/tests/integration/test_alter.py @@ -177,19 +177,25 @@ def test_alter_projected_foreign_key(pipeline): assert pipeline.Link.heading.secondary_attributes == ["weight"] -def test_alter_reads_catalog_text_as_data(pipeline, tmp_path): - """Text stored in the catalog is reproduced by describe() as data, never run by alter().""" - marker = tmp_path / "marker" +def test_alter_reads_catalog_text_as_data(pipeline): + """Text stored in the catalog is reproduced by describe() on one line and only read by alter().""" + calls = [] + + def record(): + calls.append(True) + return pipeline.Item + + context = dict(vars(pipeline), record=record) table = pipeline.Item() - comment = f"note\n-> __import__('pathlib').Path({str(marker)!r}).touch()" + comment = "note\n-> record()" if table.connection.adapter.backend == "postgresql": sql = f"COMMENT ON TABLE {table.full_table_name} IS %s" else: sql = f"ALTER TABLE {table.full_table_name} COMMENT = %s" table.connection.query(sql, args=(comment,)) table.__class__._heading = dj.heading.Heading(table_info=table.heading.table_info) - described = table.describe(context=vars(pipeline)) - assert described.splitlines()[0].startswith("# note -> __import__") + described = table.describe(context=context) + assert described.splitlines()[0] == "# note -> record()" # keep the comment unchanged so that only the new attribute is altered table.definition = ( described.splitlines()[0] @@ -199,6 +205,18 @@ def test_alter_reads_catalog_text_as_data(pipeline, tmp_path): label = "" : varchar(16) """ ) - table.alter(prompt=False) - assert not marker.exists() + table.alter(prompt=False, context=context) + assert calls == [] assert table.heading.secondary_attributes == ["label"] + + +def test_alter_unresolved_parent(pipeline): + """A parent that is not in the context is reported as unresolved.""" + pipeline.Measurement.definition = """ + -> Item + --- + value : float32 + unit = "" : varchar(16) + """ + with pytest.raises(dj.DataJointError, match="could not be resolved"): + pipeline.Measurement.alter(prompt=False, context={}) diff --git a/tests/integration/test_declare.py b/tests/integration/test_declare.py index d0b904df1..92ff2b446 100644 --- a/tests/integration/test_declare.py +++ b/tests/integration/test_declare.py @@ -353,7 +353,7 @@ class WithSuchALongPartNameThatItCrashesMySQL(dj.Part): -> (master) """ - with pytest.raises(dj.DataJointError): + with pytest.raises(dj.DataJointError, match="exceeds the max length"): schema_any(WhyWouldAnyoneCreateATableNameThisLong) diff --git a/tests/unit/test_blob_decompression.py b/tests/unit/test_blob_decompression.py index 876f03d1f..9bca71928 100644 --- a/tests/unit/test_blob_decompression.py +++ b/tests/unit/test_blob_decompression.py @@ -1,5 +1,6 @@ """Compressed blobs expand only up to the size their header declares.""" +import tracemalloc import zlib import numpy as np @@ -27,13 +28,18 @@ def test_round_trip_uncompressed(): assert unpack(pack({"a": [1, 2, 3]}, compress=False)) == {"a": [1, 2, 3]} -def test_payload_larger_than_declared_size_is_rejected(): - # a small header in front of ~100 MB of zeros that compress to ~100 kB +def test_payload_larger_than_declared_size_is_rejected_without_expanding_it(): + # a short declared size in front of ~100 MB of zeros that compress to ~100 kB inner = pack(b"x", compress=False) - payload = inner + bytes(100_000_000) - blob = compressed_blob(payload, declared_size=len(inner)) - with pytest.raises(DataJointError, match="size mismatch"): - unpack(blob) + blob = compressed_blob(inner + bytes(100_000_000), declared_size=len(inner)) + tracemalloc.start() + try: + with pytest.raises(DataJointError, match="size mismatch"): + unpack(blob) + _, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + assert peak < 10_000_000 def test_payload_smaller_than_declared_size_is_rejected(): diff --git a/tests/unit/test_foreign_key_reference.py b/tests/unit/test_foreign_key_reference.py index 89c36a039..8d4656699 100644 --- a/tests/unit/test_foreign_key_reference.py +++ b/tests/unit/test_foreign_key_reference.py @@ -1,10 +1,10 @@ """Foreign key references are parsed and looked up, never evaluated. The text after ``->`` names a table in the declaration context: a dotted name -(``Parent``, ``module.Parent``, ``Master.Part``), optionally projected with -``.proj(new_name="old_name")``. ``Table.alter`` re-parses the definition that -``describe()`` builds from names read back from the database catalog, so that -text must not be able to do anything but name a table. +(``Parent``, ``module.Parent``, ``Master.Part``), optionally in parentheses, +instantiated with ``()``, or projected with ``.proj(new_name="old_name")``. +``Table.alter`` re-parses the definition that ``describe()`` builds from names +read back from the database catalog, so that text is only ever read as a name. """ import types @@ -13,9 +13,9 @@ import datajoint as dj from datajoint.adapters.mysql import MySQLAdapter -from datajoint.declare import prepare_declare, resolve_foreign_key_reference +from datajoint.declare import parse_foreign_key_reference, prepare_declare, resolve_foreign_key_reference from datajoint.errors import DataJointError -from datajoint.table import _attribute_name, _definition_token, _one_line_comment +from datajoint.table import _one_line, _quoted class Parent(dj.Manual): @@ -30,8 +30,41 @@ class Part(dj.Part): """ +class Projectable(dj.Manual): + """Records the arguments of proj() instead of building a projection.""" + + definition = """ + projectable_id : int32 + """ + + def proj(self, *args, **kwargs): + self.proj_args = (args, kwargs) + return self + + module = types.SimpleNamespace(Parent=Parent) -CONTEXT = {"Parent": Parent, "module": module, "master": Parent, "os": __import__("os")} + + +@pytest.fixture +def calls(): + return [] + + +@pytest.fixture +def context(calls): + def record(*args, **kwargs): + calls.append((args, kwargs)) + return Parent + + return { + "Parent": Parent, + "Projectable": Projectable, + "module": module, + "master": Parent, + "Größe": Parent, + "record": record, + "__builtins__": __builtins__, + } @pytest.mark.parametrize( @@ -42,73 +75,98 @@ class Part(dj.Part): ("module.Parent", Parent), ("Parent.Part", Parent.Part), ("master.Part", Parent.Part), + ("(master)", Parent), + ("(module.Parent).Part", Parent.Part), + ("Größe", Parent), ("Parent # a trailing comment", Parent), ], ) -def test_dotted_names_resolve(reference, expected): - assert resolve_foreign_key_reference(reference, CONTEXT) is expected +def test_dotted_names_resolve(reference, expected, context): + assert resolve_foreign_key_reference(reference, context) is expected + + +def test_instantiation(context): + assert isinstance(resolve_foreign_key_reference("Parent()", context), Parent) + + +@pytest.mark.parametrize( + "reference, args, kwargs", + [ + ("Projectable.proj(new_id='projectable_id')", (), {"new_id": "projectable_id"}), + ('Projectable().proj(a="b", c="d",)', (), {"a": "b", "c": "d"}), + ("(Projectable).proj('x', a='b')", ("x",), {"a": "b"}), + (r'Projectable.proj(a="say \"hi\"")', (), {"a": 'say "hi"'}), + ], +) +def test_projection_arguments_are_string_literals(reference, args, kwargs, context): + ref = resolve_foreign_key_reference(reference, context) + assert ref.proj_args == (args, kwargs) @pytest.mark.parametrize( "reference", [ - "__import__('os').system('true')", - "os.system('true')", - "Parent.proj(x=__import__('os').getcwd())", - "Parent.proj(x=y)", - "Parent.proj(**{'a': 'b'})", + "record()", + "(record)()", + "module.Parent.proj(x=record())", + "Parent.proj(**record())", + "Parent.proj(x=record)", + "Parent.proj(x=f'{record()}')", + "[record() for _ in 'a']", + "Parent; record()", + "Parent or record()", + "lambda: record()", + "Parent.delete()", + "Parent.Part('x')", "Parent.Part.__init__.__globals__", "Parent.__class__", - "[c for c in ().__class__.__base__.__subclasses__()]", - "Parent; import os", + "__builtins__", + "__builtins__.open", "Parent & 'parent_id=1'", - "lambda: 0", - "`schema`.`parent`", - '"schema"."parent"', - "Parent.delete()", - "Parent.Part('x')", + "Parent.proj(a='b', 'c')", + "Parent.proj(a='b', a='c')", "", ], ) -def test_expressions_are_rejected(reference, monkeypatch): - def fail(*args, **kwargs): - raise AssertionError("reference text was executed") +def test_other_forms_are_refused(reference, context, calls): + with pytest.raises(DataJointError, match="could not be resolved"): + resolve_foreign_key_reference(reference, context) + assert calls == [] + - monkeypatch.setattr("os.system", fail) - with pytest.raises(DataJointError): - resolve_foreign_key_reference(reference, CONTEXT) +@pytest.mark.parametrize("reference", ["Missing", "module.Missing", "`schema`.`parent`", '"schema"."parent"']) +def test_unknown_names_could_not_be_resolved(reference, context): + with pytest.raises(DataJointError, match="could not be resolved"): + resolve_foreign_key_reference(reference, context) -@pytest.mark.parametrize("reference", ["os", "os.getcwd", "module", "Missing", "module.Missing"]) -def test_non_tables_are_rejected(reference): - with pytest.raises(DataJointError): - resolve_foreign_key_reference(reference, CONTEXT) +@pytest.mark.parametrize("reference", ["module", "record", "types", "Parent.describe"]) +def test_non_tables_are_refused(reference, context): + with pytest.raises(DataJointError, match="does not name a table|is not defined"): + resolve_foreign_key_reference(reference, context) -def test_resolution_reads_no_builtins(): +def test_resolution_leaves_context_unchanged(context): """eval() would add __builtins__ to the context it is given; lookup does not.""" - context = dict(CONTEXT) + del context["__builtins__"] resolve_foreign_key_reference("Parent", context) assert "__builtins__" not in context -def test_definition_with_crafted_reference_is_rejected(): +def test_definition_reference_is_not_called(context, calls): definition = """ - -> __import__('os').system('true') + -> record() id : int32 """ - with pytest.raises(DataJointError, match="not supported"): - prepare_declare(definition, dict(CONTEXT), MySQLAdapter()) - - -def test_describe_helpers(): - assert _attribute_name("subject_id") == "subject_id" - assert _attribute_name("_hidden") == "_hidden" - for name in ['a"); x', "a b", "a\nb", "", "1a"]: - with pytest.raises(DataJointError): - _attribute_name(name) - assert _definition_token("`s`.`t`") == "`s`.`t`" - with pytest.raises(DataJointError): - _definition_token("Parent\n-> other") - assert _one_line_comment("first\nsecond\r\nthird") == "first second third" - assert _one_line_comment("") == "" + with pytest.raises(DataJointError, match="could not be resolved"): + prepare_declare(definition, context, MySQLAdapter()) + assert calls == [] + + +def test_describe_text_stays_on_one_line(): + assert _one_line("first\nsecond\r\nthird") == "first second third" + assert _one_line("") == "" + assert _one_line(None) is None + text = 'a "quoted" \\ value\nwith a line break' + steps = parse_foreign_key_reference("Parent.proj(new={})".format(_quoted(text))) + assert steps == [("name", "Parent"), ("proj", [], {"new": _one_line(text)})] From f5ec0877517a3889fd54143f02734cb89f50be85 Mon Sep 17 00:00:00 2001 From: TheeCoderAhmed Date: Tue, 10 Nov 2026 12:36:41 +0300 Subject: [PATCH 28/37] test: check full_path matches the backend URL for trailing-slash locations The reviewer asked for a case that pins the trailing-slash location. It asserts that full_path equals what the backend builds for reads and writes, so it holds whether or not _full_path ever normalizes the slash. --- tests/unit/test_objectref.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/unit/test_objectref.py b/tests/unit/test_objectref.py index f0e70220a..ac3f4d316 100644 --- a/tests/unit/test_objectref.py +++ b/tests/unit/test_objectref.py @@ -36,3 +36,18 @@ def test_full_path_includes_store_location(spec, prefix): """full_path points where the backend stores the object, location included.""" ref = _object_ref(spec) assert ref.full_path == prefix + ref.path + + +@pytest.mark.parametrize( + "spec", + [ + {"protocol": "s3", "endpoint": "localhost:9000", "bucket": "bkt", "location": "proj/outbox"}, + {"protocol": "s3", "endpoint": "localhost:9000", "bucket": "bkt", "location": "proj/outbox/"}, + {"protocol": "gcs", "bucket": "bkt", "location": "proj/"}, + {"protocol": "azure", "container": "ctr", "location": "proj/"}, + ], +) +def test_full_path_matches_backend_url(spec): + """full_path is the URL the backend reads and writes, whatever shape location has.""" + ref = _object_ref(spec) + assert ref.full_path == ref._backend.get_url(ref.path) From 90297163ca0e0ee2be07250938a6cdbb62d74618 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Thu, 12 Nov 2026 13:56:08 -0600 Subject: [PATCH 29/37] fix(config): skip the directory warning for sticky shared secrets directories A world-writable secrets directory with the sticky bit, such as a Kubernetes secret volume mounted at /run/secrets/datajoint, no longer produces a "writable by all users" warning: each file in it is still checked when read. A world-writable secrets directory without the sticky bit still warns. Tests also cover running as root, another user's datajoint.json in a world-writable directory without the sticky bit, and a named pipe in place of a secret file. --- src/datajoint/settings.py | 6 ++- tests/unit/test_settings.py | 74 +++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 2 deletions(-) diff --git a/src/datajoint/settings.py b/src/datajoint/settings.py index c6ccd65fe..350efa8e3 100644 --- a/src/datajoint/settings.py +++ b/src/datajoint/settings.py @@ -223,7 +223,9 @@ def _use_found_dir(path: Path, hint: str = "") -> bool: Decide whether a secrets directory found by searching may be used. The rules of ``_read_found_file`` apply to the directory. The files in a - directory that is used are each checked again when read. + directory that is used are each checked again when read. For that reason a + world-writable directory with the sticky bit (such as a Kubernetes secret + volume) produces no warning; one without it does. """ if not hasattr(os, "getuid"): return path.is_dir() @@ -241,7 +243,7 @@ def _use_found_dir(path: Path, hint: str = "") -> bool: if _is_foreign(st.st_uid): if _reject_foreign(path, st.st_uid, [found_in, Path(os.path.realpath(path)).parent], hint): return False - if st.st_mode & stat.S_IWOTH: + if st.st_mode & stat.S_IWOTH and not st.st_mode & stat.S_ISVTX: logger.warning(f"{path} is writable by all users; restrict its permissions (e.g. chmod o-w).") return True diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index 1473a6438..7e42fa92a 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -1,6 +1,7 @@ """Tests for DataJoint settings module.""" import os +import signal import stat import warnings from pathlib import Path @@ -1292,6 +1293,13 @@ def test_foreign_config_below_non_sticky_world_writable_dir_skipped(self, mark, assert find_config_file(lab / "project") is None + def test_foreign_config_in_non_sticky_world_writable_dir_skipped(self, mark, shared): + """Another user's datajoint.json in a directory anyone can write (e.g. a 0777 volume) is skipped.""" + mark(shared, world_writable=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + assert find_config_file(shared / "project") is None + def test_foreign_config_in_protected_dir_used(self, mark, shared): """Another user's file in a directory only its owners can write (e.g. a lab share) is used.""" mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) @@ -1304,6 +1312,20 @@ def test_root_owned_config_in_world_writable_dir_used(self, mark, shared): assert find_config_file(shared / "project") == shared / CONFIG_FILENAME + def test_foreign_config_in_world_writable_dir_skipped_as_root(self, mark, shared, monkeypatch): + """Running as root does not make another user's file in a world-writable directory trusted.""" + monkeypatch.setattr(os, "getuid", lambda: 0) + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + assert find_config_file(shared / "project") is None + + def test_foreign_config_in_protected_dir_used_as_root(self, mark, shared, monkeypatch): + monkeypatch.setattr(os, "getuid", lambda: 0) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + assert find_config_file(shared / "project") == shared / CONFIG_FILENAME + def test_own_config_in_world_writable_dir_used(self, mark, shared, caplog): mark(shared, world_writable=True, sticky=True) @@ -1386,6 +1408,58 @@ def test_foreign_secret_file_in_world_writable_secrets_dir_skipped(self, mark, t assert cfg.database.password is None assert "main" not in cfg.stores + def test_root_owned_sticky_system_secrets_dir_used_without_warning(self, mark, tmp_path, monkeypatch, caplog): + """A Kubernetes secret volume (root-owned, mode 1777) is used; only the files in it are checked.""" + secrets_dir = tmp_path / "system-secrets" + secrets_dir.mkdir() + (secrets_dir / "database.password").write_text("from-root") + monkeypatch.setattr(settings, "SYSTEM_SECRETS_DIR", secrets_dir) + mark(secrets_dir, uid=0, world_writable=True, sticky=True) + mark(secrets_dir / "database.password", uid=0) + + with caplog.at_level("WARNING", logger="datajoint"): + found = find_secrets_dir(None) + value = read_secret_file(found, "database.password") + + assert found == secrets_dir + assert value == "from-root" + assert not any("writable by all users" in r.message for r in caplog.records) + + def test_root_owned_non_sticky_system_secrets_dir_warns(self, mark, tmp_path, monkeypatch, caplog): + secrets_dir = tmp_path / "system-secrets" + secrets_dir.mkdir() + (secrets_dir / "database.password").write_text("from-root") + monkeypatch.setattr(settings, "SYSTEM_SECRETS_DIR", secrets_dir) + mark(secrets_dir, uid=0, world_writable=True) + mark(secrets_dir / "database.password", uid=0) + + with caplog.at_level("WARNING", logger="datajoint"): + found = find_secrets_dir(None) + value = read_secret_file(found, "database.password") + + assert found == secrets_dir + assert value == "from-root" + assert any(str(secrets_dir) in r.message and "writable by all users" in r.message for r in caplog.records) + + def test_fifo_secret_file_not_read(self, tmp_path): + """A named pipe in place of a secret file is skipped without waiting for a writer.""" + secrets_dir = tmp_path / SECRETS_DIRNAME + secrets_dir.mkdir() + os.mkfifo(secrets_dir / "database.password") + + def blocked(signum, frame): + pytest.fail("opening the named pipe blocked") + + previous = signal.signal(signal.SIGALRM, blocked) + signal.alarm(5) + try: + value = read_secret_file(secrets_dir, "database.password") + finally: + signal.alarm(0) + signal.signal(signal.SIGALRM, previous) + + assert value is None + def test_no_posix_ownership_keeps_search(self, mark, shared, monkeypatch): """Without os.getuid (Windows) the search behaves as before.""" mark(shared, world_writable=True, sticky=True) From 1c3a6df8c1a9d44a12ab948bce889a1af03971ce Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Thu, 12 Nov 2026 13:57:03 -0600 Subject: [PATCH 30/37] Use database.use_tls in dj.Instance and dj.Connection when use_tls is not given Connection now falls back to database.use_tls (DJ_USE_TLS) from its config when use_tls is None, as dj.conn and Schema already did. This covers dj.Instance, which passes its own config, and a direct dj.Connection. An explicit use_tls argument still wins. The docstrings for an existing connection now say it is reconnected with the requested TLS settings unless it already satisfies them. --- src/datajoint/__init__.py | 6 +++--- src/datajoint/connection.py | 15 +++++++++------ src/datajoint/instance.py | 3 ++- tests/unit/test_tls.py | 24 ++++++++++++++++++++++-- 4 files changed, 36 insertions(+), 12 deletions(-) diff --git a/src/datajoint/__init__.py b/src/datajoint/__init__.py index 7a514674a..df7577042 100644 --- a/src/datajoint/__init__.py +++ b/src/datajoint/__init__.py @@ -137,8 +137,8 @@ def conn( TLS encryption option: True (required), False (no TLS), None (from config; TLS if the server supports it by default), or dict (TLS required; ``ca``, ``cert``, ``key``; with ``ca``, the server - certificate is verified). If the singleton connection exists and was - made with weaker TLS settings, it is reconnected with these. + certificate is verified). If the singleton connection exists, it is + reconnected with these unless it already satisfies them. Returns ------- @@ -158,7 +158,7 @@ def conn( # If reset requested, always recreate # If credentials or use_tls provided and no singleton exists, create one # If credentials provided and singleton exists, return existing singleton, - # reconnected if use_tls asks for stronger TLS than it was made with + # reconnected with use_tls unless it already satisfies use_tls if reset or ( instance_module._singleton_connection is None and (host is not None or user is not None or password is not None or use_tls is not None) diff --git a/src/datajoint/connection.py b/src/datajoint/connection.py index 58a4bd523..1ac607653 100644 --- a/src/datajoint/connection.py +++ b/src/datajoint/connection.py @@ -81,8 +81,8 @@ def conn( TLS encryption option: True (required), False (no TLS), None (preferred, default), or dict for manual configuration (TLS required; ``ca``, ``cert``, ``key``; with ``ca``, the server - certificate is verified). If the existing connection was made with - weaker TLS settings, it is reconnected with these. + certificate is verified). The existing connection is reconnected with + these unless it already satisfies them. Returns ------- @@ -168,9 +168,10 @@ class Connection: Port number. Overridden if specified in host. use_tls : bool or dict, optional TLS encryption option: True (required), False (no TLS), - None (preferred, default), or dict for manual configuration - (TLS required; ``ca``, ``cert``, ``key``; with ``ca``, the server - certificate is verified). + None (default; ``database.use_tls`` from config, and TLS if the + server supports it when that is unset), or dict for manual + configuration (TLS required; ``ca``, ``cert``, ``key``; with ``ca``, + the server certificate is verified). Attributes ---------- @@ -204,6 +205,8 @@ def __init__( if database_name is None: database_name = self._config.get("database.name") self.conn_info = dict(host=host, port=port, user=user, passwd=password, database_name=database_name) + if use_tls is None: + use_tls = self._config["database.use_tls"] self._set_use_tls(use_tls) self._conn = None self._query_cache = None @@ -264,7 +267,7 @@ def _set_use_tls(self, use_tls: bool | dict | None) -> None: def _ensure_tls(self, use_tls: bool | dict | None) -> None: """ - Reconnect with ``use_tls`` if the connection was made with weaker TLS settings. + Reconnect with ``use_tls`` unless the existing connection already satisfies it. ``use_tls=True`` is met by a connection made with True or a dict; a dict is met only by a connection made with the same dict. diff --git a/src/datajoint/instance.py b/src/datajoint/instance.py index 455336a7c..eb3c3f6d0 100644 --- a/src/datajoint/instance.py +++ b/src/datajoint/instance.py @@ -56,7 +56,8 @@ class Instance: port : int, optional Database port. Defaults to 3306 for MySQL, 5432 for PostgreSQL. use_tls : bool or dict, optional - TLS configuration. + TLS configuration. Default from ``database.use_tls`` in this + instance's config. backend : str, optional Database backend: ``"mysql"`` or ``"postgresql"``. Default from config. **kwargs : Any diff --git a/tests/unit/test_tls.py b/tests/unit/test_tls.py index a5a1acfb2..e4a0fbb04 100644 --- a/tests/unit/test_tls.py +++ b/tests/unit/test_tls.py @@ -416,12 +416,13 @@ def dj(): @pytest.fixture def adapter(monkeypatch, dj): - """Mock adapter returned by get_adapter for every Connection.""" + """Mock adapter returned by get_adapter for every Connection, with database.use_tls unset.""" adapter = mock.Mock(name="adapter") adapter.backend = "postgresql" # skips the MySQL server-version query adapter.get_connection_id.return_value = 1 monkeypatch.setattr(importlib.import_module("datajoint.connection"), "get_adapter", lambda backend: adapter) - return adapter + with dj.config.override(database__use_tls=None): # DJ_USE_TLS must not change the None cases + yield adapter def _use_tls_calls(adapter): @@ -434,6 +435,25 @@ def test_use_tls_reaches_adapter(self, dj, adapter, use_tls): dj.Connection("localhost", "alice", "secret", 5432, use_tls) assert _use_tls_calls(adapter) == [use_tls] + def test_use_tls_from_config(self, dj, adapter): + with dj.config.override(database__use_tls=True): + dj.Connection("localhost", "alice", "secret", 5432) + assert _use_tls_calls(adapter) == [True] + + def test_use_tls_argument_overrides_config(self, dj, adapter): + with dj.config.override(database__use_tls=True): + dj.Connection("localhost", "alice", "secret", 5432, False) + assert _use_tls_calls(adapter) == [False] + + @pytest.mark.parametrize("use_tls", [True, False]) + def test_instance_use_tls_from_config(self, dj, adapter, use_tls): + dj.Instance("localhost", "alice", "secret", database__use_tls=use_tls) + assert _use_tls_calls(adapter) == [use_tls] + + def test_instance_use_tls_argument_overrides_config(self, dj, adapter): + dj.Instance("localhost", "alice", "secret", use_tls=False, database__use_tls=True) + assert _use_tls_calls(adapter) == [False] + def test_reconnect_keeps_use_tls(self, dj, adapter): connection = dj.Connection("localhost", "alice", "secret", 5432, False) connection.connect() From 4845bbdecd9024d201471ef48c95ac95d9c9ad44 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Thu, 12 Nov 2026 13:57:47 -0600 Subject: [PATCH 31/37] Keep restriction literals closed under other string-escaping settings - MySQL string literals double single quotes ('') instead of writing \', so a literal stays closed even if the session's sql_mode includes NO_BACKSLASH_ESCAPES. The value read back in the default sql_mode is unchanged. - On PostgreSQL, a list value whose text contains a backslash is rendered as an E'...' literal, which reads the same whether or not standard_conforming_strings is on. Plain string and JSON object values are rendered as before. --- src/datajoint/adapters/mysql.py | 4 +-- src/datajoint/condition.py | 8 ++++- tests/integration/test_restriction_values.py | 29 +++++++++++++++ tests/unit/test_adapters.py | 2 ++ tests/unit/test_condition.py | 37 +++++++++++++++++--- 5 files changed, 72 insertions(+), 8 deletions(-) diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index 3802007d3..14a99bb0a 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -219,8 +219,8 @@ def quote_string(self, value: str) -> str: str Quoted and escaped string literal. """ - # Use pymysql's escape_string for proper escaping - escaped = client.converters.escape_string(value) + # Use pymysql's escape_string, but double quotes so the literal stays closed even under NO_BACKSLASH_ESCAPES + escaped = client.converters.escape_string(value).replace("\\'", "''") return f"'{escaped}'" def get_master_table_name(self, part_table: str) -> str | None: diff --git a/src/datajoint/condition.py b/src/datajoint/condition.py index 47b2e9c60..e07ac1943 100644 --- a/src/datajoint/condition.py +++ b/src/datajoint/condition.py @@ -390,7 +390,13 @@ def prep_value(k, v): list, ), ): - return f"{k}={literal(str(v))}" + text = str(v) + if isinstance(v, list) and adapter.backend == "postgresql" and "\\" in text: + # An E'' literal reads backslashes the same way whether or not + # standard_conforming_strings is on. + escaped = text.replace("\\", "\\\\").replace("'", "''").replace("%", "%%") + return f"{k}=E'{escaped}'" + return f"{k}={literal(text)}" if isinstance(v, str): if adapter.backend == "postgresql": # Backslashes are doubled as in previous releases so that string diff --git a/tests/integration/test_restriction_values.py b/tests/integration/test_restriction_values.py index bd9a8c86b..94c793209 100644 --- a/tests/integration/test_restriction_values.py +++ b/tests/integration/test_restriction_values.py @@ -126,6 +126,35 @@ def test_string_with_backslash(item, backend): assert ids(item & {"data.label": "back\\slash"}) == [5] +def test_mysql_values_without_backslash_escapes(item, backend): + """On MySQL, string values stay closed literals when the session enables NO_BACKSLASH_ESCAPES.""" + if backend != "mysql": + pytest.skip("sql_mode is MySQL-specific") + connection = item.connection + sql_mode = connection.query("SELECT @@SESSION.sql_mode").fetchone()[0] + try: + connection.query("SET SESSION sql_mode = %s", (",".join(filter(None, [sql_mode, "NO_BACKSLASH_ESCAPES"])),)) + assert ids(item & {"name": "' OR 1=1 --"}) == [] + assert ids(item & {"name": "o'brien"}) == [2] + finally: + connection.query("SET SESSION sql_mode = %s", (sql_mode,)) + + +def test_postgresql_list_values_without_standard_conforming_strings(item, backend): + """On PostgreSQL, list values stay closed literals when standard_conforming_strings is off.""" + if backend != "postgresql": + pytest.skip("standard_conforming_strings is PostgreSQL-specific") + item.insert1(dict(item_id=5, name=str(["back\\slash"]))) + connection = item.connection + setting = connection.query("SHOW standard_conforming_strings").fetchone()[0] + try: + connection.query("SET standard_conforming_strings = off") + assert ids(item & {"name": ["'OR 1=1 -- \""]}) == [] + assert ids(item & {"name": ["back\\slash"]}) == [5] + finally: + connection.query(f"SET standard_conforming_strings = {setting}") + + NUMERIC_JSON_TYPES = { "mysql": ["unsigned", "signed", "decimal(4, 1)", "double", "float"], "postgresql": ["integer", "int", "bigint", "numeric(10,2)", "double precision", "real", "unsigned", "double"], diff --git a/tests/unit/test_adapters.py b/tests/unit/test_adapters.py index 1e0678150..bcfe6a612 100644 --- a/tests/unit/test_adapters.py +++ b/tests/unit/test_adapters.py @@ -75,6 +75,8 @@ def test_quote_string(self, adapter): # Should handle escaping result = adapter.quote_string("It's a test") assert "It" in result + # Quotes are doubled, not backslash-escaped + assert adapter.quote_string("It's") == "'It''s'" def test_core_type_to_sql_simple(self, adapter): """Test core type mapping for simple types.""" diff --git a/tests/unit/test_condition.py b/tests/unit/test_condition.py index 9d26ecfb8..e5cfdebac 100644 --- a/tests/unit/test_condition.py +++ b/tests/unit/test_condition.py @@ -188,18 +188,26 @@ def _condition(backend, restriction): return make_condition(_fake_expression(backend), restriction, set()) -def _read_literal(backend, sql): +def _read_literal(backend, sql, backslash_escapes=None): """ Read one quoted string literal at the start of ``sql`` using the backend's rules - (MySQL with backslash escapes; PostgreSQL with standard_conforming_strings on). + (MySQL with backslash escapes; PostgreSQL with standard_conforming_strings on, + where backslashes are escapes only in an E'...' literal). + + ``backslash_escapes=False`` reads a MySQL literal as under NO_BACKSLASH_ESCAPES; + ``backslash_escapes=True`` reads a PostgreSQL literal as with standard_conforming_strings off. Returns the literal's value and the text that follows it. """ + if backslash_escapes is None: + backslash_escapes = backend == "mysql" + if backend == "postgresql" and sql.startswith("E'"): + sql, backslash_escapes = sql[1:], True assert sql[0] == "'", sql out, i = [], 1 while i < len(sql): c = sql[i] - if c == "\\" and backend == "mysql": + if c == "\\" and backslash_escapes: nxt = sql[i + 1] out.append({"n": "\n", "r": "\r", "0": "\x00", "Z": "\x1a", "t": "\t", "b": "\b"}.get(nxt, nxt)) i += 2 @@ -215,12 +223,12 @@ def _read_literal(backend, sql): raise AssertionError(f"unterminated literal in {sql!r}") -def _literal_value(backend, condition, lhs): +def _literal_value(backend, condition, lhs, backslash_escapes=None): """Value of the single literal compared with ``lhs`` in a one-term condition.""" sql = condition % () # the driver's parameter substitution turns %% into % prefix = f" ({lhs}=" assert sql.startswith(prefix), sql - value, rest = _read_literal(backend, sql[len(prefix) :]) + value, rest = _read_literal(backend, sql[len(prefix) :], backslash_escapes) assert rest == ")", f"text after the literal: {rest!r}" return value @@ -321,6 +329,25 @@ def test_negated_value_with_quote_characters(self, backend): assert _literal_value(backend, cond[4:], _quoted(backend, "name")) == "' OR 1=1 --" +@pytest.mark.parametrize("value", SPECIAL_CHARACTER_STRINGS) +@pytest.mark.parametrize("key", ["name", "car.name", "car.tags", "car.headlights[1]"]) +def test_mysql_literal_closed_without_backslash_escapes(key, value): + """MySQL literals stay closed when read with NO_BACKSLASH_ESCAPES in the session's sql_mode.""" + restriction = {"car.tags": [value, 'a"b', "c'd"], "car.headlights[1]": {"side": value}}.get(key, value) + lhs = _quoted("mysql", key) if key == "name" else _json_lhs("mysql", key.split(".", 1)[1]) + # _literal_value asserts that the literal's closing quote is followed only by ")" + _literal_value("mysql", _condition("mysql", {key: restriction}), lhs, backslash_escapes=False) + + +@pytest.mark.skipif(importlib.util.find_spec("psycopg2") is None, reason="psycopg2 not installed") +@pytest.mark.parametrize("value", SPECIAL_CHARACTER_STRINGS) +def test_postgresql_list_value_without_standard_conforming_strings(value): + """PostgreSQL list values read back exactly when standard_conforming_strings is off.""" + items = [value, 1, 'a"b', "c'd"] + cond = _condition("postgresql", {"car.tags": items}) + assert _literal_value("postgresql", cond, _json_lhs("postgresql", "tags"), backslash_escapes=True) == str(items) + + @pytest.mark.parametrize("backend", BACKENDS) @pytest.mark.parametrize( "restriction, expected", From 896d1e7e158b2044614cfa7a5418b56d565ced00 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Thu, 12 Nov 2026 13:59:41 -0600 Subject: [PATCH 32/37] Check every key of a folder object before ObjectRef.download writes it ObjectRef.download of a folder object lists the keys under the object and refuses the whole download, before writing any file, if a key relative to the object is not made of plain file names (for example, one containing a ".." component). It no longer relies on the installed fsspec version to keep such keys inside the destination. Files still land at destination//..., and fsspec still fetches them in one batch. The store-path error message now says that allow_filepath_outside_store applies to values only, and to use it only with trusted data. --- src/datajoint/objectref.py | 35 ++++++++++++++++++++++-- src/datajoint/storage.py | 5 ++-- tests/unit/test_path_confinement.py | 42 +++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 4 deletions(-) diff --git a/src/datajoint/objectref.py b/src/datajoint/objectref.py index 670f45307..e4827c580 100644 --- a/src/datajoint/objectref.py +++ b/src/datajoint/objectref.py @@ -299,7 +299,8 @@ def download(self, destination: Path | str, subpath: str | None = None) -> Path: ------ DataJointError If ``destination`` is a directory and the last component of the - stored path is not a plain file name. + stored path is not a plain file name, or if a key inside a folder + object is not made of plain file names. """ self._ensure_backend() destination = Path(destination) @@ -314,8 +315,38 @@ def download(self, destination: Path | str, subpath: str | None = None) -> Path: if self.is_dir and not subpath: # Download entire directory destination.mkdir(parents=True, exist_ok=True) + fs = self._backend.fs full_path = self._backend._full_path(remote_path) - self._backend.fs.get(full_path, str(destination), recursive=True) + root = fs._strip_protocol(full_path).rstrip("/") + # Same layout as fsspec's recursive get: destination//... + name = root.rsplit("/", 1)[-1] + target = destination / name + # Check every key before writing anything: each must be made of plain + # names below the object, so that no file lands outside target + entries = fs.find(full_path, withdirs=True, detail=True) + if not entries: + raise FileNotFoundError(full_path) + rpaths, lpaths, ldirs = [], [], [] + for rpath, info in entries.items(): + key = rpath.rstrip("/") + if key == root: + continue # the object itself + rel = key[len(root) + 1 :] if key.startswith(root + "/") else "" + parts = rel.split("/") + if not all(is_plain_file_name(p) for p in [name, *parts]): + raise DataJointError(f"Cannot download {remote_path!r}: entry {rpath!r} leads outside the destination.") + if info["type"] == "directory": + ldirs.append(target.joinpath(*parts)) + else: + rpaths.append(rpath) + lpaths.append(str(target.joinpath(*parts))) + target.mkdir(exist_ok=True) + for ldir in ldirs: + ldir.mkdir(parents=True, exist_ok=True) + for lpath in lpaths: + Path(lpath).parent.mkdir(parents=True, exist_ok=True) + if rpaths: + fs.get(rpaths, lpaths) else: # Download single file if destination.is_dir(): diff --git a/src/datajoint/storage.py b/src/datajoint/storage.py index bf83b8d9d..3455ef7a4 100644 --- a/src/datajoint/storage.py +++ b/src/datajoint/storage.py @@ -515,8 +515,9 @@ def _check_confined(self, path: str) -> None: ): raise errors.DataJointError( f"Path {path!r} may lead outside the store location. Use a path relative to the " - "store location, without '..' components. For references that " - "deliberately point outside the store, set dj.config.allow_filepath_outside_store = True." + "store location, without '..' components. ( only: " + "dj.config.allow_filepath_outside_store = True accepts such paths for every " + "value; use it only with trusted data.)" ) def _path_in_location(self, path: str) -> str | None: diff --git a/tests/unit/test_path_confinement.py b/tests/unit/test_path_confinement.py index dbf252af1..0319be483 100644 --- a/tests/unit/test_path_confinement.py +++ b/tests/unit/test_path_confinement.py @@ -290,6 +290,48 @@ def test_download_into_directory_uses_last_component_only(self, cfg, layout, sub ref.download(downloads, subpath=subpath) assert not any(downloads.iterdir()) + @pytest.fixture + def memory_backend(self): + """A backend over fsspec's in-memory filesystem, whose keys may contain '..' as object stores' keys can.""" + from fsspec.implementations.memory import MemoryFileSystem + + class MemoryBackend: + fs = MemoryFileSystem() + + def _full_path(self, path): + return f"dj-test-bucket/loc/{path}" + + backend = MemoryBackend() + yield backend + backend.fs.rm("/dj-test-bucket", recursive=True) + + def test_download_folder_rejects_key_leading_outside(self, memory_backend, tmp_path): + """Every key is checked before any file is written.""" + memory_backend.fs.pipe( + { + "/dj-test-bucket/loc/obj/a.txt": b"a", + "/dj-test-bucket/loc/obj/sub/b.txt": b"b", + "/dj-test-bucket/loc/obj/sub/../../../../x": b"x", + } + ) + dest = tmp_path / "work" / "dest" # dest/obj/sub/../../../../x is tmp_path/x + ref = ObjectRef(path="obj", size=None, hash=None, ext=None, is_dir=True, timestamp=None, _backend=memory_backend) + with pytest.raises(DataJointError, match="leads outside the destination"): + ref.download(dest) + assert not (tmp_path / "x").exists() + assert [p for p in tmp_path.rglob("*") if not p.is_dir()] == [] + assert not (dest / "obj").exists() + + def test_download_folder_round_trip(self, memory_backend, tmp_path): + """Files land in destination//..., as fsspec's recursive get placed them.""" + memory_backend.fs.pipe({"/dj-test-bucket/loc/obj/a.txt": b"a", "/dj-test-bucket/loc/obj/sub/b.txt": b"b"}) + dest = tmp_path / "dest" + ref = ObjectRef(path="obj", size=None, hash=None, ext=None, is_dir=True, timestamp=None, _backend=memory_backend) + assert ref.download(dest) == dest + assert sorted(p.relative_to(dest).as_posix() for p in dest.rglob("*") if p.is_file()) == ["obj/a.txt", "obj/sub/b.txt"] + assert (dest / "obj" / "a.txt").read_bytes() == b"a" + assert (dest / "obj" / "sub" / "b.txt").read_bytes() == b"b" + # --------------------------------------------------------------------------- # # From 8247e9ab8b8b5cfc73964e11a993990261e1810e Mon Sep 17 00:00:00 2001 From: mayuriphad Date: Sat, 14 Nov 2026 10:26:31 +0530 Subject: [PATCH 33/37] fix(proj): raise for a rename or replicate of a missing attribute The check for mentioned names used `if not self.heading.names`, which never refers to the attribute and is always false, so a rename or replicate of an attribute missing from the heading was silently dropped. Fixes #1677 Signed-off-by: mayuriphad --- src/datajoint/expression.py | 2 +- tests/integration/test_relational_operand.py | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/datajoint/expression.py b/src/datajoint/expression.py index 852dc9ad2..ca2b9be1b 100644 --- a/src/datajoint/expression.py +++ b/src/datajoint/expression.py @@ -586,7 +586,7 @@ def proj(self, *attributes, **named_attributes): # check that all mentioned names are present in heading mentions = attributes.union(replicate_map.values()).union(rename_map.values()) try: - raise DataJointError("Attribute '%s' not found." % next(a for a in mentions if not self.heading.names)) + raise DataJointError("Attribute `%s` not found." % next(a for a in mentions if a not in self.heading.names)) except StopIteration: pass # all ok diff --git a/tests/integration/test_relational_operand.py b/tests/integration/test_relational_operand.py index afdd12328..c3209de66 100644 --- a/tests/integration/test_relational_operand.py +++ b/tests/integration/test_relational_operand.py @@ -180,6 +180,12 @@ def test_project(schema_simp_pop): assert len((D() & cond).proj()) == len((D() & cond)), "projection failed: altered its arguments cardinality" +@pytest.mark.parametrize("value", ["nonexistent", "(nonexistent)"]) +def test_project_missing_source_attribute(schema_simp_pop, value): + with pytest.raises(DataJointError, match="Attribute `nonexistent` not found"): + A().proj(c=value) + + def test_rename_non_dj_attribute(connection_test, schema_simp_pop, schema_any_pop, prefix): schema = prefix + "_test1" connection_test.query(f"CREATE TABLE {schema}.test_table (oldID int PRIMARY KEY)").fetchall() From 99fdda292181f1d464a0706a87724c720f0b99ef Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Mon, 16 Nov 2026 20:02:02 -0600 Subject: [PATCH 34/37] Check where a file-store path resolves when the location adds no prefix With a file store whose location is "" or ".", a stored path is used as given, and fsspec reads a leading "file:" or "local:" as a protocol and expands a leading "~". Such a path passed the store-path check and then resolved outside the working directory. The full path is now also checked after fsspec resolves it, so it must lie inside the location whatever the location is. --- src/datajoint/storage.py | 29 ++++++++++++++++++++--------- tests/unit/test_path_confinement.py | 15 +++++++++++++++ 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/src/datajoint/storage.py b/src/datajoint/storage.py index 3455ef7a4..0b8d88132 100644 --- a/src/datajoint/storage.py +++ b/src/datajoint/storage.py @@ -18,6 +18,7 @@ from typing import Any import fsspec +from fsspec.implementations.local import LocalFileSystem from . import errors @@ -500,9 +501,15 @@ def _full_path(self, path: str | PurePosixPath) -> str: return f"{bucket}/{path}" elif self.protocol == "file": location = self.spec.get("location", "") - if location: - return (Path(location) / path).as_posix() - return path + full = (Path(location) / path).as_posix() if location else path + # A location of "" or "." adds no prefix, and fsspec reads a leading "file:" or + # "local:" as a protocol and expands "~", so compare where fsspec resolves both + if self.confine_paths: + root = LocalFileSystem._strip_protocol(Path(location or ".").as_posix()).rstrip("/") + resolved = LocalFileSystem._strip_protocol(full) + if resolved != root and not resolved.startswith(root + "/"): + raise self._confinement_error(path) + return full else: return self._require_adapter().full_path(self.spec, path) @@ -513,12 +520,16 @@ def _check_confined(self, path: str) -> None: or _has_parent_reference(path) or (self.protocol == "file" and Path(path).anchor and self._path_in_location(path) is None) ): - raise errors.DataJointError( - f"Path {path!r} may lead outside the store location. Use a path relative to the " - "store location, without '..' components. ( only: " - "dj.config.allow_filepath_outside_store = True accepts such paths for every " - "value; use it only with trusted data.)" - ) + raise self._confinement_error(path) + + @staticmethod + def _confinement_error(path: str) -> errors.DataJointError: + return errors.DataJointError( + f"Path {path!r} may lead outside the store location. Use a path relative to the " + "store location, without '..' components. ( only: " + "dj.config.allow_filepath_outside_store = True accepts such paths for every " + "value; use it only with trusted data.)" + ) def _path_in_location(self, path: str) -> str | None: """Express an absolute path inside a ``file`` store's location relative to it (see :func:`path_in_location`).""" diff --git a/tests/unit/test_path_confinement.py b/tests/unit/test_path_confinement.py index 0319be483..efc3431b0 100644 --- a/tests/unit/test_path_confinement.py +++ b/tests/unit/test_path_confinement.py @@ -115,6 +115,21 @@ def test_file_store_accepts_relative_paths_inside(self, layout, path): backend = StorageBackend({"protocol": "file", "location": str(store)}) assert backend._full_path(path) == (store / path).as_posix() + @posix_only + @pytest.mark.parametrize("location", [".", ""]) + def test_file_store_in_working_directory_rejects_protocol_and_home_paths(self, layout, monkeypatch, location): + root, store, _ = layout + monkeypatch.chdir(store) + monkeypatch.setenv("HOME", str(root)) + backend = StorageBackend({"protocol": "file", "location": location}) + outside = str(root / "outside.txt") + for path in ("file://" + outside, "file:" + outside, "local://" + outside, "local:" + outside, "~/outside.txt"): + with pytest.raises(DataJointError, match="outside the store location"): + backend._full_path(path) + with pytest.raises(DataJointError): + backend.get_buffer("file://" + outside) + assert backend.get_buffer("data/inside.txt") == b"inside" + def test_io_never_reaches_outside(self, layout): root, store, _ = layout backend = StorageBackend({"protocol": "file", "location": str(store)}) From 152b2bb6e198b296b2bdca42de12bd5b126cd1d3 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Wed, 18 Nov 2026 10:36:49 -0600 Subject: [PATCH 35/37] Normalize both sides of the file-store location check fsspec before 2024 leaves "." segments in a resolved path, so a store whose location is "" or "." rejected every path, including ones inside it. Compare normalized paths instead. The working-directory test now checks what the store does with each path: it is rejected, or fsspec resolves it inside the store and I/O stays there. Old fsspec does not read some "file:" and "local:" forms as a protocol, so it accepts them as names inside the store. The Windows download test accepts OSError, which Windows raises for a source path containing ":". --- src/datajoint/storage.py | 11 ++++++----- tests/unit/test_path_confinement.py | 23 +++++++++++++++++------ 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/datajoint/storage.py b/src/datajoint/storage.py index 0b8d88132..60c03ad36 100644 --- a/src/datajoint/storage.py +++ b/src/datajoint/storage.py @@ -10,6 +10,7 @@ import json import logging import os +import posixpath import re import secrets import urllib.parse @@ -400,8 +401,7 @@ def _validate_spec(self): # with a clear message. if bool(self.spec.get("access_key")) != bool(self.spec.get("secret_key")): raise errors.DataJointError( - "Incomplete S3 credentials: set both access_key and secret_key, " - "or neither to use ambient AWS credentials." + "Incomplete S3 credentials: set both access_key and secret_key, or neither to use ambient AWS credentials." ) @property @@ -503,10 +503,11 @@ def _full_path(self, path: str | PurePosixPath) -> str: location = self.spec.get("location", "") full = (Path(location) / path).as_posix() if location else path # A location of "" or "." adds no prefix, and fsspec reads a leading "file:" or - # "local:" as a protocol and expands "~", so compare where fsspec resolves both + # "local:" as a protocol and expands "~", so compare where fsspec resolves both. + # fsspec before 2024 leaves "." segments in place, so normalize both sides if self.confine_paths: - root = LocalFileSystem._strip_protocol(Path(location or ".").as_posix()).rstrip("/") - resolved = LocalFileSystem._strip_protocol(full) + root = posixpath.normpath(LocalFileSystem._strip_protocol(Path(location or ".").as_posix())).rstrip("/") + resolved = posixpath.normpath(LocalFileSystem._strip_protocol(full)) if resolved != root and not resolved.startswith(root + "/"): raise self._confinement_error(path) return full diff --git a/tests/unit/test_path_confinement.py b/tests/unit/test_path_confinement.py index efc3431b0..0e843f1bd 100644 --- a/tests/unit/test_path_confinement.py +++ b/tests/unit/test_path_confinement.py @@ -118,16 +118,26 @@ def test_file_store_accepts_relative_paths_inside(self, layout, path): @posix_only @pytest.mark.parametrize("location", [".", ""]) def test_file_store_in_working_directory_rejects_protocol_and_home_paths(self, layout, monkeypatch, location): + from fsspec.implementations.local import LocalFileSystem + root, store, _ = layout monkeypatch.chdir(store) monkeypatch.setenv("HOME", str(root)) backend = StorageBackend({"protocol": "file", "location": location}) outside = str(root / "outside.txt") + cwd = os.path.realpath(os.getcwd()) for path in ("file://" + outside, "file:" + outside, "local://" + outside, "local:" + outside, "~/outside.txt"): - with pytest.raises(DataJointError, match="outside the store location"): - backend._full_path(path) - with pytest.raises(DataJointError): - backend.get_buffer("file://" + outside) + try: + full = backend._full_path(path) + except DataJointError as error: + assert "outside the store location" in str(error) + continue + # fsspec before 2024 does not read some of these prefixes as a protocol. A path it + # accepts then names a file inside the working directory, and I/O stays there + assert os.path.realpath(LocalFileSystem._strip_protocol(full)).startswith(cwd + "/") + backend.put_buffer(b"written", path) + assert backend.get_buffer(path) == b"written" + assert (root / "outside.txt").read_text() == "outside" assert backend.get_buffer("data/inside.txt") == b"inside" def test_io_never_reaches_outside(self, layout): @@ -300,8 +310,9 @@ def test_download_into_directory_uses_last_component_only(self, cfg, layout, sub with pytest.raises(DataJointError, match="not a plain file name"): ref.download(downloads, subpath=subpath) else: - # Missing source file: the error comes from the store, after the name was accepted - with pytest.raises(FileNotFoundError): + # Missing source file: the error comes from the store, after the name was accepted. + # Windows reports a source path containing ":" as invalid rather than missing + with pytest.raises(OSError): ref.download(downloads, subpath=subpath) assert not any(downloads.iterdir()) From 6829f5074666d1260e170e7d200e7440d8d27270 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Wed, 18 Nov 2026 14:18:40 -0600 Subject: [PATCH 36/37] build: require pymysql>=1.1.1 in the mysql extra Match the floor master declares for the core dependency: pymysql 1.0 adds the ssl_disabled connection option, and 1.1.1 fixes CVE-2024-36039. Raise the same floor in the test and dev extras, the test dependency group, and the conda run requirements in RELEASE_MEMO.md, and refresh pixi.lock. --- RELEASE_MEMO.md | 2 +- pixi.lock | 10 +++++----- pyproject.toml | 10 ++++++---- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/RELEASE_MEMO.md b/RELEASE_MEMO.md index 951efde55..34466534d 100644 --- a/RELEASE_MEMO.md +++ b/RELEASE_MEMO.md @@ -155,7 +155,7 @@ If the bot doesn't create a PR, manually update the feedstock: run: - python >={{ python_min }} - numpy - - pymysql >=0.7.2 + - pymysql >=1.1.1 - psycopg2 >=2.9.0 - deepdiff - pyparsing diff --git a/pixi.lock b/pixi.lock index 3984f1eb7..436ad432c 100644 --- a/pixi.lock +++ b/pixi.lock @@ -4492,8 +4492,8 @@ packages: requires_python: '>=3.8' - pypi: ./ name: datajoint - version: 2.3.5.dev44+g215175ada - sha256: 93aa78078608348c30e7d6a88ad78f218220990a716b35a4a52f62fb5d7955d6 + version: 2.3.5.dev45+g6760c26d6.d20261118 + sha256: f0c20862d49a5540137f14a5b54cdc8efdaa572b77c49792c5338eec6b2b3d26 requires_dist: - deepdiff - deepdiff<9 ; python_full_version >= '3.15' @@ -4513,12 +4513,12 @@ packages: - pre-commit ; extra == 'dev' - psycopg2-binary>=2.9.0 ; extra == 'dev' - pyarrow>=14.0.0 ; extra == 'dev' - - pymysql>=0.7.2 ; extra == 'dev' + - pymysql>=1.1.1 ; extra == 'dev' - pytest ; extra == 'dev' - pytest-cov ; extra == 'dev' - ruff ; extra == 'dev' - gcsfs>=2023.1.0 ; extra == 'gcs' - - pymysql>=0.7.2 ; extra == 'mysql' + - pymysql>=1.1.1 ; extra == 'mysql' - polars>=0.20.0 ; extra == 'polars' - psycopg2-binary>=2.9.0 ; extra == 'postgres' - s3fs>=2023.1.0 ; extra == 's3' @@ -4528,7 +4528,7 @@ packages: - polars>=0.20.0 ; extra == 'test' - psycopg2-binary>=2.9.0 ; extra == 'test' - pyarrow>=14.0.0 ; extra == 'test' - - pymysql>=0.7.2 ; extra == 'test' + - pymysql>=1.1.1 ; extra == 'test' - pytest ; extra == 'test' - pytest-cov ; extra == 'test' - requests ; extra == 'test' diff --git a/pyproject.toml b/pyproject.toml index dae3c45ff..4781dd2be 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -96,7 +96,7 @@ test = [ "ipython", "graphviz", "testcontainers[mysql,postgres]>=4.0", - "pymysql>=0.7.2", + "pymysql>=1.1.1", "psycopg2-binary>=2.9.0", "polars>=0.20.0", "pyarrow>=14.0.0", @@ -108,7 +108,9 @@ gcs = ["gcsfs>=2023.1.0"] azure = ["adlfs>=2023.1.0"] # Database drivers: install the extra for each backend in use. postgres = ["psycopg2-binary>=2.9.0"] -mysql = ["pymysql>=0.7.2"] +# pymysql 1.0 adds the ssl_disabled connection option; 1.1.1 fixes +# CVE-2024-36039. +mysql = ["pymysql>=1.1.1"] polars = ["polars>=0.20.0"] arrow = ["pyarrow>=14.0.0"] viz = ["matplotlib", "ipython"] @@ -121,7 +123,7 @@ test = [ "ipython", "s3fs>=2023.1.0", "testcontainers[mysql,postgres]>=4.0", - "pymysql>=0.7.2", + "pymysql>=1.1.1", "psycopg2-binary>=2.9.0", "polars>=0.20.0", "pyarrow>=14.0.0", @@ -133,7 +135,7 @@ dev = [ # including test "pytest", "pytest-cov", - "pymysql>=0.7.2", + "pymysql>=1.1.1", "psycopg2-binary>=2.9.0", "polars>=0.20.0", "pyarrow>=14.0.0", From 2fd05579dd015c6dfb40e31bffe1e794bd6f8866 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Wed, 18 Nov 2026 15:06:36 -0600 Subject: [PATCH 37/37] fix(lint): ignore codespell regex fragment and PyMySQL internals in mypy codespell flags "acter" in the char(?:acter)? pattern in condition.py; add it to the ignore list. mypy reports server_capabilities and _request_authentication on the TLS connection subclass, which are PyMySQL internals that types-PyMySQL does not declare; mark those three lines with targeted type-ignore codes. No behavior change. --- pyproject.toml | 3 ++- src/datajoint/adapters/mysql.py | 8 +++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 75789801c..280d6f493 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -251,7 +251,8 @@ skip = ".git,*.pdf,*.svg,*.csv,*.ipynb,*.drawio" # Rever -- nobody knows # numer -- numerator variable # astroid -- Python library name (not "asteroid") -ignore-words-list = "rever,numer,astroid" +# acter -- regex fragment char(?:acter)? +ignore-words-list = "rever,numer,astroid,acter" [tool.pytest.ini_options] markers = [ diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index 7a786c7e8..e55425254 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -68,14 +68,16 @@ class _TLSRequiredConnection(client.connections.Connection): tls_required = True + # server_capabilities and _request_authentication are PyMySQL internals + # that types-PyMySQL does not declare. def _request_authentication(self): - if not self.server_capabilities & CLIENT.SSL: + if not self.server_capabilities & CLIENT.SSL: # type: ignore[attr-defined] if self.tls_required: raise _TLSUnavailableError() # Continue without TLS: do not announce TLS in the handshake response self.ssl = False self.client_flag &= ~CLIENT.SSL - super()._request_authentication() + super()._request_authentication() # type: ignore[misc] class _TLSPreferredConnection(_TLSRequiredConnection): @@ -174,7 +176,7 @@ def connect( # Require SSL, configured by the dict or SSLContext connection = _TLSRequiredConnection(**conn_params) # Checked again in case a PyMySQL version bypasses the hook above - if not connection.server_capabilities & CLIENT.SSL: + if not connection.server_capabilities & CLIENT.SSL: # type: ignore[attr-defined] # PyMySQL internal connection.close() raise _TLSUnavailableError() return connection