diff --git a/.github/dependabot.yml b/.github/dependabot.yml index aac560ed2..0b0fbc610 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,8 +5,30 @@ updates: schedule: interval: "monthly" day: "wednesday" - time: "9:00" + time: "09:00" 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" + # 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 + patterns: [ "*" ] 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/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..456b254c7 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -1,4 +1,6 @@ name: Lint +permissions: + contents: read on: push: branches: @@ -14,16 +16,19 @@ jobs: lint: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - # enforce the same check as pre-commit - # but only run important checks - - uses: pre-commit/action@v3.0.1 - with: - extra_args: codespell --all-files - - uses: pre-commit/action@v3.0.1 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: - extra_args: ruff --all-files - - uses: pre-commit/action@v3.0.1 + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + # enforce the same check as pre-commit + # 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: 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 diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index a3f2bc5c8..1435f8b38 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -1,5 +1,8 @@ name: Test +permissions: + contents: read + on: push: branches: @@ -11,6 +14,7 @@ on: - "tests/**" - "pyproject.toml" - "pixi.lock" + - ".github/scripts/minimum_requirements.py" - ".github/workflows/test.yaml" pull_request: branches: @@ -22,6 +26,7 @@ on: - "tests/**" - "pyproject.toml" - "pixi.lock" + - ".github/scripts/minimum_requirements.py" - ".github/workflows/test.yaml" jobs: @@ -40,10 +45,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 +65,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 +93,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 }} @@ -104,3 +114,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/CONTRIBUTING.md b/CONTRIBUTING.md index 06f1accda..14fce4642 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -54,12 +54,13 @@ pixi run -e test pytest -m postgresql # PostgreSQL tests only export DOCKER_HOST=unix://$HOME/.docker/run/docker.sock ``` -### PostgreSQL Backend +### Database Backends -DataJoint supports MySQL 8.0.13+ and PostgreSQL 15+ as production database backends. To install the PostgreSQL driver: +DataJoint supports PostgreSQL 15+ and MySQL 8.0.13+ as production database backends. Each database driver is an optional extra, and the `test` and `dev` extras install both: ```bash pip install -e ".[postgres]" # Installs psycopg2-binary +pip install -e ".[mysql]" # Installs pymysql ``` Tests automatically spin up both MySQL and PostgreSQL containers via testcontainers. Backend-parameterized tests (those using the `backend` fixture in `tests/conftest.py`) run against both backends to ensure feature parity. diff --git a/Dockerfile b/Dockerfile index 88c046345..28c94f18a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -19,6 +19,6 @@ USER root RUN \ chown -R ${HOST_UID:-1000}:mambauser /main && \ chown -R ${HOST_UID:-1000}:mambauser /src && \ - ${CONDA_BIN} run -n base pip install -q --no-cache-dir /main && \ + ${CONDA_BIN} run -n base pip install -q --no-cache-dir "/main[postgres,mysql]" && \ rm -r /main/* USER ${MAMBA_USER} diff --git a/README.md b/README.md index 7b68d185b..099864cc3 100644 --- a/README.md +++ b/README.md @@ -57,8 +57,11 @@ The **DataJoint Library** is a framework for scientific data pipelines based on ## Installation +Install DataJoint with the driver for your database: + ```bash -pip install datajoint +pip install "datajoint[postgres]" # PostgreSQL +pip install "datajoint[mysql]" # MySQL ``` or with Conda: diff --git a/RELEASE_MEMO.md b/RELEASE_MEMO.md index 1a3623330..34466534d 100644 --- a/RELEASE_MEMO.md +++ b/RELEASE_MEMO.md @@ -143,7 +143,9 @@ If the bot doesn't create a PR, manually update the feedstock: curl -sL https://pypi.org/pypi/datajoint/2.1.0/json | jq -r '.urls[] | select(.packagetype=="sdist") | .digests.sha256' ``` -4. **Check dependencies** match `pyproject.toml`: +4. **Check dependencies** match `pyproject.toml`. conda has no extras, so `run` + also lists the database drivers that `pyproject.toml` keeps in the `mysql` and + `postgres` extras: ```yaml requirements: host: @@ -153,7 +155,8 @@ If the bot doesn't create a PR, manually update the feedstock: run: - python >={{ python_min }} - numpy - - pymysql >=0.7.2 + - pymysql >=1.1.1 + - psycopg2 >=2.9.0 - deepdiff - pyparsing - pandas diff --git a/pixi.lock b/pixi.lock index e287ed2ae..e18d7e337 100644 --- a/pixi.lock +++ b/pixi.lock @@ -111,7 +111,6 @@ environments: - pypi: https://files.pythonhosted.org/packages/cf/4e/35a80cae583a37cf15604b44240e45c05e04e86f9cfd766623149297e971/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl - pypi: https://files.pythonhosted.org/packages/c1/60/5d4751ba3f4a40a6891f24eec885f51afd78d208498268c734e256fb13c4/pydantic_settings-2.12.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/7e/32/a7125fb28c4261a627f999d5fb4afff25b523800faed2c30979949d6facd/pydot-4.0.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/7c/4c/ad33b92b9864cbde84f259d5df035a6447f91891f5be77788e2a3892bce3/pymysql-1.1.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/53/b8/fbab973592e23ae313042d450fc26fa24282ebffba21ba373786e1ce63b4/pyparsing-3.2.4-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/14/1b/a298b06749107c305e1fe0f814c6c74aea7b2f1e10989cb30f544a1b3253/python_dotenv-1.2.1-py3-none-any.whl @@ -236,7 +235,6 @@ environments: - pypi: https://files.pythonhosted.org/packages/15/df/a4c740c0943e93e6500f9eb23f4ca7ec9bf71b19e608ae5b579678c8d02f/pydantic_core-2.41.5-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl - pypi: https://files.pythonhosted.org/packages/c1/60/5d4751ba3f4a40a6891f24eec885f51afd78d208498268c734e256fb13c4/pydantic_settings-2.12.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/7e/32/a7125fb28c4261a627f999d5fb4afff25b523800faed2c30979949d6facd/pydot-4.0.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/7c/4c/ad33b92b9864cbde84f259d5df035a6447f91891f5be77788e2a3892bce3/pymysql-1.1.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/10/5e/1aa9a93198c6b64513c9d7752de7422c06402de6600a8767da1524f9570b/pyparsing-3.2.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/14/1b/a298b06749107c305e1fe0f814c6c74aea7b2f1e10989cb30f544a1b3253/python_dotenv-1.2.1-py3-none-any.whl @@ -316,7 +314,6 @@ environments: - pypi: https://files.pythonhosted.org/packages/94/02/abfa0e0bda67faa65fef1c84971c7e45928e108fe24333c81f3bfe35d5f5/pydantic_core-2.41.5-cp313-cp313-macosx_11_0_arm64.whl - pypi: https://files.pythonhosted.org/packages/c1/60/5d4751ba3f4a40a6891f24eec885f51afd78d208498268c734e256fb13c4/pydantic_settings-2.12.0-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/7e/32/a7125fb28c4261a627f999d5fb4afff25b523800faed2c30979949d6facd/pydot-4.0.1-py3-none-any.whl - - pypi: https://files.pythonhosted.org/packages/7c/4c/ad33b92b9864cbde84f259d5df035a6447f91891f5be77788e2a3892bce3/pymysql-1.1.2-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/10/5e/1aa9a93198c6b64513c9d7752de7422c06402de6600a8767da1524f9570b/pyparsing-3.2.5-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/14/1b/a298b06749107c305e1fe0f814c6c74aea7b2f1e10989cb30f544a1b3253/python_dotenv-1.2.1-py3-none-any.whl @@ -4495,31 +4492,33 @@ packages: requires_python: '>=3.8' - pypi: ./ name: datajoint - version: 2.3.5.dev28+ge3d2a553e.d20261024 - sha256: 9ac2b52fcb44ab2d1c54ec75a4c390fc2a8d53b0480a2490d897c2dc22f593a3 + version: 2.3.5.dev45+gcc4ca9e3d.d20261106 + sha256: 204220782b38892346a27748aa110b40929b1a0075f07b5b72fabd073c84a924 requires_dist: - - deepdiff - deepdiff<9 ; python_full_version >= '3.15' + - deepdiff>=6.6.0 - fsspec>=2023.1.0 - - networkx - - numpy - - packaging - - pandas + - networkx>=3.0 + - numpy>=1.22.4 + - packaging>=22.0 + - pandas>=2.2.2 - pydantic-settings>=2.0.0 - - pydot - - pymysql>=0.7.2 - - pyparsing - - tqdm + - pydot>=3.0.0 + - pyparsing>=3.1.1 + - tqdm>=4.66.3 - pyarrow>=14.0.0 ; extra == 'arrow' - adlfs>=2023.1.0 ; extra == 'azure' - codespell ; extra == 'dev' - polars>=0.20.0 ; extra == 'dev' - pre-commit ; extra == 'dev' + - psycopg2-binary>=2.9.0 ; extra == 'dev' - pyarrow>=14.0.0 ; extra == 'dev' + - pymysql>=1.1.1 ; extra == 'dev' - pytest ; extra == 'dev' - pytest-cov ; extra == 'dev' - ruff ; extra == 'dev' - gcsfs>=2023.1.0 ; extra == 'gcs' + - pymysql>=1.1.1 ; extra == 'mysql' - polars>=0.20.0 ; extra == 'polars' - psycopg2-binary>=2.9.0 ; extra == 'postgres' - s3fs>=2023.1.0 ; extra == 's3' @@ -4529,6 +4528,7 @@ packages: - polars>=0.20.0 ; extra == 'test' - psycopg2-binary>=2.9.0 ; extra == 'test' - pyarrow>=14.0.0 ; extra == 'test' + - pymysql>=1.1.1 ; extra == 'test' - pytest ; extra == 'test' - pytest-cov ; extra == 'test' - requests ; extra == 'test' diff --git a/pyproject.toml b/pyproject.toml index 47c1019e7..01d49484d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,20 +6,28 @@ build-backend = "hatchling.build" name = "datajoint" dynamic = ["version"] dependencies = [ - "numpy", - "pymysql>=0.7.2", - "deepdiff", + "numpy>=1.22.4", + # 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'", - "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 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", + # 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" @@ -97,6 +105,8 @@ test = [ "ipython", "graphviz", "testcontainers[mysql,postgres]>=4.0", + "pymysql>=1.1.1", + "psycopg2-binary>=2.9.0", "polars>=0.20.0", "pyarrow>=14.0.0", ] @@ -105,7 +115,11 @@ test = [ s3 = ["s3fs>=2023.1.0"] gcs = ["gcsfs>=2023.1.0"] azure = ["adlfs>=2023.1.0"] +# Database drivers: install the extra for each backend in use. postgres = ["psycopg2-binary>=2.9.0"] +# pymysql 1.0 adds the ssl_disabled connection option; 1.1.1 fixes +# CVE-2024-36039. +mysql = ["pymysql>=1.1.1"] polars = ["polars>=0.20.0"] arrow = ["pyarrow>=14.0.0"] viz = ["matplotlib", "ipython"] @@ -118,6 +132,7 @@ test = [ "ipython", "s3fs>=2023.1.0", "testcontainers[mysql,postgres]>=4.0", + "pymysql>=1.1.1", "psycopg2-binary>=2.9.0", "polars>=0.20.0", "pyarrow>=14.0.0", @@ -129,6 +144,8 @@ dev = [ # including test "pytest", "pytest-cov", + "pymysql>=1.1.1", + "psycopg2-binary>=2.9.0", "polars>=0.20.0", "pyarrow>=14.0.0", ] @@ -240,7 +257,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/__init__.py b/src/datajoint/__init__.py index 69c6df269..716376558 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, it is + reconnected with these unless it already satisfies them. 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 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) + 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() @@ -278,7 +286,7 @@ def FreeTable(conn_or_name, full_table_name: str | None = None) -> _FreeTable: # ============================================================================= # Lazy imports — heavy dependencies loaded on first access # ============================================================================= -# These modules import heavy dependencies (networkx, matplotlib, click, pymysql) +# These modules import heavy dependencies (networkx, matplotlib, click) # that slow down `import datajoint`. They are loaded on demand. _lazy_modules = { diff --git a/src/datajoint/adapters/base.py b/src/datajoint/adapters/base.py index 1aa12f52f..fbe56cddf 100644 --- a/src/datajoint/adapters/base.py +++ b/src/datajoint/adapters/base.py @@ -7,9 +7,48 @@ from __future__ import annotations +import importlib from abc import ABC, abstractmethod +from types import ModuleType from typing import Any +from ..errors import DataJointError + + +def import_driver(module: str, backend: str, extra: str) -> ModuleType: + """ + Import a database driver, or name the extra that installs it. + + Database drivers are optional extras, so adapters import them when they are + created rather than when ``datajoint`` is imported. + + Parameters + ---------- + module : str + Import name of the driver, e.g. ``'pymysql'`` or ``'psycopg2'``. + backend : str + Backend name for the error message, e.g. ``'MySQL'``. + extra : str + The ``datajoint`` extra that installs the driver, e.g. ``'mysql'``. + + Returns + ------- + ModuleType + The imported driver module. + + Raises + ------ + DataJointError + If the driver is not installed. + """ + try: + return importlib.import_module(module) + except ImportError as error: + raise DataJointError( + f"The {backend} backend requires the {module} driver, which is not installed. " + f'Install it with: pip install "datajoint[{extra}]"' + ) from error + class DatabaseAdapter(ABC): """ diff --git a/src/datajoint/adapters/mysql.py b/src/datajoint/adapters/mysql.py index 38e3ad1b1..d56078bcc 100644 --- a/src/datajoint/adapters/mysql.py +++ b/src/datajoint/adapters/mysql.py @@ -7,12 +7,22 @@ from __future__ import annotations +import ssl from typing import Any -import pymysql as client - from .. import errors -from .base import DatabaseAdapter +from .base import DatabaseAdapter, import_driver + +# The pymysql driver (the ``datajoint[mysql]`` extra), imported when the first +# MySQLAdapter is created so that ``import datajoint`` loads no database driver. +client: Any = None + +# PyMySQL subclasses that enforce use_tls, defined by _define_tls_classes() +# once the driver is imported. +_CLIENT_SSL: int = 0 +_TLSUnavailableError: Any = None +_TLSRequiredConnection: Any = None +_TLSPreferredConnection: Any = None # Core type mapping: DataJoint core types → MySQL types CORE_TYPE_MAP = { @@ -45,9 +55,80 @@ } +def _define_tls_classes() -> None: + """Define the PyMySQL subclasses that enforce use_tls; called after pymysql is imported.""" + global _CLIENT_SSL, _TLSUnavailableError, _TLSRequiredConnection, _TLSPreferredConnection + if _TLSUnavailableError is not None: + return + import pymysql + from pymysql.constants import CLIENT, CR + + class TLSUnavailableError(pymysql.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(pymysql.connections.Connection): + """ + PyMySQL connection that does not authenticate without TLS. + + 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 + + # 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: # 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() # type: ignore[misc] + + class TLSPreferredConnection(TLSRequiredConnection): + """PyMySQL connection that uses TLS when the server offers it and continues without TLS otherwise.""" + + tls_required = False + + _CLIENT_SSL = CLIENT.SSL + _TLSUnavailableError = TLSUnavailableError + _TLSRequiredConnection = TLSRequiredConnection + _TLSPreferredConnection = TLSPreferredConnection + + +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.""" + def __init__(self) -> None: + """ + Initialize MySQL adapter. + + Raises + ------ + DataJointError + If pymysql is not installed (``pip install "datajoint[mysql]"``). + """ + global client + client = import_driver("pymysql", backend="MySQL", extra="mysql") + _define_tls_classes() + # ========================================================================= # Connection Management # ========================================================================= @@ -76,7 +157,13 @@ 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). + 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``, + the server certificate is verified. False: TLS disabled. - charset: Character set (default from kwargs) Returns @@ -86,9 +173,11 @@ 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 + 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 None or 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 @@ -107,13 +196,22 @@ def connect( if ssl_config is False: # Explicitly disable SSL conn_params["ssl_disabled"] = True - elif ssl_config is not None: - # Enable SSL with config dict (can be empty for defaults) - conn_params["ssl"] = ssl_config - # Explicitly enable SSL by setting ssl_disabled=False - conn_params["ssl_disabled"] = False - - return client.connect(**conn_params) + 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: # PyMySQL internal + connection.close() + raise _TLSUnavailableError() + return connection def close(self, connection: Any) -> None: """Close the MySQL connection.""" @@ -175,9 +273,7 @@ def get_cursor(self, connection: Any, as_dict: bool = False) -> Any: Any pymysql cursor object. """ - import pymysql - - cursor_class = pymysql.cursors.DictCursor if as_dict else pymysql.cursors.Cursor + cursor_class = client.cursors.DictCursor if as_dict else client.cursors.Cursor return connection.cursor(cursor=cursor_class) # ========================================================================= @@ -219,8 +315,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: @@ -892,7 +988,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..472cb7b93 100644 --- a/src/datajoint/adapters/postgres.py +++ b/src/datajoint/adapters/postgres.py @@ -7,18 +7,64 @@ from __future__ import annotations +import logging import re from typing import Any -try: - import psycopg2 as client - from psycopg2 import sql -except ImportError: - client = None # type: ignore - sql = None # type: ignore - from .. import errors -from .base import DatabaseAdapter +from .base import DatabaseAdapter, import_driver + +# The psycopg2 driver (the ``datajoint[postgres]`` extra), imported when the first +# PostgreSQLAdapter is created so that ``import datajoint`` loads no database driver. +# Either the psycopg2 or the psycopg2-binary distribution provides it. +client: Any = None + +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"} + + +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]: + """ + 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} + 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" + # 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 ignored for PostgreSQL: %s. Supported: ca, cert, key, password, and check_hostname with ca.", + ", ".join(ignored), + ) + return params + # Core type mapping: DataJoint core types → PostgreSQL types CORE_TYPE_MAP = { @@ -56,11 +102,16 @@ class PostgreSQLAdapter(DatabaseAdapter): """PostgreSQL database adapter implementation.""" def __init__(self) -> None: - """Initialize PostgreSQL adapter.""" - if client is None: - raise ImportError( - "psycopg2 is required for PostgreSQL support. " "Install it with: pip install 'datajoint[postgres]'" - ) + """ + Initialize PostgreSQL adapter. + + Raises + ------ + DataJointError + If psycopg2 is not installed (``pip install "datajoint[postgres]"``). + """ + global client + client = import_driver("psycopg2", backend="PostgreSQL", extra="postgres") # ========================================================================= # Connection Management @@ -90,8 +141,15 @@ 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: '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'. - connect_timeout: Connection timeout in seconds Returns @@ -105,28 +163,41 @@ 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 - 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 @@ -1136,7 +1207,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/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/builtin_codecs/attach.py b/src/datajoint/builtin_codecs/attach.py index 8035810be..5c6e9eb70 100644 --- a/src/datajoint/builtin_codecs/attach.py +++ b/src/datajoint/builtin_codecs/attach.py @@ -4,9 +4,46 @@ from __future__ import annotations +import os +import stat +from pathlib import Path from typing import Any 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. A stored name + with path separators (``/`` or ``\\``), ``..``, a NUL byte, or (on Windows) + a drive or stream marker ``:`` is refused. + """ + if not is_plain_file_name(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 +56,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 +109,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 +134,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 +154,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..abe14c0e6 100644 --- a/src/datajoint/builtin_codecs/filepath.py +++ b/src/datajoint/builtin_codecs/filepath.py @@ -59,6 +59,14 @@ 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: 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. DataJoint does not manage the lifecycle of referenced files. @@ -99,12 +107,16 @@ 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 + from ..storage import path_in_location config = self._codec_config(key, context) if config is None: @@ -117,8 +129,16 @@ 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. 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. + path_normalized = posixpath.normpath(path.replace("\\", "/")).lstrip("/") reserved_prefixes = [] hash_prefix = spec.get("hash_prefix") @@ -129,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. " @@ -147,7 +168,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 +207,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/npy.py b/src/datajoint/builtin_codecs/npy.py index c6eab2118..df9d00b85 100644 --- a/src/datajoint/builtin_codecs/npy.py +++ b/src/datajoint/builtin_codecs/npy.py @@ -4,11 +4,83 @@ from __future__ import annotations +import logging +import os +import shutil +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. 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. + + 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 not stat.S_IMODE(st.st_mode) & 0o077: + return cache_dir + try: + os.chmod(cache_dir, 0o700) + 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: {reason}. Using {_fallback_mmap_cache_dir} for this session.") + return _fallback_mmap_cache_dir + class NpyRef: """ @@ -135,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 -------- @@ -165,15 +238,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/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/condition.py b/src/datajoint/condition.py index 650015539..e9b6cdbfe 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,23 @@ 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)"``: +# 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 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]: """ @@ -56,6 +74,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"]) @@ -167,15 +187,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, @@ -335,18 +353,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 JSON path `{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 +388,25 @@ def prep_value(k, v): list, ), ): - # Use single quotes for string literals (works for both MySQL and PostgreSQL) - return f"{k}='{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): - # 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"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): return f"{'NOT ' if negate else ''} ({')AND('.join(conditions)})" @@ -379,6 +416,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 +488,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/connection.py b/src/datajoint/connection.py index 4e6252e0d..1ac607653 100644 --- a/src/datajoint/connection.py +++ b/src/datajoint/connection.py @@ -79,7 +79,10 @@ 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). The existing connection is reconnected with + these unless it already satisfies them. Returns ------- @@ -105,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 @@ -162,7 +167,11 @@ 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 (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 ---------- @@ -196,17 +205,9 @@ 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 + 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 self._is_closed = True # Mark as closed until connect() succeeds @@ -255,7 +256,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`` 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. + 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"], @@ -263,7 +293,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"] @@ -273,19 +303,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 fails, retry without SSL (if it was auto-detected) - if self.conn_info.get("ssl_input") is None: - 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/src/datajoint/declare.py b/src/datajoint/declare.py index 438bb72b0..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 @@ -172,6 +173,211 @@ def build_attribute_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]: + """ + 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 + ------- + 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 + + 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 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 + ---------- + 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 + + 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: + 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: """ @@ -254,10 +460,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/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..ca2b9be1b 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 @@ -419,6 +422,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: @@ -578,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 @@ -614,6 +622,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 +1210,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 +1460,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 +1537,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 +1593,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..a841bf970 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, ) @@ -775,5 +776,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/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/src/datajoint/objectref.py b/src/datajoint/objectref.py index c312e0c5d..dd060f5f0 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,20 +171,20 @@ 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) - 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 @@ -285,6 +287,13 @@ 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, or if a key inside a folder + object is not made of plain file names. """ self._ensure_backend() destination = Path(destination) @@ -299,12 +308,44 @@ 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(): - 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 0929f301d..981bbc314 100644 --- a/src/datajoint/settings.py +++ b/src/datajoint/settings.py @@ -16,6 +16,15 @@ ``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, 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 -------- >>> import datajoint as dj @@ -47,11 +56,12 @@ import json import logging import os +import stat import warnings 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 @@ -61,6 +71,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,41 +104,203 @@ logger = logging.getLogger(__name__.split(".")[0]) -def find_config_file(start: Path | None = None) -> Path | None: +_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_foreign(uid: int) -> bool: + """True if ``uid`` is neither the current user nor root.""" + return uid not in (os.getuid(), 0) + + +def _open_location(directory: Path) -> Path | None: """ - Search for datajoint.json in current and parent directories. + Find a directory that lets any user create or replace entries in ``directory``. - Searches upward from ``start`` until finding the config file or hitting - a project boundary (``.git``, ``.hg``) or filesystem root. + 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. + + 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 ---------- - start : Path, optional - Directory to start search from. Defaults to current working directory. + path : Path + File found by the search. + hint : str, optional + Advice appended to the warning when the file is ignored. Returns ------- - Path or None - Path to config file if found, None otherwise. + str or None + File contents, or None if the file is missing, not a regular file, or + ignored. + """ + if not hasattr(os, "getuid"): + try: + return path.read_text() + except OSError: + return None + + found_in = path.absolute().parent + try: + link_st = os.lstat(path) + except OSError: + 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 + + 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() + + +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. 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() + 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 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 + + +def _search_config_file(start: Path | None = None) -> tuple[Path | None, str | None]: + """ + Search for datajoint.json and read it. + + Returns + ------- + 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(): - return config_path + 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. @@ -137,6 +310,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 that another user could have placed there is not used, under + the same rule as ``find_config_file``. + Parameters ---------- config_path : Path, optional @@ -150,12 +326,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 _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 + return SYSTEM_SECRETS_DIR if _use_found_dir(SYSTEM_SECRETS_DIR, _SECRETS_HINT) else None return None @@ -164,6 +340,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 @@ -179,11 +358,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(): - 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): @@ -444,6 +620,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 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.", + ) + # Internal: track where config was loaded from _config_path: Path | None = None _secrets_dir: Path | None = None @@ -749,12 +934,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: @@ -842,8 +1030,11 @@ def _load_secrets(self, secrets_dir: Path) -> None: parts = secret_file.name.split(".") if len(parts) == 3 and parts[0] == "stores": + 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] = {} @@ -1131,12 +1322,24 @@ def _create_config() -> Config: config_path: Path | None = None if not cfg.ignore_config_file: - config_path = find_config_file() - if config_path is not None: + # 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) + 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/src/datajoint/storage.py b/src/datajoint/storage.py index 51e1d80cd..60c03ad36 100644 --- a/src/datajoint/storage.py +++ b/src/datajoint/storage.py @@ -9,6 +9,9 @@ import json import logging +import os +import posixpath +import re import secrets import urllib.parse from datetime import datetime, timezone @@ -16,6 +19,7 @@ from typing import Any import fsspec +from fsspec.implementations.local import LocalFileSystem from . import errors @@ -45,6 +49,45 @@ 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_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. @@ -309,8 +352,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: paths with ``..`` components and, for ``file`` stores, + absolute paths outside the location are rejected. """ + confine_paths: bool = True + def __init__(self, spec: dict[str, Any]) -> None: """ Initialize storage backend from configuration spec. @@ -352,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 @@ -429,8 +477,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", "") @@ -445,12 +501,43 @@ 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. + # fsspec before 2024 leaves "." segments in place, so normalize both sides + if self.confine_paths: + 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 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 and self._path_in_location(path) is None) + ): + 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`).""" + 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/table.py b/src/datajoint/table.py index 2c8a4adaa..dd6e979f8 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(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=_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=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(attr, ref) for attr, ref in fk_props["attr_map"].items() if ref != attr + "{}={}".format(_one_line(attr), _quoted(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 = _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, 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, _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(k)) + definition += "{unique}INDEX ({attrs})\n".format( + unique="UNIQUE " if v["unique"] else "", attrs=", ".join(_one_line(a) for a in k) + ) if printout: logger.info("\n" + definition) return definition @@ -1663,6 +1671,16 @@ def check_fields(fields): return row_to_insert +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 _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): """ Find a table's class in the context given its full table name. 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_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")} diff --git a/tests/integration/test_alter.py b/tests/integration/test_alter.py index c593dc30a..2bbfaaa5e 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,62 @@ 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): + """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 = "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=context) + assert described.splitlines()[0] == "# note -> record()" + # 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, 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/integration/test_path_confinement.py b/tests/integration/test_path_confinement.py new file mode 100644 index 000000000..1eaf240e5 --- /dev/null +++ b/tests/integration/test_path_confinement.py @@ -0,0 +1,183 @@ +""" +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" / "outside.txt" + path.parent.mkdir() + path.write_bytes(b"outside") + 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", + ["../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)) + _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" / "outside.txt").exists() + assert not (tmp_path / "a" / "outside.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("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")) + assert (Reference & "ref_id=1").fetch1("file_ref").read() == b"inside" + + meta = _json(Reference, "file_ref", ref_id=1) + meta["path"] = { + "absolute": str(outside), + "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"outside" + 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/integration/test_relational_operand.py b/tests/integration/test_relational_operand.py index eea53288e..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() @@ -608,12 +614,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_restriction_values.py b/tests/integration/test_restriction_values.py new file mode 100644 index 000000000..94c793209 --- /dev/null +++ b/tests/integration/test_restriction_values.py @@ -0,0 +1,205 @@ +""" +Mapping restrictions with values that need quoting, on both backends. + +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 +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}), +] + +SPECIAL_CHARACTER_VALUES = [ + "' 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", 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}}) == [] + 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", 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() + (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] + + +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"], +} +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/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/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_adapters.py b/tests/unit/test_adapters.py index 1e0678150..8b586572e 100644 --- a/tests/unit/test_adapters.py +++ b/tests/unit/test_adapters.py @@ -4,9 +4,14 @@ Tests adapter functionality without requiring actual database connections. """ +import re +import sys + import pytest from datajoint.adapters import DatabaseAdapter, MySQLAdapter, PostgreSQLAdapter, get_adapter +from datajoint.connection import Connection +from datajoint.errors import DataJointError class TestAdapterRegistry: @@ -48,6 +53,45 @@ def test_get_adapter_invalid(self): get_adapter("sqlite") +# Each backend, the driver module its adapter imports, and the extra that installs it. +MISSING_DRIVER_CASES = [ + ("mysql", "pymysql", "mysql"), + ("postgresql", "psycopg2", "postgres"), + ("postgres", "psycopg2", "postgres"), +] + + +class TestMissingDriver: + """A missing database driver is reported with the extra that installs it.""" + + @pytest.mark.parametrize("backend, driver, extra", MISSING_DRIVER_CASES) + def test_get_adapter_names_extra(self, monkeypatch, backend, driver, extra): + """Creating the adapter without its driver raises a DataJointError naming the extra.""" + # A None entry in sys.modules makes `import ` raise ImportError. + monkeypatch.setitem(sys.modules, driver, None) + with pytest.raises(DataJointError, match=re.escape(f'pip install "datajoint[{extra}]"')) as info: + get_adapter(backend) + assert driver in str(info.value) + assert isinstance(info.value.__cause__, ImportError) + + @pytest.mark.parametrize("backend, driver, extra", MISSING_DRIVER_CASES) + def test_connection_names_extra(self, monkeypatch, backend, driver, extra): + """Connecting without the driver fails before contacting any server.""" + monkeypatch.setitem(sys.modules, driver, None) + with pytest.raises(DataJointError, match=re.escape(f'pip install "datajoint[{extra}]"')): + Connection("localhost", "user", "password", backend=backend) + + def test_other_driver_not_required(self, monkeypatch): + """Each backend needs only its own driver.""" + pytest.importorskip("psycopg2") + with monkeypatch.context() as patch: + patch.setitem(sys.modules, "pymysql", None) + assert isinstance(get_adapter("postgresql"), PostgreSQLAdapter) + with monkeypatch.context() as patch: + patch.setitem(sys.modules, "psycopg2", None) + assert isinstance(get_adapter("mysql"), MySQLAdapter) + + class TestMySQLAdapter: """Test MySQL adapter implementation.""" @@ -75,6 +119,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_blob_decompression.py b/tests/unit/test_blob_decompression.py new file mode 100644 index 000000000..9bca71928 --- /dev/null +++ b/tests/unit/test_blob_decompression.py @@ -0,0 +1,73 @@ +"""Compressed blobs expand only up to the size their header declares.""" + +import tracemalloc +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_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) + 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(): + 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_condition.py b/tests/unit/test_condition.py index 3200e34c4..6e6be5ecc 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"]) @@ -93,3 +108,328 @@ 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"), + ), +] + +SPECIAL_CHARACTER_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", +] + + +# 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} + 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, 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, + 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 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 + 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, 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) :], backslash_escapes) + 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", 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", 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", 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", 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}) + 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", 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_value_with_quote_characters(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("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", + [ + ({"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')" + ) + + +@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) diff --git a/tests/unit/test_foreign_key_reference.py b/tests/unit/test_foreign_key_reference.py new file mode 100644 index 000000000..8d4656699 --- /dev/null +++ b/tests/unit/test_foreign_key_reference.py @@ -0,0 +1,172 @@ +"""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 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 + +import pytest + +import datajoint as dj +from datajoint.adapters.mysql import MySQLAdapter +from datajoint.declare import parse_foreign_key_reference, prepare_declare, resolve_foreign_key_reference +from datajoint.errors import DataJointError +from datajoint.table import _one_line, _quoted + + +class Parent(dj.Manual): + definition = """ + parent_id : int32 + """ + + class Part(dj.Part): + definition = """ + -> master + part_id : int32 + """ + + +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) + + +@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( + "reference, expected", + [ + ("Parent", Parent), + (" Parent ", Parent), + ("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, 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", + [ + "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__", + "__builtins__", + "__builtins__.open", + "Parent & 'parent_id=1'", + "Parent.proj(a='b', 'c')", + "Parent.proj(a='b', a='c')", + "", + ], +) +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 == [] + + +@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", ["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_leaves_context_unchanged(context): + """eval() would add __builtins__ to the context it is given; lookup does not.""" + del context["__builtins__"] + resolve_foreign_key_reference("Parent", context) + assert "__builtins__" not in context + + +def test_definition_reference_is_not_called(context, calls): + definition = """ + -> record() + id : int32 + """ + 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)})] diff --git a/tests/unit/test_lazy_imports.py b/tests/unit/test_lazy_imports.py index a87412151..36e33c68d 100644 --- a/tests/unit/test_lazy_imports.py +++ b/tests/unit/test_lazy_imports.py @@ -2,9 +2,11 @@ Tests for lazy import behavior. These tests verify that heavy dependencies (networkx, matplotlib, click) -are not loaded until their associated features are accessed. +are not loaded until their associated features are accessed, and that +``import datajoint`` loads no database driver. """ +import subprocess import sys @@ -85,3 +87,20 @@ def test_core_imports_available(): # Heavy modules should still not be loaded assert "datajoint.diagram" not in sys.modules assert "datajoint.cli" not in sys.modules + + +def test_import_loads_no_database_driver(): + """import datajoint should not import pymysql or psycopg2. + + Drivers are optional extras, so the import must succeed without them and + leave the driver to the adapter that connects. A fresh interpreter is used + so that drivers already imported by other tests do not hide the import. + """ + code = ( + "import sys, warnings\n" + "warnings.simplefilter('ignore')\n" + "import datajoint\n" + "print(sorted(m for m in sys.modules if m.split('.')[0] in ('pymysql', 'psycopg2')))\n" + ) + result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, check=True) + assert result.stdout.strip() == "[]", f"import datajoint loaded database drivers: {result.stdout.strip()}" diff --git a/tests/unit/test_npy_cache.py b/tests/unit/test_npy_cache.py new file mode 100644 index 000000000..f94771327 --- /dev/null +++ b/tests/unit/test_npy_cache.py @@ -0,0 +1,128 @@ +"""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_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 +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_objectref.py b/tests/unit/test_objectref.py new file mode 100644 index 000000000..ac3f4d316 --- /dev/null +++ b/tests/unit/test_objectref.py @@ -0,0 +1,53 @@ +"""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 + + +@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) diff --git a/tests/unit/test_path_confinement.py b/tests/unit/test_path_confinement.py new file mode 100644 index 000000000..0e843f1bd --- /dev/null +++ b/tests/unit/test_path_confinement.py @@ -0,0 +1,432 @@ +"""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. + +No test reads a device or opens a pipe: a regression must fail, not hang. +""" + +import importlib +import os +import sys + +import pytest + +posix_only = pytest.mark.skipif(sys.platform == "win32", reason="needs POSIX paths and symlinks") + + +@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, 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 + + +@pytest.fixture +def layout(tmp_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_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 + + +@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 + + +PATHS_WITH_PARENT_REF = [ + "../outside.txt", + "data/../../outside.txt", + "../store-sibling/sibling.txt", + "..\\outside.txt", + "data/..\\..\\outside.txt", + "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", 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) + + @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 _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_relative_paths_inside(self, layout, path): + _, store, _ = layout + 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): + 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"): + 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): + root, store, _ = layout + backend = StorageBackend({"protocol": "file", "location": str(store)}) + with pytest.raises(DataJointError): + backend.get_buffer(str(root / "outside.txt")) + 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", 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}) + + @posix_only + def test_encode_rejects_absolute_paths_outside_store(self, cfg, layout): + root, store, _ = layout + 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}) + + @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}) + + 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", "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"), + "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") + + 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() + + +# --------------------------------------------------------------------------- # +# and ObjectRef +# --------------------------------------------------------------------------- # +class TestObjectConfinement: + @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}) + + 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_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. + # 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()) + + @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" + + +# --------------------------------------------------------------------------- # +# +# --------------------------------------------------------------------------- # +def _attach_blob(name: str, contents: bytes) -> bytes: + return name.encode("utf-8") + b"\x00" + contents + + +class TestAttachConfinement: + @pytest.mark.parametrize( + "name", + ["../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_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 / "outside.txt").exists() + assert not (downloads / "sub").exists() + + 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"): + 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" + + 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 / "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_reuse_or_write_through_link(self, cfg, layout): + root, _, downloads = layout + downloads.mkdir() + (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("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): + 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() 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"' diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index 1cb535d81..7e42fa92a 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -1,5 +1,9 @@ """Tests for DataJoint settings module.""" +import os +import signal +import stat +import warnings from pathlib import Path import pytest @@ -1197,3 +1201,328 @@ def test_backend_field_in_env_var_mapping(self): assert "database.backend" in ENV_VAR_MAPPING 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 where they are found.""" + + FOREIGN_UID = 54321 + + @pytest.fixture + 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. + """ + 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") + + 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 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, 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 + 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_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) + + assert find_config_file(shared / "project") == shared / CONFIG_FILENAME + + 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_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) + + 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, mark, shared, caplog): + mark(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_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 + target.write_text("{}") + shared = tmp_path / "shared" + (shared / "project").mkdir(parents=True) + (shared / CONFIG_FILENAME).symlink_to(target) + 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, mark, tmp_path): + config_file = tmp_path / CONFIG_FILENAME + config_file.write_text("{}") + secrets_dir = tmp_path / SECRETS_DIRNAME + secrets_dir.mkdir() + 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, mark, tmp_path): + secrets_dir = tmp_path / SECRETS_DIRNAME + secrets_dir.mkdir() + (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") + 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" + + cfg = settings.Config() + cfg._load_secrets(secrets_dir) + 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) + 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_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") + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + 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, 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) + 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_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") + + cfg = settings._create_config() + + assert cfg.database.host == "localhost" + + 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) + mark(shared, world_writable=True, sticky=True) + mark(shared / CONFIG_FILENAME, uid=self.FOREIGN_UID) + + cfg = settings.Config() + cfg.load(shared / CONFIG_FILENAME) + + assert cfg.database.host == "from-shared" diff --git a/tests/unit/test_tls.py b/tests/unit/test_tls.py new file mode 100644 index 000000000..2c9cdf63b --- /dev/null +++ b/tests/unit/test_tls.py @@ -0,0 +1,533 @@ +""" +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. +Connection and dj.conn are checked with a mock adapter. +""" + +import importlib +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 + +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("