From 62c3d8b1a8d72b9fb14bb6c2524f1a9e18252f3d Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Sat, 17 Oct 2026 18:46:18 -0500 Subject: [PATCH 01/39] feat: PostgreSQL is the default backend database.backend defaulted to "mysql", so a connection made without configuring a backend went to MySQL. It now defaults to "postgresql" on port 5432. MySQL stays a fully supported backend, selected with one setting. The port follows the backend unless it is set. The port was derived from the backend only when the settings were first built, so a backend set later, in datajoint.json or by assignment, kept the other backend's port: with the new default, backend "mysql" in datajoint.json would have connected to port 5432. The validator now recomputes a port that was not set whenever the backend changes. A port set by DJ_PORT, datajoint.json, or assignment is kept, and setting it to None returns it to the backend's default. When a connection fails and the backend is still the default, so that neither the backend argument nor the configuration chose one, the error is re-raised as a DataJointError that keeps the original message and adds: The default backend is postgresql since DataJoint 2.4; set database.backend='mysql' (DJ_BACKEND=mysql) for a MySQL server. The same applies when the adapter cannot be created, as when psycopg2 is not installed. The settings record which fields were set (pydantic's model_fields_set), so DJ_BACKEND, datajoint.json, dj.config assignment, and Instance(backend=...) all count as chosen, and with any of them the original error is raised unchanged. Instance no longer passes its config's backend to Connection as an argument, which hid whether it was chosen; Connection reads it from that config. save_template writes "backend": "postgresql" and port 5432. The settings docstring, the Connection and Instance docstrings, the CLI help, docker-compose.yaml, and CONTRIBUTING.md list PostgreSQL first. In the compose file the app service's DJ_HOST, DJ_USER, and DJ_PASS name the MySQL service, which the test suite reads as its MySQL server, so the service now sets DJ_BACKEND=mysql to match. Migration for MySQL users: select the backend with DJ_BACKEND=mysql, "backend": "mysql" under "database" in datajoint.json, dj.config["database.backend"] = "mysql" before connecting, or dj.Instance(..., backend="mysql"). The port then defaults to 3306; an explicit port is kept. A MySQL setup that sets no backend fails to connect with the message above. Tests: the MySQL-only fixtures no longer rely on the default. A session fixture, mysql_backend_config, selects MySQL in dj.config for the tests that connect through db_creds_root and db_creds_test. connection_root_bare and connection_test pass backend="mysql". The CLI test's subprocess sets DJ_BACKEND=mysql. connection_by_backend falls back to "postgresql". New unit tests, which need no server, check the default backend and port, that a port not set follows the backend (including backend "mysql" in datajoint.json), that a port that was set survives a change of backend, and that the hint appears for a failed connection or missing driver with the default backend. They also check that it does not appear when the backend comes from the argument, assignment, DJ_BACKEND, or datajoint.json, using a stub adapter and a real refused connection to a closed local port. --- CONTRIBUTING.md | 34 +++---- docker-compose.yaml | 47 +++++----- src/datajoint/cli.py | 13 ++- src/datajoint/connection.py | 46 +++++++--- src/datajoint/instance.py | 9 +- src/datajoint/settings.py | 41 ++++++--- tests/conftest.py | 26 +++++- tests/integration/test_cli.py | 5 +- tests/unit/test_connection_backend_hint.py | 102 +++++++++++++++++++++ tests/unit/test_settings.py | 79 +++++++++++++--- tests/unit/test_thread_safe.py | 35 ++++++- 11 files changed, 345 insertions(+), 92 deletions(-) create mode 100644 tests/unit/test_connection_backend_hint.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 64ad3f6ab..25d98470e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,17 +36,17 @@ pytest tests/ ## Running Tests -Tests use [testcontainers](https://testcontainers.com/) to automatically manage MySQL, PostgreSQL, and MinIO containers. No manual `docker-compose up` required. +Tests use [testcontainers](https://testcontainers.com/) to automatically manage PostgreSQL, MySQL, and MinIO containers. No manual `docker-compose up` required. -Integration tests are **backend-parameterized** — tests using the `backend` fixture run automatically against both MySQL and PostgreSQL. +Integration tests are **backend-parameterized** — tests using the `backend` fixture run automatically against both PostgreSQL and MySQL. ```bash pixi run -e test test # All tests (both backends) pixi run -e test test-cov # With coverage pixi run -e test pytest tests/unit/ # Unit tests only pixi run -e test pytest tests/integration/test_blob.py -v # Specific file -pixi run -e test pytest -m mysql # MySQL tests only pixi run -e test pytest -m postgresql # PostgreSQL tests only +pixi run -e test pytest -m mysql # MySQL tests only ``` **macOS Docker Desktop users:** If tests fail to connect: @@ -62,18 +62,18 @@ DataJoint supports MySQL 8.0.13+ and PostgreSQL 15+ as production database backe pip install -e ".[postgres]" # Installs psycopg2-binary ``` -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. +Tests automatically spin up both PostgreSQL and MySQL containers via testcontainers. Backend-parameterized tests (those using the `backend` fixture in `tests/conftest.py`) run against both backends to ensure feature parity. PostgreSQL is the default backend (`database.backend`), so fixtures and tests that need MySQL select it explicitly. ### External Containers (for debugging) ```bash -# MySQL + MinIO -docker compose up -d db minio +# PostgreSQL + MySQL + MinIO +docker compose up -d postgres db minio DJ_USE_EXTERNAL_CONTAINERS=1 pixi run -e test test docker compose down -# MySQL + PostgreSQL + MinIO -docker compose up -d db postgres minio +# MySQL + MinIO +docker compose up -d db minio DJ_USE_EXTERNAL_CONTAINERS=1 pixi run -e test test docker compose down ``` @@ -111,6 +111,15 @@ Hooks include: **ruff** (lint/format), **codespell**, YAML/JSON/TOML validation. For `DJ_USE_EXTERNAL_CONTAINERS=1`: +### PostgreSQL + +| Variable | Default | Description | +|----------|---------|-------------| +| `DJ_PG_HOST` | `localhost` | PostgreSQL hostname | +| `DJ_PG_PORT` | `5432` | PostgreSQL port | +| `DJ_PG_USER` | `postgres` | PostgreSQL username | +| `DJ_PG_PASS` | `password` | PostgreSQL password | + ### MySQL | Variable | Default | Description | @@ -120,14 +129,7 @@ For `DJ_USE_EXTERNAL_CONTAINERS=1`: | `DJ_USER` | `root` | MySQL username | | `DJ_PASS` | `password` | MySQL password | -### PostgreSQL - -| Variable | Default | Description | -|----------|---------|-------------| -| `DJ_PG_HOST` | `localhost` | PostgreSQL hostname | -| `DJ_PG_PORT` | `5432` | PostgreSQL port | -| `DJ_PG_USER` | `postgres` | PostgreSQL username | -| `DJ_PG_PASS` | `password` | PostgreSQL password | +The test suite reads `DJ_HOST`, `DJ_PORT`, `DJ_USER`, and `DJ_PASS` as the MySQL server. Outside the tests, these variables configure whichever backend `DJ_BACKEND` selects, PostgreSQL by default. ### Object Storage diff --git a/docker-compose.yaml b/docker-compose.yaml index 23fd773c1..8de571804 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -1,4 +1,4 @@ -# Development environment with MySQL and MinIO services +# Development environment with PostgreSQL, MySQL, and MinIO services # # NOTE: docker-compose is OPTIONAL for running tests. # Tests use testcontainers to automatically manage containers. @@ -6,24 +6,14 @@ # # Use docker-compose for development/debugging when you want # persistent containers that survive test runs: -# docker compose up -d db minio # Start services manually -# pytest tests/ # Tests will use these containers +# docker compose up -d postgres db minio # Start services manually +# DJ_USE_EXTERNAL_CONTAINERS=1 pytest tests/ # Tests will use these containers +# +# PostgreSQL is DataJoint's default backend. The MySQL service is `db`. # # Full Docker testing (CI): # docker compose --profile test up djtest --build services: - db: - image: datajoint/mysql:${MYSQL_VER:-8.0} - environment: - - MYSQL_ROOT_PASSWORD=${DJ_PASS:-password} - command: mysqld --default-authentication-plugin=mysql_native_password - ports: - - "3306:3306" - healthcheck: - test: [ "CMD", "mysqladmin", "ping", "-h", "localhost" ] - timeout: 30s - retries: 5 - interval: 15s postgres: image: postgres:${POSTGRES_VER:-15} environment: @@ -37,6 +27,18 @@ services: timeout: 30s retries: 5 interval: 15s + db: + image: datajoint/mysql:${MYSQL_VER:-8.0} + environment: + - MYSQL_ROOT_PASSWORD=${DJ_PASS:-password} + command: mysqld --default-authentication-plugin=mysql_native_password + ports: + - "3306:3306" + healthcheck: + test: [ "CMD", "mysqladmin", "ping", "-h", "localhost" ] + timeout: 30s + retries: 5 + interval: 15s minio: image: minio/minio:${MINIO_VER:-RELEASE.2025-02-28T09-55-16Z} environment: @@ -63,23 +65,26 @@ services: PY_VER: ${PY_VER:-3.10} HOST_UID: ${HOST_UID:-1000} depends_on: - db: - condition: service_healthy postgres: condition: service_healthy + db: + condition: service_healthy minio: condition: service_healthy environment: + - DJ_PG_HOST=postgres + - DJ_PG_USER=postgres + - DJ_PG_PASS=password + - DJ_PG_PORT=5432 + # DJ_HOST, DJ_USER, and DJ_PASS name the MySQL service, which the test suite + # reads as its MySQL server, so DJ_BACKEND selects the matching backend. + - DJ_BACKEND=mysql - DJ_HOST=db - DJ_USER=root - DJ_PASS=password - DJ_TEST_HOST=db - DJ_TEST_USER=datajoint - DJ_TEST_PASSWORD=datajoint - - DJ_PG_HOST=postgres - - DJ_PG_USER=postgres - - DJ_PG_PASS=password - - DJ_PG_PORT=5432 - S3_ENDPOINT=minio:9000 - S3_ACCESS_KEY=datajoint - S3_SECRET_KEY=datajoint diff --git a/src/datajoint/cli.py b/src/datajoint/cli.py index c77cca686..1310980b4 100644 --- a/src/datajoint/cli.py +++ b/src/datajoint/cli.py @@ -5,8 +5,8 @@ Usage:: - # Start REPL with database credentials - dj --user root --password secret --host localhost:3306 + # Start REPL with database credentials (PostgreSQL unless DJ_BACKEND=mysql) + dj --user postgres --password secret --host localhost:5432 # Load schemas as virtual modules dj -s my_lab:lab -s my_analysis:analysis @@ -41,7 +41,8 @@ def cli(args: list[str] | None = None) -> None: -------- From the command line:: - $ dj --host localhost:3306 --user root --password secret + $ dj --host localhost:5432 --user postgres --password secret + $ DJ_BACKEND=mysql dj --host localhost:3306 --user root --password secret $ dj -s my_lab:lab -s my_analysis:analysis Programmatically:: @@ -52,7 +53,11 @@ def cli(args: list[str] | None = None) -> None: parser = argparse.ArgumentParser( prog="dj", description="DataJoint interactive console. Start a Python REPL with DataJoint pre-loaded.", - epilog="Example: dj -s my_lab:lab --host localhost:3306", + epilog=( + "The database backend is PostgreSQL unless database.backend is set in config; " + "for a MySQL server, set DJ_BACKEND=mysql. " + "Example: dj -s my_lab:lab --host localhost:5432" + ), ) parser.add_argument( "-V", diff --git a/src/datajoint/connection.py b/src/datajoint/connection.py index 4e6252e0d..4f34b53e1 100644 --- a/src/datajoint/connection.py +++ b/src/datajoint/connection.py @@ -29,6 +29,13 @@ cache_key = "query_cache" # the key to lookup the query_cache folder in dj.config +# Added to a failed connection whose backend came from the default rather than from the +# configuration, since a MySQL server reached with the default backend fails this way. +DEFAULT_BACKEND_HINT = ( + "The default backend is postgresql since DataJoint 2.4; " + "set database.backend='mysql' (DJ_BACKEND=mysql) for a MySQL server." +) + def translate_query_error(client_error: Exception, query: str, adapter) -> Exception: """ @@ -163,6 +170,16 @@ class Connection: Port number. Overridden if specified in host. use_tls : bool or dict, optional TLS encryption option. + backend : str, optional + Database backend: ``"postgresql"`` or ``"mysql"``. Default from + ``database.backend`` in config, which is ``"postgresql"`` unless set. + + Raises + ------ + DataJointError + If the connection fails while the backend is the default rather than one + set by the ``backend`` argument or in config. The message adds how to + select the MySQL backend. Attributes ---------- @@ -211,20 +228,27 @@ def __init__( self._query_cache = None self._is_closed = True # Mark as closed until connect() succeeds - # Select adapter: explicit backend > config backend + # Select adapter: explicit backend > config backend. When neither names one, + # the backend is the default and a failure to connect says how to change it. + backend_is_default = backend is None and "backend" not in self._config.database.model_fields_set if backend is None: backend = self._config["database.backend"] - self.adapter = get_adapter(backend) - - if database_name and self.adapter.backend == "mysql": - warnings.warn( - "database.name is set but the MySQL backend does not support database selection. " - "This setting only applies to PostgreSQL connections.", - UserWarning, - stacklevel=2, - ) + try: + self.adapter = get_adapter(backend) + + if database_name and self.adapter.backend == "mysql": + warnings.warn( + "database.name is set but the MySQL backend does not support database selection. " + "This setting only applies to PostgreSQL connections.", + UserWarning, + stacklevel=2, + ) - self.connect() + self.connect() + except Exception as error: + if backend_is_default: + raise errors.DataJointError(f"{str(error).rstrip()}\n{DEFAULT_BACKEND_HINT}") from error + raise if self.is_connected: db = self.conn_info.get("database_name") db_str = f"/{db}" if db else "" diff --git a/src/datajoint/instance.py b/src/datajoint/instance.py index 455336a7c..80bcc5fe9 100644 --- a/src/datajoint/instance.py +++ b/src/datajoint/instance.py @@ -54,11 +54,12 @@ class Instance: password : str Database password. port : int, optional - Database port. Defaults to 3306 for MySQL, 5432 for PostgreSQL. + Database port. Defaults to 5432 for PostgreSQL, 3306 for MySQL. use_tls : bool or dict, optional TLS configuration. backend : str, optional - Database backend: ``"mysql"`` or ``"postgresql"``. Default from config. + Database backend: ``"postgresql"`` or ``"mysql"``. Default from config, + which is ``"postgresql"`` unless set. **kwargs : Any Additional config overrides applied to this instance's config. @@ -112,14 +113,14 @@ def __init__( if port is None: port = self.config.database.port - # Create connection with this instance's config and backend + # Create connection with this instance's config. The backend comes from that + # config, which records whether it was set or left at the default. self.connection = Connection( host, user, password, port, use_tls, - backend=self.config.database.backend, config_override=self.config, ) diff --git a/src/datajoint/settings.py b/src/datajoint/settings.py index 38339a1d9..008f5babe 100644 --- a/src/datajoint/settings.py +++ b/src/datajoint/settings.py @@ -21,10 +21,10 @@ >>> import datajoint as dj >>> dj.config.database.host 'localhost' ->>> dj.config.database.backend -'mysql' ->>> dj.config.database.port # Auto-detects: 3306 for MySQL, 5432 for PostgreSQL -3306 +>>> dj.config.database.backend # PostgreSQL is the default; set 'mysql' for a MySQL server +'postgresql' +>>> dj.config.database.port # Follows the backend unless set: 5432 for PostgreSQL, 3306 for MySQL +5432 >>> with dj.config.override(safemode=False): ... # dangerous operations here ... pass @@ -199,11 +199,15 @@ class DatabaseSettings(BaseSettings): user: str | None = Field(default=None, validation_alias="DJ_USER") password: SecretStr | None = Field(default=None, validation_alias="DJ_PASS") backend: Literal["mysql", "postgresql"] = Field( - default="mysql", + default="postgresql", validation_alias="DJ_BACKEND", - description="Database backend: 'mysql' or 'postgresql'", + description="Database backend: 'postgresql' (default) or 'mysql'", + ) + port: int | None = Field( + default=None, + validation_alias="DJ_PORT", + description="Database port. Defaults to the backend's port: 5432 for PostgreSQL, 3306 for MySQL.", ) - port: int | None = Field(default=None, validation_alias="DJ_PORT") name: str | None = Field( default=None, validation_alias="DJ_DATABASE_NAME", @@ -225,9 +229,19 @@ class DatabaseSettings(BaseSettings): @model_validator(mode="after") def set_default_port_from_backend(self) -> "DatabaseSettings": - """Set default port based on backend if not explicitly provided.""" + """ + Use the backend's default port unless a port was set explicitly. + + The validator also runs when a setting is assigned, so a port that was + not set follows later changes of the backend (for example + ``backend: "mysql"`` in ``datajoint.json``). Setting the port to None + returns it to the backend's default. + """ if self.port is None: - self.port = 5432 if self.backend == "postgresql" else 3306 + self.model_fields_set.discard("port") + if "port" not in self.model_fields_set: + # Write the derived port directly so that it is not recorded as set explicitly. + self.__dict__["port"] = 5432 if self.backend == "postgresql" else 3306 return self @@ -939,6 +953,9 @@ def save_template( Set ``DJ_IGNORE_CONFIG_FILE=true`` to skip both ``datajoint.json`` and the secrets directory entirely (env-var-only configuration). + The template selects the PostgreSQL backend on port 5432. For a MySQL + server, set ``backend`` to ``"mysql"`` and ``port`` to 3306. + Parameters ---------- path : str or Path, optional @@ -973,15 +990,17 @@ def save_template( if minimal: template = { "database": { + "backend": "postgresql", "host": "localhost", - "port": 3306, + "port": 5432, }, } else: template = { "database": { + "backend": "postgresql", "host": "localhost", - "port": 3306, + "port": 5432, "reconnect": True, "use_tls": None, }, diff --git a/tests/conftest.py b/tests/conftest.py index bfbbc293d..35d3c36a0 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -12,6 +12,10 @@ DJ_USE_EXTERNAL_CONTAINERS=1 DJ_HOST=localhost DJ_PORT=3306 S3_ENDPOINT=localhost:9000 pytest +PostgreSQL is the default backend. The MySQL-only fixtures (``db_creds_root``, +``db_creds_test`` and the connections built from them) select MySQL explicitly +through ``mysql_backend_config``. + To run only unit tests (no Docker required): pytest -m "not requires_mysql" """ @@ -207,7 +211,19 @@ def prefix(): @pytest.fixture(scope="session") -def db_creds_root(mysql_container) -> Dict: +def mysql_backend_config(): + """Select the MySQL backend in ``dj.config`` for the MySQL-only fixtures and tests. + + PostgreSQL is the default backend. Tests connect to the MySQL server with + ``dj.conn(**db_creds_root)`` and ``dj.Connection(**db_creds_test)``, which take + the backend from ``dj.config``, so the MySQL credentials fixtures set it. + ``connection_by_backend`` switches it per test and restores it afterwards. + """ + dj.config["database.backend"] = "mysql" + + +@pytest.fixture(scope="session") +def db_creds_root(mysql_container, mysql_backend_config) -> Dict: """Root database credentials from container or environment.""" if mysql_container is not None: # From testcontainer @@ -230,7 +246,7 @@ def db_creds_root(mysql_container) -> Dict: @pytest.fixture(scope="session") -def db_creds_test(mysql_container) -> Dict: +def db_creds_test(mysql_container, mysql_backend_config) -> Dict: """Test user database credentials from container or environment.""" if mysql_container is not None: # From testcontainer @@ -340,7 +356,7 @@ def connection_by_backend(db_creds_by_backend): is restored after each test, preventing config pollution between tests. """ # Save original config to restore after tests - original_backend = dj.config.get("database.backend", "mysql") + original_backend = dj.config.get("database.backend", "postgresql") original_host = dj.config.get("database.host") original_port = dj.config.get("database.port") @@ -410,7 +426,7 @@ def configure_datajoint(db_creds_root): @pytest.fixture(scope="session") def connection_root_bare(db_creds_root, configure_datajoint): """Bare root connection without user setup.""" - connection = dj.Connection(**db_creds_root) + connection = dj.Connection(**db_creds_root, backend="mysql") yield connection @@ -480,7 +496,7 @@ def connection_test(connection_root, prefix, db_creds_test): """ ) - connection = dj.Connection(**db_creds_test) + connection = dj.Connection(**db_creds_test, backend="mysql") yield connection connection_root.query(f"""DROP USER `{db_creds_test["user"]}`""") connection.close() diff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.py index 1f8144f0f..524c18c2f 100644 --- a/tests/integration/test_cli.py +++ b/tests/integration/test_cli.py @@ -2,6 +2,7 @@ Collection of test cases to test the dj cli """ +import os import subprocess import sys @@ -80,7 +81,8 @@ class IJ(dj.Lookup): """ contents = list(dict(i=i, j=j + 2) for i in range(3) for j in range(3)) - # Pass credentials via CLI args to avoid prompting for username + # Pass credentials via CLI args to avoid prompting for username. The test server + # is MySQL and PostgreSQL is the default backend, so select MySQL for the subprocess. process = subprocess.Popen( [ sys.executable, @@ -99,6 +101,7 @@ class IJ(dj.Lookup): stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + env={**os.environ, "DJ_BACKEND": "mysql"}, ) process.stdin.write("test_schema.__dict__['__name__']\n") diff --git a/tests/unit/test_connection_backend_hint.py b/tests/unit/test_connection_backend_hint.py new file mode 100644 index 000000000..80b9b93b8 --- /dev/null +++ b/tests/unit/test_connection_backend_hint.py @@ -0,0 +1,102 @@ +""" +Unit tests for the hint added when a connection with the default backend fails. + +PostgreSQL is the default backend. A connection that fails while the backend +was left at that default says how to select MySQL; one whose backend was set, +by argument, config assignment, ``datajoint.json`` or ``DJ_BACKEND``, raises +the original error unchanged. No database server is needed. +""" + +import json +import socket +from unittest.mock import patch + +import pytest + +from datajoint.connection import DEFAULT_BACKEND_HINT, Connection +from datajoint.errors import DataJointError +from datajoint.settings import Config + + +class _RefusingAdapter: + """Adapter stub whose connect fails the way a refused connection does.""" + + backend = "postgresql" + + def connect(self, **kwargs): + raise OSError("connection refused") + + +@pytest.fixture +def fresh_config(monkeypatch): + """A Config built without DJ_BACKEND or DJ_PORT from the developer's shell.""" + for var in ("DJ_BACKEND", "DJ_PORT"): + monkeypatch.delenv(var, raising=False) + return Config() + + +def _connect(config, **kwargs): + with patch("datajoint.connection.get_adapter", return_value=_RefusingAdapter()): + return Connection("localhost", "user", "password", config_override=config, **kwargs) + + +def test_default_backend_failure_adds_hint(fresh_config): + """A failed connection with the default backend names the MySQL setting.""" + with pytest.raises(DataJointError) as info: + _connect(fresh_config) + message = str(info.value) + assert "connection refused" in message + assert DEFAULT_BACKEND_HINT in message + assert "database.backend='mysql'" in message and "DJ_BACKEND=mysql" in message + assert isinstance(info.value.__cause__, OSError) + + +def test_missing_driver_with_default_backend_adds_hint(fresh_config): + """A missing PostgreSQL driver with the default backend also names the MySQL setting.""" + missing = ImportError("psycopg2 is required for PostgreSQL support.") + with patch("datajoint.connection.get_adapter", side_effect=missing): + with pytest.raises(DataJointError, match="psycopg2 is required") as info: + Connection("localhost", "user", "password", config_override=fresh_config) + assert DEFAULT_BACKEND_HINT in str(info.value) + assert info.value.__cause__ is missing + + +def test_backend_argument_gets_no_hint(fresh_config): + """backend= passed to Connection counts as set: the original error is raised.""" + with pytest.raises(OSError, match="connection refused"): + _connect(fresh_config, backend="postgresql") + + +def test_backend_assigned_in_config_gets_no_hint(fresh_config): + """A backend assigned in config, even to the default value, counts as set.""" + fresh_config["database.backend"] = "postgresql" + with pytest.raises(OSError, match="connection refused"): + _connect(fresh_config) + + +def test_backend_from_env_var_gets_no_hint(monkeypatch): + """DJ_BACKEND counts as set.""" + monkeypatch.setenv("DJ_BACKEND", "postgresql") + with pytest.raises(OSError, match="connection refused"): + _connect(Config()) + + +def test_backend_from_config_file_gets_no_hint(fresh_config, tmp_path): + """database.backend in datajoint.json counts as set.""" + config_file = tmp_path / "datajoint.json" + config_file.write_text(json.dumps({"database": {"backend": "postgresql"}})) + fresh_config.load(config_file) + with pytest.raises(OSError, match="connection refused"): + _connect(fresh_config) + + +def test_refused_connection_with_default_backend(fresh_config): + """A real refused connection through the PostgreSQL adapter carries the hint.""" + pytest.importorskip("psycopg2") + # Find a local port with nothing listening on it. + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + with pytest.raises(DataJointError) as info: + Connection("127.0.0.1", "user", "password", port, use_tls=False, config_override=fresh_config) + assert DEFAULT_BACKEND_HINT in str(info.value) diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index a2fd26b3f..a2b28b4e3 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -164,7 +164,7 @@ def test_attribute_access(self): # Host can be localhost or db (docker), just verify it's a string assert isinstance(dj.config.database.host, str) assert len(dj.config.database.host) > 0 - # Port may be 3306 (default) or a random port (testcontainers) + # Port may be the backend's default or a random port (testcontainers) assert isinstance(dj.config.database.port, int) assert 1 <= dj.config.database.port <= 65535 # safemode may be modified by conftest fixtures @@ -175,7 +175,7 @@ def test_dict_style_access(self): # Host can be localhost or db (docker), just verify it's a string assert isinstance(dj.config["database.host"], str) assert len(dj.config["database.host"]) > 0 - # Port may be 3306 (default) or a random port (testcontainers) + # Port may be the backend's default or a random port (testcontainers) assert isinstance(dj.config["database.port"], int) assert 1 <= dj.config["database.port"] <= 65535 # safemode may be modified by conftest fixtures @@ -770,8 +770,9 @@ def test_save_minimal_template(self, tmp_path): content = json.load(f) assert "database" in content + assert content["database"]["backend"] == "postgresql" assert content["database"]["host"] == "localhost" - assert content["database"]["port"] == 3306 + assert content["database"]["port"] == 5432 # Minimal template should not have credentials assert "password" not in content["database"] assert "user" not in content["database"] @@ -1062,12 +1063,23 @@ def _isolate_dj_env(self, monkeypatch): monkeypatch.delenv(var, raising=False) def test_backend_default(self): - """Test default backend is mysql.""" + """Test default backend is postgresql on port 5432.""" from datajoint.settings import DatabaseSettings + settings = DatabaseSettings() + assert settings.backend == "postgresql" + assert settings.port == 5432 + assert "backend" not in settings.model_fields_set + + def test_backend_mysql_env_var(self, monkeypatch): + """DJ_BACKEND=mysql selects MySQL on port 3306 and counts as set explicitly.""" + from datajoint.settings import DatabaseSettings + + monkeypatch.setenv("DJ_BACKEND", "mysql") settings = DatabaseSettings() assert settings.backend == "mysql" assert settings.port == 3306 + assert "backend" in settings.model_fields_set def test_backend_postgresql(self, monkeypatch): """Test PostgreSQL backend with auto port.""" @@ -1121,7 +1133,6 @@ def test_config_file_backend(self, tmp_path, monkeypatch): from datajoint.settings import Config - # Include port in config since auto-detection only happens during initialization config_file = tmp_path / "test_config.json" config_file.write_text(json.dumps({"database": {"backend": "postgresql", "host": "db.example.com", "port": 5432}})) @@ -1138,7 +1149,7 @@ def test_config_file_backend(self, tmp_path, monkeypatch): def test_global_config_backend(self): """Test global config has backend configuration.""" - # Global config should have backend field with default mysql + # Global config has a backend field (conftest fixtures may have set it) assert hasattr(dj.config.database, "backend") # Backend should be one of the valid values assert dj.config.database.backend in ["mysql", "postgresql"] @@ -1146,19 +1157,59 @@ def test_global_config_backend(self): assert isinstance(dj.config.database.port, int) assert 1 <= dj.config.database.port <= 65535 - def test_port_auto_detection_on_initialization(self): - """Test port auto-detects only during initialization, not on live updates.""" + def test_port_follows_backend_when_not_set(self): + """A port that was not set follows changes of the backend on a live config.""" from datajoint.settings import DatabaseSettings - # Start with MySQL (default) settings = DatabaseSettings() - assert settings.port == 3306 + assert settings.port == 5432 - # Change backend on live config - port won't auto-update + settings.backend = "mysql" + assert settings.port == 3306 settings.backend = "postgresql" - # Port remains at previous value (this is expected behavior) - # Users should set port explicitly when changing backend on live config - assert settings.port == 3306 # Didn't auto-update + assert settings.port == 5432 + assert "port" not in settings.model_fields_set + + def test_explicit_port_survives_backend_change(self, monkeypatch): + """A port that was set, by assignment or DJ_PORT, is kept when the backend changes.""" + from datajoint.settings import DatabaseSettings + + settings = DatabaseSettings() + settings.port = 6543 + settings.backend = "mysql" + assert settings.port == 6543 + + monkeypatch.setenv("DJ_PORT", "3307") + settings = DatabaseSettings() + settings.backend = "mysql" + assert settings.port == 3307 + + def test_port_none_returns_to_backend_default(self): + """Setting the port to None makes it follow the backend again.""" + from datajoint.settings import DatabaseSettings + + settings = DatabaseSettings() + settings.port = 6543 + settings.port = None + assert settings.port == 5432 + settings.backend = "mysql" + assert settings.port == 3306 + + def test_config_file_mysql_backend_without_port(self, tmp_path): + """backend: mysql in datajoint.json, without a port, connects on port 3306.""" + import json + + from datajoint.settings import Config + + config_file = tmp_path / "datajoint.json" + config_file.write_text(json.dumps({"database": {"backend": "mysql", "host": "db.example.com"}})) + + cfg = Config() + assert cfg.database.port == 5432 + cfg.load(config_file) + assert cfg.database.backend == "mysql" + assert cfg.database.port == 3306 + assert "backend" in cfg.database.model_fields_set def test_mysql_backend_with_explicit_port(self, monkeypatch): """Test MySQL backend with explicit non-default port.""" diff --git a/tests/unit/test_thread_safe.py b/tests/unit/test_thread_safe.py index aba1b686b..f464f35b4 100644 --- a/tests/unit/test_thread_safe.py +++ b/tests/unit/test_thread_safe.py @@ -173,19 +173,26 @@ def test_instance_backend_sets_config(self, monkeypatch): ) assert inst.config.database.backend == "postgresql" - def test_instance_backend_default_from_config(self, monkeypatch): - """Instance without backend uses config default.""" + def test_instance_backend_default_from_config(self, monkeypatch, tmp_path): + """Instance without backend uses the config default, postgresql on port 5432.""" monkeypatch.setenv("DJ_THREAD_SAFE", "false") + monkeypatch.delenv("DJ_BACKEND", raising=False) + monkeypatch.delenv("DJ_PORT", raising=False) + # Keep a datajoint.json in a parent directory from supplying the backend + (tmp_path / ".git").mkdir() + monkeypatch.chdir(tmp_path) from datajoint.instance import Instance from unittest.mock import patch - with patch("datajoint.instance.Connection"): + with patch("datajoint.instance.Connection") as MockConn: inst = Instance( host="localhost", - user="root", + user="postgres", password="secret", ) - assert inst.config.database.backend == "mysql" + assert inst.config.database.backend == "postgresql" + args, kwargs = MockConn.call_args + assert args[3] == 5432 # port is the 4th positional arg def test_instance_backend_affects_port_default(self, monkeypatch): """Instance(backend='postgresql') uses port 5432 by default.""" @@ -204,6 +211,24 @@ def test_instance_backend_affects_port_default(self, monkeypatch): args, kwargs = MockConn.call_args assert args[3] == 5432 # port is the 4th positional arg + def test_instance_mysql_backend_uses_port_3306(self, monkeypatch): + """Instance(backend='mysql') uses port 3306 by default.""" + monkeypatch.setenv("DJ_THREAD_SAFE", "false") + monkeypatch.delenv("DJ_PORT", raising=False) + from datajoint.instance import Instance + from unittest.mock import patch + + with patch("datajoint.instance.Connection") as MockConn: + inst = Instance( + host="localhost", + user="root", + password="secret", + backend="mysql", + ) + assert inst.config.database.backend == "mysql" + args, kwargs = MockConn.call_args + assert args[3] == 3306 + class TestCrossConnectionValidation: """Test that cross-connection operations are rejected.""" From e77d8a551320b2adcb995f273afa66ac8e0cebe8 Mon Sep 17 00:00:00 2001 From: mayuriphad Date: Sun, 18 Oct 2026 15:38:56 +0530 Subject: [PATCH 02/39] 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/39] 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 247125c9105d25c786fe52dc115d48bdb669f9bf Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Wed, 4 Nov 2026 15:46:33 -0600 Subject: [PATCH 04/39] 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 05/39] 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 06/39] 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 07/39] 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 08/39] 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 09/39] 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 10/39] 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 11/39] 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 12/39] 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 13/39] 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 14/39] 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 15/39] 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 16/39] 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 17/39] 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 18/39] 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 19/39] 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 20/39] 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 21/39] 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 22/39] 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 23/39] 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 24/39] 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 25/39] 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 26/39] 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 27/39] 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 28/39] 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 29/39] 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 30/39] 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 31/39] 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 32/39] 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 33/39] 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 34/39] 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 efaf08fbf22fc372c60568125c12f95d09b8f2b1 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Wed, 18 Nov 2026 14:18:52 -0600 Subject: [PATCH 35/39] test: derive the default port from the backend for Instance and config Cover each way the backend reaches a connection with no port set: Instance(database__backend=...) gives 3306 for mysql and 5432 for postgresql, DJ_BACKEND=mysql without DJ_PORT gives 3306 both in the created config and in an Instance, and the default backend gives 5432. --- tests/unit/test_settings.py | 14 ++++++++++ tests/unit/test_thread_safe.py | 49 ++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index 07a1019a6..781456324 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -1102,6 +1102,20 @@ def test_backend_mysql_env_var(self, monkeypatch): assert settings.port == 3306 assert "backend" in settings.model_fields_set + @pytest.mark.parametrize(("backend", "port"), [(None, 5432), ("postgresql", 5432), ("mysql", 3306)]) + def test_created_config_port_follows_dj_backend(self, monkeypatch, backend, port): + """The config that connections read takes its port from DJ_BACKEND when DJ_PORT is unset.""" + from datajoint.settings import _create_config + + monkeypatch.setenv("DJ_IGNORE_CONFIG_FILE", "true") + if backend is not None: + monkeypatch.setenv("DJ_BACKEND", backend) + cfg = _create_config() + assert cfg.database.backend == (backend or "postgresql") + assert cfg.database.port == port + assert cfg["database.port"] == port + assert "port" not in cfg.database.model_fields_set + def test_backend_postgresql(self, monkeypatch): """Test PostgreSQL backend with auto port.""" from datajoint.settings import DatabaseSettings diff --git a/tests/unit/test_thread_safe.py b/tests/unit/test_thread_safe.py index f464f35b4..a2c880142 100644 --- a/tests/unit/test_thread_safe.py +++ b/tests/unit/test_thread_safe.py @@ -230,6 +230,55 @@ def test_instance_mysql_backend_uses_port_3306(self, monkeypatch): assert args[3] == 3306 +class TestInstancePortFromBackend: + """An Instance with no port connects on the default port of the backend it ends up with.""" + + @pytest.fixture(autouse=True) + def _isolate_config(self, monkeypatch): + """Keep the shell environment and any datajoint.json from supplying a backend or port.""" + monkeypatch.setenv("DJ_THREAD_SAFE", "false") + monkeypatch.setenv("DJ_IGNORE_CONFIG_FILE", "true") + for var in ("DJ_BACKEND", "DJ_PORT"): + monkeypatch.delenv(var, raising=False) + + @staticmethod + def _connect(**kwargs): + """Create an Instance with the connection mocked; return it and the port it connects on.""" + from unittest.mock import patch + + from datajoint.instance import Instance + + with patch("datajoint.instance.Connection") as MockConn: + inst = Instance(host="localhost", user="user", password="secret", **kwargs) + args, _ = MockConn.call_args + return inst, args[3] # port is the 4th positional arg + + def test_default_backend_uses_port_5432(self): + """With no backend set anywhere, the backend is postgresql on port 5432.""" + inst, port = self._connect() + assert inst.config.database.backend == "postgresql" + assert port == 5432 + + @pytest.mark.parametrize( + ("backend", "port"), + [("mysql", 3306), ("postgresql", 5432)], + ) + def test_database_backend_override_sets_port(self, monkeypatch, backend, port): + """Instance(database__backend=...) derives the port, whatever DJ_BACKEND selected.""" + monkeypatch.setenv("DJ_BACKEND", "postgresql" if backend == "mysql" else "mysql") + inst, connected_port = self._connect(database__backend=backend) + assert inst.config.database.backend == backend + assert inst.config.database.port == port + assert connected_port == port + + def test_dj_backend_env_uses_port_3306(self, monkeypatch): + """DJ_BACKEND=mysql with no DJ_PORT connects on port 3306.""" + monkeypatch.setenv("DJ_BACKEND", "mysql") + inst, port = self._connect() + assert inst.config.database.backend == "mysql" + assert port == 3306 + + class TestCrossConnectionValidation: """Test that cross-connection operations are rejected.""" From 616dec326104b8b7a397301a51623b0c6784fb1d Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Wed, 18 Nov 2026 14:19:14 -0600 Subject: [PATCH 36/39] fix: keep a configured port when Instance selects the backend Instance(backend=...) overwrote the port with the backend's default whenever no port argument was given, so a port set by DJ_PORT or in datajoint.json was dropped, while Instance(database__backend=...) kept it. The database settings now derive a port that was not set from the backend whenever the backend changes, so Instance no longer derives it itself, and both forms connect on the configured port. --- src/datajoint/instance.py | 6 ++---- tests/unit/test_thread_safe.py | 8 ++++++++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/datajoint/instance.py b/src/datajoint/instance.py index 80bcc5fe9..f2be9db28 100644 --- a/src/datajoint/instance.py +++ b/src/datajoint/instance.py @@ -90,12 +90,10 @@ def __init__( # Create fresh config with defaults loaded from env/file self.config = _create_config() - # Apply backend override before other kwargs (port default depends on it) + # Apply backend override before other kwargs. A port that was not set follows + # the backend, and a port set in config (DJ_PORT, datajoint.json) is kept. if backend is not None: self.config.database.backend = backend - # Re-derive port default since _create_config resolved it before backend was set - if port is None and "database__port" not in kwargs: - self.config.database.port = 5432 if backend == "postgresql" else 3306 # Apply any config overrides from kwargs for key, value in kwargs.items(): diff --git a/tests/unit/test_thread_safe.py b/tests/unit/test_thread_safe.py index a2c880142..bae56174d 100644 --- a/tests/unit/test_thread_safe.py +++ b/tests/unit/test_thread_safe.py @@ -278,6 +278,14 @@ def test_dj_backend_env_uses_port_3306(self, monkeypatch): assert inst.config.database.backend == "mysql" assert port == 3306 + @pytest.mark.parametrize("override", ["backend", "database__backend"]) + def test_backend_override_keeps_configured_port(self, monkeypatch, override): + """A port set by DJ_PORT is kept when the Instance selects the backend.""" + monkeypatch.setenv("DJ_PORT", "3307") + inst, port = self._connect(**{override: "mysql"}) + assert inst.config.database.backend == "mysql" + assert port == 3307 + class TestCrossConnectionValidation: """Test that cross-connection operations are rejected.""" From 2fd05579dd015c6dfb40e31bffe1e794bd6f8866 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Wed, 18 Nov 2026 15:06:36 -0600 Subject: [PATCH 37/39] 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 From 6614b26c4930af70ad6bdfa9a789780c008eb578 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Wed, 18 Nov 2026 15:10:04 -0600 Subject: [PATCH 38/39] fix: require the backend to be set for port 3306 PostgreSQL is the default backend, and the backend is never inferred from the port. A connection on port 3306, MySQL's default port, with the backend left at its default now raises a DataJointError before any network access. The message names the port, says the backend defaults to PostgreSQL since 2.4 and that PostgreSQL uses 5432, and lists how to set the backend: DJ_BACKEND=mysql, database.backend in datajoint.json or dj.config, or the backend keyword. The check runs in Connection.__init__, which every path reaches (dj.conn, dj.Instance, dj.Connection), so DJ_PORT, datajoint.json, dj.config assignment, port arguments, and host:port are all covered. It is not in the settings validator: settings are assigned one at a time, so port 3306 may be set before the backend, and a validator error would be swallowed into a warning when datajoint.json loads. An explicit backend, including "postgresql", allows port 3306. --- CONTRIBUTING.md | 2 +- src/datajoint/__init__.py | 4 + src/datajoint/connection.py | 52 +++- src/datajoint/instance.py | 10 +- src/datajoint/settings.py | 9 +- .../unit/test_mysql_port_requires_backend.py | 278 ++++++++++++++++++ 6 files changed, 347 insertions(+), 8 deletions(-) create mode 100644 tests/unit/test_mysql_port_requires_backend.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6eb9ee545..d97b27e7d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -129,7 +129,7 @@ For `DJ_USE_EXTERNAL_CONTAINERS=1`: | `DJ_USER` | `root` | MySQL username | | `DJ_PASS` | `password` | MySQL password | -The test suite reads `DJ_HOST`, `DJ_PORT`, `DJ_USER`, and `DJ_PASS` as the MySQL server. Outside the tests, these variables configure whichever backend `DJ_BACKEND` selects, PostgreSQL by default. +The test suite reads `DJ_HOST`, `DJ_PORT`, `DJ_USER`, and `DJ_PASS` as the MySQL server. Outside the tests, these variables configure whichever backend `DJ_BACKEND` selects, PostgreSQL by default. The backend is never inferred from the port: `DJ_PORT=3306` without `DJ_BACKEND` raises an error on connecting, so set `DJ_BACKEND=mysql` for a MySQL server. ### Object Storage diff --git a/src/datajoint/__init__.py b/src/datajoint/__init__.py index 69c6df269..bb327d85c 100644 --- a/src/datajoint/__init__.py +++ b/src/datajoint/__init__.py @@ -145,6 +145,10 @@ def conn( ------ ThreadSafetyError If thread_safe mode is enabled. + DataJointError + If the port (``database.port``, ``DJ_PORT``, or ``host:port``) is 3306, + MySQL's default port, and the backend is not set. Set + ``database.backend`` (``DJ_BACKEND``) to ``"mysql"`` for a MySQL server. """ import datajoint.instance as instance_module from pydantic import SecretStr diff --git a/src/datajoint/connection.py b/src/datajoint/connection.py index 4f34b53e1..49d6a23cf 100644 --- a/src/datajoint/connection.py +++ b/src/datajoint/connection.py @@ -36,6 +36,38 @@ "set database.backend='mysql' (DJ_BACKEND=mysql) for a MySQL server." ) +MYSQL_DEFAULT_PORT = 3306 + + +def _check_mysql_port_without_backend(host: str, port, backend_is_default: bool) -> None: + """ + Refuse MySQL's default port when the backend was left at its default. + + The backend is never inferred from the port. Port 3306 with no backend set + is most likely a MySQL server reached with the PostgreSQL default, so the + connection stops before any network access and says how to set the backend. + A backend set explicitly, including ``"postgresql"``, allows any port. + + Raises + ------ + DataJointError + If ``backend_is_default`` and the port is 3306. + """ + if not backend_is_default or str(port) != str(MYSQL_DEFAULT_PORT): + return + raise errors.DataJointError( + f"Connecting to {host}:{port} with the database backend not set. " + f"Port {MYSQL_DEFAULT_PORT} is MySQL's default port, but the backend defaults to PostgreSQL " + "since DataJoint 2.4, and DataJoint does not infer the backend from the port.\n" + "For a MySQL server, set the backend to 'mysql' in one of these ways:\n" + " - environment: DJ_BACKEND=mysql\n" + ' - datajoint.json: {"database": {"backend": "mysql"}}\n' + " - in Python: dj.config['database.backend'] = 'mysql'\n" + " - keyword: dj.Instance(..., backend='mysql') or dj.Connection(..., backend='mysql')\n" + "For a PostgreSQL server, use its port, 5432 by default, or set the backend to " + "'postgresql' explicitly to keep port 3306." + ) + def translate_query_error(client_error: Exception, query: str, adapter) -> Exception: """ @@ -77,7 +109,7 @@ def conn( Parameters ---------- host : str, optional - Database hostname. + Database hostname, may include the port as ``hostname:port``. user : str, optional Database username. Required if not set in config. password : str, optional @@ -97,6 +129,9 @@ def conn( ------ DataJointError If user or password is not provided and not set in config. + DataJointError + If the port is 3306, MySQL's default port, and the backend is not set. + See :class:`Connection`. """ if not hasattr(conn, "connection") or reset: host = host if host is not None else config["database.host"] @@ -167,7 +202,9 @@ class Connection: password : str Database password. port : int, optional - Port number. Overridden if specified in host. + Port number. Overridden if specified in host. Default from + ``database.port`` in config: 5432 for PostgreSQL, 3306 for MySQL. Port + 3306 requires the backend to be set (see Raises). use_tls : bool or dict, optional TLS encryption option. backend : str, optional @@ -177,9 +214,13 @@ class Connection: Raises ------ DataJointError - If the connection fails while the backend is the default rather than one - set by the ``backend`` argument or in config. The message adds how to - select the MySQL backend. + If the port is 3306, MySQL's default port, while the backend is the + default rather than one set by the ``backend`` argument or in config. + The backend is never inferred from the port; set it to ``"mysql"`` for + a MySQL server. Raised before any connection attempt. + DataJointError + If the connection fails while the backend is the default. The message + adds how to select the MySQL backend. Attributes ---------- @@ -233,6 +274,7 @@ def __init__( backend_is_default = backend is None and "backend" not in self._config.database.model_fields_set if backend is None: backend = self._config["database.backend"] + _check_mysql_port_without_backend(host, port, backend_is_default) try: self.adapter = get_adapter(backend) diff --git a/src/datajoint/instance.py b/src/datajoint/instance.py index f2be9db28..01e0f0f43 100644 --- a/src/datajoint/instance.py +++ b/src/datajoint/instance.py @@ -54,7 +54,9 @@ class Instance: password : str Database password. port : int, optional - Database port. Defaults to 5432 for PostgreSQL, 3306 for MySQL. + Database port. Defaults to 5432 for PostgreSQL, 3306 for MySQL. Port + 3306 requires the backend to be set, by ``backend`` or in config: the + backend is never inferred from the port. use_tls : bool or dict, optional TLS configuration. backend : str, optional @@ -63,6 +65,12 @@ class Instance: **kwargs : Any Additional config overrides applied to this instance's config. + Raises + ------ + DataJointError + If the port is 3306, MySQL's default port, and the backend is not set + (by ``backend``, ``DJ_BACKEND``, ``datajoint.json``, or ``kwargs``). + Attributes ---------- config : Config diff --git a/src/datajoint/settings.py b/src/datajoint/settings.py index 4e7f6e828..dc5f30672 100644 --- a/src/datajoint/settings.py +++ b/src/datajoint/settings.py @@ -207,7 +207,8 @@ class DatabaseSettings(BaseSettings): port: int | None = Field( default=None, validation_alias="DJ_PORT", - description="Database port. Defaults to the backend's port: 5432 for PostgreSQL, 3306 for MySQL.", + description="Database port. Defaults to the backend's port: 5432 for PostgreSQL, 3306 for MySQL. " + "Port 3306 with the backend not set raises an error on connecting; set the backend explicitly.", ) name: str | None = Field( default=None, @@ -237,6 +238,12 @@ def set_default_port_from_backend(self) -> "DatabaseSettings": not set follows later changes of the backend (for example ``backend: "mysql"`` in ``datajoint.json``). Setting the port to None returns it to the backend's default. + + The backend is never inferred from the port. A port of 3306 with the + backend not set is refused when a connection is made, not here: the + settings are assigned one at a time (from ``datajoint.json`` or by + ``dj.config[...]``), so the port may legitimately be set before the + backend. """ if self.port is None: self.model_fields_set.discard("port") diff --git a/tests/unit/test_mysql_port_requires_backend.py b/tests/unit/test_mysql_port_requires_backend.py new file mode 100644 index 000000000..bcae1c815 --- /dev/null +++ b/tests/unit/test_mysql_port_requires_backend.py @@ -0,0 +1,278 @@ +""" +Unit tests for refusing MySQL's default port when the backend is not set. + +PostgreSQL is the default backend, and DataJoint never infers the backend from +the port. A connection on port 3306 whose backend was left at the default raises +a DataJointError before any network access, whichever way the port was given: +``DJ_PORT``, ``datajoint.json``, ``dj.config`` assignment, ``dj.Instance`` and +``dj.Connection`` arguments, or ``host:port``. A backend set explicitly, to +``"mysql"`` or to ``"postgresql"``, allows port 3306. No database server is needed. +""" + +import importlib +import json +from unittest.mock import patch + +import pytest + + +def _module(name): + """ + The module as currently imported. + + Another unit test removes the datajoint modules from ``sys.modules`` and imports + them again, so classes and patch targets are looked up at test time. + """ + return importlib.import_module(name) + + +def Config(): + return _module("datajoint.settings").Config() + + +def Connection(*args, **kwargs): + return _module("datajoint.connection").Connection(*args, **kwargs) + + +def Instance(**kwargs): + return _module("datajoint.instance").Instance(**kwargs) + + +class _Reached(Exception): + """Raised by the adapter stub: the connection got past the port check.""" + + def __init__(self, backend, kwargs): + super().__init__(f"reached {backend} adapter") + self.backend = backend + self.kwargs = kwargs + + +class _RecordingAdapter: + """Adapter stub that records the connect arguments and stops there.""" + + def __init__(self, backend): + self.backend = backend + + def connect(self, **kwargs): + raise _Reached(self.backend, kwargs) + + +@pytest.fixture(autouse=True) +def _isolate(monkeypatch, tmp_path): + """Keep the shell environment and any datajoint.json from setting a backend or port.""" + monkeypatch.setenv("DJ_THREAD_SAFE", "false") + monkeypatch.setenv("DJ_IGNORE_CONFIG_FILE", "true") + for var in ("DJ_BACKEND", "DJ_PORT"): + monkeypatch.delenv(var, raising=False) + monkeypatch.chdir(tmp_path) + with patch.object(_module("datajoint.connection"), "get_adapter", side_effect=_RecordingAdapter) as get_adapter: + yield get_adapter + + +def _reached(connect): + """Run ``connect``, which must get past the port check; return (backend, port) it used.""" + with pytest.raises(Exception) as info: + connect() + error = info.value + if isinstance(error, _module("datajoint.errors").DataJointError): + # The default backend adds a hint to a failed connection and chains the original error. + assert _module("datajoint.connection").DEFAULT_BACKEND_HINT in str(error) + error = error.__cause__ + assert isinstance(error, _Reached), f"expected the adapter to be reached, got {info.value!r}" + return error.backend, error.kwargs["port"] + + +def _refused(connect, get_adapter): + """Run ``connect``, which must stop at the port check; return the error message.""" + with pytest.raises(_module("datajoint.errors").DataJointError) as info: + connect() + assert not isinstance(info.value.__cause__, _Reached) + get_adapter.assert_not_called() + return str(info.value) + + +def _connection(config, *args, **kwargs): + kwargs.setdefault("use_tls", False) + return lambda: Connection("localhost", "user", "password", *args, config_override=config, **kwargs) + + +def _instance(**kwargs): + return lambda: Instance(host="localhost", user="user", password="password", use_tls=False, **kwargs) + + +# --- The error message -------------------------------------------------------- + + +def test_message_says_why_and_how_to_fix(_isolate): + """The message names port 3306 as MySQL's, the PostgreSQL default, each fix, and port 5432.""" + message = _refused(_connection(Config(), 3306), _isolate) + assert "localhost:3306" in message + assert "MySQL's default port" in message + assert "backend not set" in message + assert "defaults to PostgreSQL" in message and "2.4" in message + assert "DJ_BACKEND=mysql" in message + assert '{"database": {"backend": "mysql"}}' in message + assert "dj.config['database.backend'] = 'mysql'" in message + assert "backend='mysql'" in message + assert "5432" in message + + +# --- Each way of setting port 3306 without a backend raises --------------------- + + +def test_dj_port_env_raises(monkeypatch, _isolate): + monkeypatch.setenv("DJ_PORT", "3306") + config = Config() + assert config.database.port == 3306 + _refused(_connection(config), _isolate) + + +def test_dj_port_env_raises_for_instance(monkeypatch, _isolate): + monkeypatch.setenv("DJ_PORT", "3306") + _refused(_instance(), _isolate) + + +def test_config_file_port_raises(tmp_path, _isolate): + config_file = tmp_path / "datajoint.json" + config_file.write_text(json.dumps({"database": {"port": 3306}})) + config = Config() + config.load(config_file) + _refused(_connection(config), _isolate) + + +def test_config_assignment_raises(_isolate): + config = Config() + config["database.port"] = 3306 + _refused(_connection(config), _isolate) + + +def test_instance_port_argument_raises(_isolate): + _refused(_instance(port=3306), _isolate) + + +def test_instance_port_kwarg_override_raises(_isolate): + _refused(_instance(database__port=3306), _isolate) + + +def test_connection_port_argument_raises(_isolate): + _refused(_connection(Config(), 3306), _isolate) + + +def test_port_in_host_raises(_isolate): + config = Config() + _refused(lambda: Connection("localhost:3306", "user", "password", use_tls=False, config_override=config), _isolate) + + +def test_dj_conn_raises(monkeypatch, _isolate): + """dj.conn takes no port, but a port in the host or in config counts.""" + dj = _module("datajoint") + monkeypatch.setattr(dj, "_global_config", Config()) + monkeypatch.setattr(_module("datajoint.instance"), "_singleton_connection", None) + _refused(lambda: dj.conn("localhost:3306", "user", "password", use_tls=False), _isolate) + dj._global_config["database.port"] = 3306 + _refused(lambda: dj.conn("localhost", "user", "password", reset=True, use_tls=False), _isolate) + + +def test_port_set_before_backend_is_not_refused_by_config(tmp_path): + """The settings accept port 3306 first and the backend second: the check is on connecting.""" + config = Config() + config["database.port"] = 3306 + config["database.backend"] = "mysql" + assert (config.database.backend, config.database.port) == ("mysql", 3306) + config_file = tmp_path / "datajoint.json" + config_file.write_text(json.dumps({"database": {"port": 3306, "backend": "mysql"}})) + loaded = Config() + loaded.load(config_file) + assert (loaded.database.backend, loaded.database.port) == ("mysql", 3306) + + +# --- An explicit mysql backend resolves and allows 3306 -------------------------- + + +def test_mysql_env_resolves_3306(monkeypatch): + monkeypatch.setenv("DJ_BACKEND", "mysql") + assert _reached(_connection(Config())) == ("mysql", 3306) + + +def test_mysql_env_with_dj_port_3306(monkeypatch): + monkeypatch.setenv("DJ_BACKEND", "mysql") + monkeypatch.setenv("DJ_PORT", "3306") + assert _reached(_connection(Config())) == ("mysql", 3306) + + +def test_mysql_config_file_resolves_3306(tmp_path): + config_file = tmp_path / "datajoint.json" + config_file.write_text(json.dumps({"database": {"backend": "mysql", "port": 3306}})) + config = Config() + config.load(config_file) + assert _reached(_connection(config)) == ("mysql", 3306) + + +def test_mysql_config_assignment_resolves_3306(): + config = Config() + config["database.backend"] = "mysql" + assert _reached(_connection(config)) == ("mysql", 3306) + + +def test_mysql_instance_resolves_3306(): + assert _reached(_instance(backend="mysql")) == ("mysql", 3306) + assert _reached(_instance(backend="mysql", port=3306)) == ("mysql", 3306) + + +def test_mysql_connection_argument_with_3306(): + assert _reached(_connection(Config(), 3306, backend="mysql")) == ("mysql", 3306) + + +# --- An explicit postgresql backend allows 3306 ------------------------------------- + + +def test_postgresql_env_allows_3306(monkeypatch): + monkeypatch.setenv("DJ_BACKEND", "postgresql") + monkeypatch.setenv("DJ_PORT", "3306") + assert _reached(_connection(Config())) == ("postgresql", 3306) + + +def test_postgresql_config_file_allows_3306(tmp_path): + config_file = tmp_path / "datajoint.json" + config_file.write_text(json.dumps({"database": {"backend": "postgresql", "port": 3306}})) + config = Config() + config.load(config_file) + assert _reached(_connection(config)) == ("postgresql", 3306) + + +def test_postgresql_config_assignment_allows_3306(): + config = Config() + config["database.backend"] = "postgresql" + config["database.port"] = 3306 + assert _reached(_connection(config)) == ("postgresql", 3306) + + +def test_postgresql_instance_allows_3306(): + assert _reached(_instance(backend="postgresql", port=3306)) == ("postgresql", 3306) + + +def test_postgresql_connection_argument_allows_3306(): + assert _reached(_connection(Config(), 3306, backend="postgresql")) == ("postgresql", 3306) + config = Config() + connect = lambda: Connection("localhost:3306", "u", "p", use_tls=False, backend="postgresql", config_override=config) # noqa: E731 + assert _reached(connect) == ("postgresql", 3306) + + +# --- The default backend without port 3306 is unaffected ---------------------------- + + +def test_default_without_port_resolves_5432(): + assert _reached(_connection(Config())) == ("postgresql", 5432) + assert _reached(_instance()) == ("postgresql", 5432) + + +def test_default_with_port_5432(monkeypatch): + assert _reached(_connection(Config(), 5432)) == ("postgresql", 5432) + assert _reached(_instance(port=5432)) == ("postgresql", 5432) + monkeypatch.setenv("DJ_PORT", "5432") + assert _reached(_connection(Config())) == ("postgresql", 5432) + + +def test_default_with_other_port(): + """Only MySQL's default port is refused; any other port with the default backend connects.""" + assert _reached(_connection(Config(), 3307)) == ("postgresql", 3307) From e4a37a30f40dd370ca6f1946f8655d141ae5a601 Mon Sep 17 00:00:00 2001 From: Dimitri Yatsenko Date: Wed, 18 Nov 2026 15:35:31 -0600 Subject: [PATCH 39/39] fix: tailor the port 3306 message and keep override from setting fields The port 3306 error now fits the path the user took. A connection that reads the global config suggests dj.config; one from dj.Instance says that an Instance reads only the environment, datajoint.json, and its keyword arguments, and suggests backend='mysql', database__backend, or DJ_BACKEND. The closing sentence now reads: "PostgreSQL's default port is 5432. To reach a PostgreSQL server on port 3306, set the backend to 'postgresql' explicitly." Ports are compared as numbers. Config.override() restores whether each setting was set explicitly, not only its value: a setting unset before the block is unset after it, and database.port is derived again from the backend. Before, an override of database.backend left the backend counted as set, so port 3306 later reached PostgreSQL without the error. The backend name is accepted in any case, an empty DJ_BACKEND counts as not set, and any other value raises a DataJointError that lists 'mysql' and 'postgresql', instead of a pydantic literal_error on import. CONTRIBUTING notes that a datajoint.json from save_template() sets the backend to "postgresql" explicitly, so MySQL users change the backend, not only the port. --- CONTRIBUTING.md | 1 + src/datajoint/connection.py | 54 +++++-- src/datajoint/settings.py | 93 +++++++++--- .../unit/test_mysql_port_requires_backend.py | 100 ++++++++++-- tests/unit/test_settings.py | 142 +++++++++++++++++- 5 files changed, 350 insertions(+), 40 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d97b27e7d..06ebcd80b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -130,6 +130,7 @@ For `DJ_USE_EXTERNAL_CONTAINERS=1`: | `DJ_PASS` | `password` | MySQL password | The test suite reads `DJ_HOST`, `DJ_PORT`, `DJ_USER`, and `DJ_PASS` as the MySQL server. Outside the tests, these variables configure whichever backend `DJ_BACKEND` selects, PostgreSQL by default. The backend is never inferred from the port: `DJ_PORT=3306` without `DJ_BACKEND` raises an error on connecting, so set `DJ_BACKEND=mysql` for a MySQL server. +A `datajoint.json` made with `dj.config.save_template()` sets the backend to `"postgresql"` explicitly, so for a MySQL server change its `backend` to `"mysql"` rather than only changing the port. ### Object Storage diff --git a/src/datajoint/connection.py b/src/datajoint/connection.py index 49d6a23cf..fd943e528 100644 --- a/src/datajoint/connection.py +++ b/src/datajoint/connection.py @@ -39,7 +39,7 @@ MYSQL_DEFAULT_PORT = 3306 -def _check_mysql_port_without_backend(host: str, port, backend_is_default: bool) -> None: +def _check_mysql_port_without_backend(host: str, port, backend_is_default: bool, uses_global_config: bool = True) -> None: """ Refuse MySQL's default port when the backend was left at its default. @@ -48,24 +48,57 @@ def _check_mysql_port_without_backend(host: str, port, backend_is_default: bool) connection stops before any network access and says how to set the backend. A backend set explicitly, including ``"postgresql"``, allows any port. + Parameters + ---------- + host : str + Hostname, for the message. + port : int or str + The resolved port. A value that is not an integer is left to the adapter. + backend_is_default : bool + True when neither the ``backend`` argument nor the config set the backend. + uses_global_config : bool, optional + True when the connection reads the global ``dj.config`` (``dj.conn``, + ``dj.Connection``). False for a ``dj.Instance``, whose own config + ``dj.config`` does not reach, so the message names the ways an + Instance takes the backend instead. + Raises ------ DataJointError If ``backend_is_default`` and the port is 3306. """ - if not backend_is_default or str(port) != str(MYSQL_DEFAULT_PORT): + if not backend_is_default: return + try: + is_mysql_port = int(port) == MYSQL_DEFAULT_PORT + except (TypeError, ValueError): + return + if not is_mysql_port: + return + if uses_global_config: + how_to_set = ( + "For a MySQL server, set the backend to 'mysql' in one of these ways:\n" + " - environment: DJ_BACKEND=mysql\n" + ' - datajoint.json: {"database": {"backend": "mysql"}}\n' + " - in Python: dj.config['database.backend'] = 'mysql'\n" + " - keyword: dj.Connection(..., backend='mysql')\n" + ) + else: + how_to_set = ( + "This connection belongs to a dj.Instance, which reads its settings only from the " + "environment, datajoint.json, and its keyword arguments; dj.config does not reach it.\n" + "For a MySQL server, set the backend to 'mysql' in one of these ways:\n" + " - keyword: dj.Instance(..., backend='mysql') or dj.Instance(..., database__backend='mysql')\n" + " - environment: DJ_BACKEND=mysql\n" + ' - datajoint.json: {"database": {"backend": "mysql"}}\n' + ) raise errors.DataJointError( f"Connecting to {host}:{port} with the database backend not set. " f"Port {MYSQL_DEFAULT_PORT} is MySQL's default port, but the backend defaults to PostgreSQL " "since DataJoint 2.4, and DataJoint does not infer the backend from the port.\n" - "For a MySQL server, set the backend to 'mysql' in one of these ways:\n" - " - environment: DJ_BACKEND=mysql\n" - ' - datajoint.json: {"database": {"backend": "mysql"}}\n' - " - in Python: dj.config['database.backend'] = 'mysql'\n" - " - keyword: dj.Instance(..., backend='mysql') or dj.Connection(..., backend='mysql')\n" - "For a PostgreSQL server, use its port, 5432 by default, or set the backend to " - "'postgresql' explicitly to keep port 3306." + f"{how_to_set}" + f"PostgreSQL's default port is 5432. To reach a PostgreSQL server on port {MYSQL_DEFAULT_PORT}, " + "set the backend to 'postgresql' explicitly." ) @@ -274,7 +307,8 @@ def __init__( backend_is_default = backend is None and "backend" not in self._config.database.model_fields_set if backend is None: backend = self._config["database.backend"] - _check_mysql_port_without_backend(host, port, backend_is_default) + # Only the global config is reached by dj.config; any other config here is a dj.Instance's. + _check_mysql_port_without_backend(host, port, backend_is_default, uses_global_config=self._config is config) try: self.adapter = get_adapter(backend) diff --git a/src/datajoint/settings.py b/src/datajoint/settings.py index dc5f30672..475c2e614 100644 --- a/src/datajoint/settings.py +++ b/src/datajoint/settings.py @@ -186,6 +186,9 @@ def read_secret_file(secrets_dir: Path | None, name: str) -> str | None: return None +VALID_BACKENDS = ("mysql", "postgresql") + + class DatabaseSettings(BaseSettings): """Database connection settings.""" @@ -229,6 +232,43 @@ class DatabaseSettings(BaseSettings): "Set to False for production mode to prevent automatic table creation.", ) + @model_validator(mode="before") + @classmethod + def ignore_empty_backend_env(cls, data: Any) -> Any: + """ + Treat an empty ``DJ_BACKEND`` as not set, so the backend stays at its default. + + An empty variable leaves ``backend`` out of the fields set, as if + ``DJ_BACKEND`` were absent; the port check on connecting then still + applies. + """ + if not isinstance(data, dict): + return data + empty = [ + key + for key, value in data.items() + if isinstance(key, str) and key.lower() == "dj_backend" and isinstance(value, str) and not value.strip() + ] + return {key: value for key, value in data.items() if key not in empty} if empty else data + + @field_validator("backend", mode="before") + @classmethod + def normalize_backend(cls, value: Any) -> Any: + """ + Accept the backend name in any case; refuse any other value with the valid names. + + Raises + ------ + DataJointError + If the value is not ``"mysql"`` or ``"postgresql"`` (in any case). + """ + if isinstance(value, str) and value.strip().lower() in VALID_BACKENDS: + return value.strip().lower() + raise DataJointError( + f"Invalid database backend {value!r} (database.backend, DJ_BACKEND). " + f"Valid values: {', '.join(repr(b) for b in VALID_BACKENDS)}." + ) + @model_validator(mode="after") def set_default_port_from_backend(self) -> "DatabaseSettings": """ @@ -918,9 +958,16 @@ def override(self, **kwargs: Any) -> Iterator["Config"]: ... # config.safemode is False here ... pass >>> # config.safemode is restored + + Notes + ----- + On exit each overridden setting gets back its value and whether it was + set explicitly. A setting that was not set before the block is not set + after it, and a default derived from other settings (``database.port`` + from ``database.backend``) is derived again. """ - # Store original values - backup = {} + # key parts -> (settings object, original value, whether it was set explicitly) + backup: dict[tuple[str, ...], tuple[Any, Any, bool]] = {} # Convert double underscore to nested access converted = {} @@ -935,28 +982,34 @@ def override(self, **kwargs: Any) -> Iterator["Config"]: # Save originals and apply overrides for key_parts, value in converted.items(): if len(key_parts) == 1: - key = key_parts[0] - if hasattr(self, key): - backup[key_parts] = copy.deepcopy(getattr(self, key)) - setattr(self, key, value) + obj, attr = self, key_parts[0] elif len(key_parts) == 2: group, attr = key_parts - if hasattr(self, group): - group_obj = getattr(self, group) - if hasattr(group_obj, attr): - backup[key_parts] = copy.deepcopy(getattr(group_obj, attr)) - setattr(group_obj, attr, value) + obj = getattr(self, group, None) + else: + continue + if obj is None or not hasattr(obj, attr): + continue + if key_parts not in backup: + backup[key_parts] = (obj, copy.deepcopy(getattr(obj, attr)), attr in obj.model_fields_set) + setattr(obj, attr, value) yield self finally: - # Restore original values - for key_parts, original in backup.items(): - if len(key_parts) == 1: - setattr(self, key_parts[0], original) - elif len(key_parts) == 2: - group, attr = key_parts - setattr(getattr(self, group), attr, original) + # Restore in reverse order, with the fields-set state: a setting that was not + # set explicitly before the block gets its value back and is not set after it. + for key_parts, (obj, original, was_set) in reversed(list(backup.items())): + attr = key_parts[-1] + if was_set: + setattr(obj, attr, original) + continue + field = type(obj).model_fields.get(attr) + # A field whose default is None may hold a value derived from other settings + # (database.port from database.backend). Assigning None runs the validators, + # which derive it again from the restored settings. + setattr(obj, attr, None if field is not None and field.default is None else original) + obj.model_fields_set.discard(attr) @staticmethod def save_template( @@ -977,7 +1030,9 @@ def save_template( the secrets directory entirely (env-var-only configuration). The template selects the PostgreSQL backend on port 5432. For a MySQL - server, set ``backend`` to ``"mysql"`` and ``port`` to 3306. + server, set ``backend`` to ``"mysql"`` and ``port`` to 3306. Changing + only the port is not enough: the template sets the backend explicitly, + so port 3306 with ``"postgresql"`` is taken as a PostgreSQL server. Parameters ---------- diff --git a/tests/unit/test_mysql_port_requires_backend.py b/tests/unit/test_mysql_port_requires_backend.py index bcae1c815..f47bf8c49 100644 --- a/tests/unit/test_mysql_port_requires_backend.py +++ b/tests/unit/test_mysql_port_requires_backend.py @@ -6,7 +6,10 @@ a DataJointError before any network access, whichever way the port was given: ``DJ_PORT``, ``datajoint.json``, ``dj.config`` assignment, ``dj.Instance`` and ``dj.Connection`` arguments, or ``host:port``. A backend set explicitly, to -``"mysql"`` or to ``"postgresql"``, allows port 3306. No database server is needed. +``"mysql"`` or to ``"postgresql"``, allows port 3306. The message suggests +``dj.config`` for a connection that reads the global config, and the Instance's +own sources (keywords, ``DJ_BACKEND``, ``datajoint.json``) for a ``dj.Instance``. +No database server is needed. """ import importlib @@ -100,12 +103,27 @@ def _instance(**kwargs): return lambda: Instance(host="localhost", user="user", password="password", use_tls=False, **kwargs) -# --- The error message -------------------------------------------------------- +# --- The error message ------------------------------------------------------------ +REWORDED = ( + "PostgreSQL's default port is 5432. To reach a PostgreSQL server on port 3306, set the backend to 'postgresql' explicitly." +) -def test_message_says_why_and_how_to_fix(_isolate): - """The message names port 3306 as MySQL's, the PostgreSQL default, each fix, and port 5432.""" - message = _refused(_connection(Config(), 3306), _isolate) + +def _use_global_config(monkeypatch): + """Give dj.conn and dj.Connection a fresh global config, shared as in a real session.""" + config = Config() + monkeypatch.setattr(_module("datajoint.connection"), "config", config) + monkeypatch.setattr(_module("datajoint"), "_global_config", config) + monkeypatch.setattr(_module("datajoint.instance"), "_global_config", config) + monkeypatch.setattr(_module("datajoint.instance"), "_singleton_connection", None) + return config + + +def test_message_for_global_config(monkeypatch, _isolate): + """Through dj.config, the message names port 3306 as MySQL's, each fix including dj.config, and 5432.""" + _use_global_config(monkeypatch) + message = _refused(lambda: Connection("localhost", "user", "password", 3306, use_tls=False), _isolate) assert "localhost:3306" in message assert "MySQL's default port" in message assert "backend not set" in message @@ -114,7 +132,72 @@ def test_message_says_why_and_how_to_fix(_isolate): assert '{"database": {"backend": "mysql"}}' in message assert "dj.config['database.backend'] = 'mysql'" in message assert "backend='mysql'" in message - assert "5432" in message + assert "dj.Instance" not in message + assert message.endswith(REWORDED) + + +def test_message_for_dj_conn(monkeypatch, _isolate): + """dj.conn reads the global config, so its message suggests dj.config.""" + dj = _module("datajoint") + config = _use_global_config(monkeypatch) + config["database.port"] = 3306 + message = _refused(lambda: dj.conn("localhost", "user", "password", reset=True, use_tls=False), _isolate) + assert "dj.config['database.backend'] = 'mysql'" in message + assert "dj.Instance" not in message + assert message.endswith(REWORDED) + + +def test_message_for_instance(_isolate): + """An Instance's config is not dj.config, so the message names the Instance's own sources.""" + message = _refused(_instance(port=3306), _isolate) + assert "localhost:3306" in message + assert "MySQL's default port" in message + assert ( + "dj.Instance, which reads its settings only from the environment, datajoint.json, and its keyword arguments" + ) in message + assert "dj.config does not reach it" in message + assert "dj.Instance(..., backend='mysql')" in message + assert "database__backend='mysql'" in message + assert "DJ_BACKEND=mysql" in message + assert "dj.config['database.backend']" not in message + assert message.endswith(REWORDED) + + +def test_message_for_instance_from_env_port(monkeypatch, _isolate): + monkeypatch.setenv("DJ_PORT", "3306") + message = _refused(_instance(), _isolate) + assert "dj.Instance(..., backend='mysql')" in message + assert "dj.config['database.backend']" not in message + + +# --- The port is compared as a number ------------------------------------------------ + + +@pytest.mark.parametrize("port", [3306, "3306", "03306", 3306.0]) +def test_port_compared_numerically(port): + check = _module("datajoint.connection")._check_mysql_port_without_backend + with pytest.raises(_module("datajoint.errors").DataJointError, match="MySQL's default port"): + check("localhost", port, True) + + +@pytest.mark.parametrize("port", [None, "", "mysql", 3307, "5432"]) +def test_other_or_unparsable_port_passes(port): + check = _module("datajoint.connection")._check_mysql_port_without_backend + check("localhost", port, True) + check("localhost", 3306, False) + + +# --- override() leaves no backend set behind --------------------------------------- + + +def test_override_backend_then_port_3306_raises(_isolate): + """After an override of the backend ends, the backend is not set, so port 3306 is refused.""" + config = Config() + with config.override(database__backend="mysql"): + pass + config["database.port"] = 3306 + assert "backend" not in config.database.model_fields_set + _refused(_connection(config), _isolate) # --- Each way of setting port 3306 without a backend raises --------------------- @@ -166,10 +249,9 @@ def test_port_in_host_raises(_isolate): def test_dj_conn_raises(monkeypatch, _isolate): """dj.conn takes no port, but a port in the host or in config counts.""" dj = _module("datajoint") - monkeypatch.setattr(dj, "_global_config", Config()) - monkeypatch.setattr(_module("datajoint.instance"), "_singleton_connection", None) + config = _use_global_config(monkeypatch) _refused(lambda: dj.conn("localhost:3306", "user", "password", use_tls=False), _isolate) - dj._global_config["database.port"] = 3306 + config["database.port"] = 3306 _refused(lambda: dj.conn("localhost", "user", "password", reset=True, use_tls=False), _isolate) diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index 781456324..69cc8d8bc 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -247,6 +247,40 @@ def test_override_nested_value(self): assert dj.config.database.host == "override_host" assert dj.config.database.host == original + def test_override_restores_fields_set(self): + """A setting not set before the block is not set after it; a set one stays set.""" + from datajoint.settings import Config + + cfg = Config() + assert "backend" not in cfg.database.model_fields_set + with cfg.override(database__backend="mysql"): + assert (cfg.database.backend, cfg.database.port) == ("mysql", 3306) + assert (cfg.database.backend, cfg.database.port) == ("postgresql", 5432) + assert "backend" not in cfg.database.model_fields_set + assert "port" not in cfg.database.model_fields_set + + cfg.database.host = "db.example.com" + with cfg.override(database__host="other", safemode=False): + pass + assert cfg.database.host == "db.example.com" + assert "host" in cfg.database.model_fields_set + assert "safemode" not in cfg.model_fields_set + + def test_override_rederives_port(self): + """An overridden port that was not set returns to following the backend.""" + from datajoint.settings import Config + + cfg = Config() + with cfg.override(database__port=3306, database__backend="mysql"): + assert cfg.database.port == 3306 + assert (cfg.database.backend, cfg.database.port) == ("postgresql", 5432) + assert "port" not in cfg.database.model_fields_set + + with cfg.override(database__port=6543): + cfg.database.backend = "mysql" # a lasting change made inside the block + assert cfg.database.port == 3306 + assert "port" not in cfg.database.model_fields_set + def test_override_restores_on_exception(self): """Test that override restores values even when exception occurs.""" original = dj.config.safemode @@ -1155,13 +1189,73 @@ def test_port_env_var_overrides_backend_default(self, monkeypatch): assert settings.port == 8888 def test_invalid_backend(self, monkeypatch): - """Test invalid backend raises validation error.""" + """An invalid backend raises a DataJointError that lists the valid values.""" + # Imported here: another unit test re-imports the datajoint modules. + from datajoint.errors import DataJointError from datajoint.settings import DatabaseSettings monkeypatch.setenv("DJ_BACKEND", "sqlite") - with pytest.raises(ValidationError, match="Input should be 'mysql' or 'postgresql'"): + with pytest.raises(DataJointError, match="Valid values: 'mysql', 'postgresql'"): DatabaseSettings() + def test_invalid_backend_assignment(self): + """Assigning an invalid backend raises the same error and keeps the backend.""" + # Imported here: another unit test re-imports the datajoint modules. + from datajoint.errors import DataJointError + from datajoint.settings import DatabaseSettings + + settings = DatabaseSettings() + with pytest.raises(DataJointError, match="'oracle'.*Valid values: 'mysql', 'postgresql'"): + settings.backend = "oracle" + with pytest.raises(DataJointError, match="Valid values"): + settings.backend = "" + assert settings.backend == "postgresql" + assert "backend" not in settings.model_fields_set + + @pytest.mark.parametrize("value", ["MySQL", "MYSQL", " mysql "]) + def test_backend_env_any_case(self, monkeypatch, value): + """DJ_BACKEND is read in any case and normalized to lowercase.""" + from datajoint.settings import DatabaseSettings + + monkeypatch.setenv("DJ_BACKEND", value) + settings = DatabaseSettings() + assert settings.backend == "mysql" + assert settings.port == 3306 + assert "backend" in settings.model_fields_set + + def test_backend_assignment_any_case(self): + from datajoint.settings import DatabaseSettings + + settings = DatabaseSettings() + settings.backend = "MySQL" + assert (settings.backend, settings.port) == ("mysql", 3306) + settings.backend = "PostgreSQL" + assert (settings.backend, settings.port) == ("postgresql", 5432) + + @pytest.mark.parametrize("value", ["", " "]) + def test_empty_backend_env_is_not_set(self, monkeypatch, value): + """An empty DJ_BACKEND counts as not set: the default backend, not set explicitly.""" + from datajoint.settings import DatabaseSettings + + monkeypatch.setenv("DJ_BACKEND", value) + settings = DatabaseSettings() + assert settings.backend == "postgresql" + assert settings.port == 5432 + assert "backend" not in settings.model_fields_set + + def test_empty_backend_env_does_not_hide_config_file(self, monkeypatch, tmp_path): + """With DJ_BACKEND empty, the backend in datajoint.json applies.""" + import json + + from datajoint.settings import Config + + monkeypatch.setenv("DJ_BACKEND", "") + config_file = tmp_path / "datajoint.json" + config_file.write_text(json.dumps({"database": {"backend": "mysql"}})) + cfg = Config() + cfg.load(config_file) + assert (cfg.database.backend, cfg.database.port) == ("mysql", 3306) + def test_config_file_backend(self, tmp_path, monkeypatch): """Test loading backend from config file.""" import json @@ -1262,3 +1356,47 @@ 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 TestBackendEnvAtImport: + """DJ_BACKEND as set before ``import datajoint``, checked in a fresh interpreter.""" + + SCRIPT = "import datajoint as dj\ndb = dj.config.database\nprint(db.backend, db.port, 'backend' in db.model_fields_set)\n" + + @staticmethod + def _import_with(tmp_path, backend): + import os + import subprocess + import sys + + env = {k: v for k, v in os.environ.items() if not k.startswith("DJ_")} + env.update(DJ_BACKEND=backend, DJ_IGNORE_CONFIG_FILE="true") + return subprocess.run( + [sys.executable, "-c", TestBackendEnvAtImport.SCRIPT], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + timeout=120, + ) + + @pytest.mark.parametrize( + ("backend", "expected"), + [ + ("MySQL", "mysql 3306 True"), + ("POSTGRESQL", "postgresql 5432 True"), + ("", "postgresql 5432 False"), + ], + ) + def test_import_succeeds(self, tmp_path, backend, expected): + result = self._import_with(tmp_path, backend) + assert result.returncode == 0, result.stderr + assert result.stdout.strip().splitlines()[-1] == expected + + def test_import_invalid_backend_lists_valid_values(self, tmp_path): + result = self._import_with(tmp_path, "oracle") + assert result.returncode != 0 + assert "DataJointError" in result.stderr + assert "Invalid database backend 'oracle'" in result.stderr + assert "Valid values: 'mysql', 'postgresql'" in result.stderr + assert "literal_error" not in result.stderr