Skip to content

feat(tes/data/crypt4gh): add the Crypt4GH plugin - #66

Merged
uniqueg merged 10 commits into
devfrom
feat/65-crypt4gh
Nov 12, 2026
Merged

uniqueg merged 10 commits into
devfrom
feat/65-crypt4gh

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Moves the Crypt4GH middleware of proTES (protes-middleware-crypt4gh) here as the plugin tes.data.crypt4gh (plugins/tes/data/crypt4gh/, distribution foca-plugin-tes-data-crypt4gh, phase request, maturity experimental).

  • Plugin (__init__.py, task.py): finds the Crypt4GH files and secret keys among a task's inputs by suffix (encrypted_suffixes, default .c4gh; key_suffixes, default .sec), adds a volume (volume, default /vol/crypt4gh) and a decryption executor (image, required; command, default crypt4gh-decrypt) before the task's own executors, and points whole executor arguments and stdin that name a Crypt4GH input (in any spelling of its absolute path) to its decrypted file. Tasks without Crypt4GH inputs, and tasks it changed already, are left unchanged. It rejects tasks with 422 when there are Crypt4GH inputs but no key, when names collide or are empty/./.., when Crypt4GH paths are not absolute and normalized or other task paths are relative, when a task path is the volume, inside it or one of its parents (for wildcard outputs, the directory before the first wildcard), or when an output has the path of a Crypt4GH input or a wildcard matching one. Annotations hold counts only.
  • Gateway-neutral parts, kept apart from the TES rewrite for a later WES variant: inputs.py (which inputs are Crypt4GH files and keys, by path) and decrypt.py (the decryption script; stdlib plus crypt4gh, not imported by the plugin).
  • Decryption image (image/Dockerfile): Python 3.13 by digest, crypt4gh pinned with hashes (image/requirements.txt), the script as crypt4gh-decrypt, and an allowlist .dockerignore (with .env* excluded). CI's new job smoke ("Smoke test", added to the gate's needs) builds the image without pushing it, runs image/smoke.sh on it and audits its pinned packages. Dependabot updates the base image digest and the image's packages, except crypt4gh itself, which is updated by hand together with the tests' version.
  • Tests: pytest at 100% coverage (unit, FOCA contract check, harness, entry-point pipeline, and a test that runs the script with the executor the plugin generates). Keys and Crypt4GH files are created at test time in temporary directories, so the repository contains no key fixtures and the secret scanners have nothing to flag. No allowlist entry or inline suppression is needed.
  • Docs: plugin README (behaviour, settings, proTES configuration example, image, keys and decrypted data, changes from the middleware), CHANGELOG, plugins/tes/README.md. The catalogue picks the plugin up from its README.

Behaviour changes from the middleware

The README's "Changes from the middleware" section lists them:

  • Only .c4gh inputs are decrypted, and only .sec inputs are passed as keys. Other inputs stay where they are.
  • The suffix is removed from decrypted file names.
  • Decrypted files are 0644, and inputs may be mounted read-only.
  • A failed decryption fails the task.
  • The volume is a setting, no longer a random path per process.
  • The image is a setting.

Open work in the old repository

Verification

  • uv run ruff check, ruff format --check, ast-grep scan and python -m scripts.packages mypy on plugins/tes/data/crypt4gh: passed.
  • coverage run --source plugins/tes/data/crypt4gh/src -m pytest plugins/tes/data/crypt4gh with coverage report: 112 passed, 100%, on each of these combinations:
    • Python 3.13 with FOCA 0.22.0
    • Python 3.11 with FOCA 0.18.0
    • Python 3.15 with FOCA dev, which gets crypt4gh 1.7 (see below)
  • pre-commit run --all-files: passed. gitleaks dir on the plugin's files: no leaks.
  • coverage run --source scripts,docs -m pytest tests: 140 passed, 100%. mkdocs build --strict: passed; the catalogue lists the plugin.
  • uv build --all-packages with python -m scripts.checks dist: passed.
  • docker build -f image/Dockerfile … with image/smoke.sh: passed. pip-audit on the image requirements: no known vulnerabilities.
  • CI: all checks passed, including the new "Smoke test" job and the full test matrix (Python 3.11, 3.13 and 3.15 × FOCA 0.18.0 to 0.22.0 and dev).
  • Two independent review rounds were run on the branch, one checking correctness and one checking maintainability. Their findings are fixed, except those listed below.
  • Sourcery's 11 threads: 8 fixed in the last commit (path aliases, parents of the volume, non-string output paths, executors: null, repeated rewrites, overlapping suffixes, cleanup errors, the malformed-lists test), 3 answered (see below). Two correctness review rounds on the fixes found a way to skip the checks with a task that looked rewritten (fixed: only an exact match of the decryption executor counts, and such tasks are still checked), plus missing or empty executors, relative and wildcard paths and a null input type (all fixed).
  • Sourcery's second review (9 threads): 5 fixed in d7ba853 (// volume settings, executors added to a rewritten task, malformed tasks left to the app before their inputs are checked, key paths checked only with Crypt4GH files, an independent copy in the idempotence test), 4 answered (see below). A correctness review of d7ba853 found one low (malformed tasks get no annotations), documented in 58b5756.

Decisions

  • Python 3.15 in the tests. crypt4gh 1.8 has no wheels for Python 3.15 yet, and its sdist needs libsodium. The dev group therefore pins crypt4gh 1.7 for Python 3.15 through an environment marker. 1.7 is pure Python and has the same API, and CI passes with it. When 1.8 wheels for 3.15 appear, the marker can be dropped.

Declined review findings

  • Rewriting executor stdout, stderr and workdir that point into the volume is declined. These are paths of the client's own task; the client holds the keys, and writing there only affects the client's own decrypted copies. The README documents which fields are rewritten.
  • Running pip-audit through the locked dev environment in the smoke job, instead of pinning it in a pipx run, is declined. Setting up uv and the dev environment would add minutes to a job that has no other use for them. The pin follows the workflow's existing pattern of versions updated by hand (e.g. cffconvert), and its comment points to uv.lock.
  • Failing the decryption on existing files at the targets, instead of replacing them (and removing them on failure), is declined. The volume belongs to one task, whose executors run once each, in order; refusing existing files would break restarted executors (e.g. a rescheduled Kubernetes pod). The README says so.
  • Restricting the decrypted files to the executor's user (0600/0700) is declined: the task's next executors may run as other users. The README documents the modes as deliberate.
  • Serializing concurrent decryption attempts on one volume is declined, for the same reason as the rollback above.
  • Resolving symbolic links when matching arguments to inputs is declined: the gateway can't see the container's file system; inputs must have normalized paths, and the volume checks test both spellings.
  • Passing the paths through a manifest instead of the command line is declined for now: the usual 2 MiB argument limit allows thousands of paths; the README states the bound.
  • Sourcery's "image is not published": follow-up ci: publish the Crypt4GH decryption image #69, as above.
  • Detecting decryption executors added by a gateway with other settings (image, command or volume) is declined; the README says to chain gateways with this plugin only with the same settings.
  • Building the image for linux/arm64 is declined for now. The image is linux/amd64 only, as documented, until it is published (see the follow-ups).

Follow-ups

Maintainer follow-ups (not blocking this PR)

  1. Publishing the image (ci: publish the Crypt4GH decryption image #69). CI builds and tests the image but does not push it, and no release workflow, secret or registry has been added. Before operators can use the plugin without building the image themselves, the maintainer has to choose a Docker Hub repository (e.g. elixircloud/foca-plugin-tes-data-crypt4gh-decrypt, or another name) and create it. Publishing would then be a follow-up issue that extends release.yml with an image job: push by digest, scan, sign and attest on the plugin's release tag, using the org's existing Docker Hub secrets. Until then, the README tells operators to build the image themselves.
  2. Archiving the old repository (maintainer step after the first release): change its README to point here, then archive it.

Closes #65

🤖 Generated with Claude Code

https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV

uniqueg and others added 4 commits November 11, 2026 23:16
Move the Crypt4GH middleware of proTES (protes-middleware-crypt4gh)
here as the plugin tes.data.crypt4gh (request phase). It finds the
Crypt4GH files and secret keys among a task's inputs by suffix, adds a
volume and a decryption executor before the task's own executors, and
points the executors' arguments to the decrypted files.

The gateway-neutral parts (inputs.py: which inputs are Crypt4GH files
and keys; decrypt.py: the decryption script) are separate from the TES
rewrite (task.py), so that a WES variant can reuse them. Tests make
their keys and Crypt4GH files at runtime, so the repository holds no
key fixtures.

Closes #65

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Add the image of the plugin's decryption executor (image/Dockerfile:
Python 3.13 by digest, crypt4gh pinned with hashes, the script as
crypt4gh-decrypt), an allowlist .dockerignore, and a smoke test that
CI's new job smoke runs on the built image (not pushed). Dependabot
updates the base image digest and the image's packages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Address the review of the plugin:

- Reject Crypt4GH inputs that decrypt to `.` or `..`, and check the
  reserved volume also against normalized paths (`..`, `//`).
- Take task fields of the wrong type as absent instead of failing.
- The decryption script removes its temporary file and earlier targets
  on any error (also of writing a target or creating its directory),
  and says why a key can't be read.
- The smoke test decrypts two files with two keys, checks the modes,
  and checks the cleanup after a later failure; CI audits the image's
  pinned packages, and Dependabot leaves crypt4gh itself to manual
  updates (kept in step with the tests' version).
- Fix the README on where decrypted files go.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Address the second review round:

- Crypt4GH inputs and keys need absolute, normalized paths, so that
  executor arguments and outputs that name them are recognized.
- Tasks whose executors or volumes are no lists are left unchanged,
  for the app's validation to reject.
- The decryption script logs targets that it can't remove after a
  failure and still exits with status 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
@sourcery-ai

sourcery-ai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Define the gateway-neutral input classification and path utilities that the plugin and TES rewrite use to identify Crypt4GH files and keys.

  • plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/inputs.py L1-188

API

Expose the plugin class and validated settings, register the tes.data.crypt4gh entry point, and package its namespace module.

  • plugins/tes/data/crypt4gh/pyproject.toml L1-65
  • plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/__init__.py L1-200

Implementation

Implement the TES task rewrite, including safety checks, idempotence, executor insertion, and argument and stdin aliasing.

  • plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py L1-312

Implement the standalone decryption command, including key loading, file permissions, temporary writes, and cleanup on failure.

  • plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/decrypt.py L1-214

Configuration

Configure the decryption image and its pinned dependency inputs, and restrict the image build context with an allowlist.

  • plugins/tes/data/crypt4gh/.dockerignore L1-10
  • plugins/tes/data/crypt4gh/image/Dockerfile L1-45
  • plugins/tes/data/crypt4gh/image/requirements.in L1-11

Configure Dependabot updates for the image base and packages while keeping the Crypt4GH version synchronized manually with the tests.

  • .github/dependabot.yml L23-48

Add the development test dependency and its Python-version-specific Crypt4GH pins.

  • pyproject.toml L27-32

Add the always-running CI image build, smoke-test and dependency-audit job, and require it in the gate.

  • .github/workflows/ci.yml L5-6, L299-326, L337

Documentation

Document the plugin’s behaviour, settings, image, data handling, installation and operational differences from the former middleware.

  • plugins/tes/data/crypt4gh/README.md L1-242

Record the new plugin feature and its decryption image in the plugin changelog.

  • plugins/tes/data/crypt4gh/CHANGELOG.md L1-17

Add the Crypt4GH plugin to the TES plugin subgroup overview.

  • plugins/tes/README.md L11-12

Add the plugin’s license file.

  • plugins/tes/data/crypt4gh/LICENSE L1-201

Tests

Test plugin validation and request rewriting through unit cases, FOCA contract checks, the harness, and the registered pipeline.

  • plugins/tes/data/crypt4gh/tests/test_crypt4gh.py L1-690

Test decryption of generated Crypt4GH fixtures, including failure cleanup, permissions, and execution with plugin-generated arguments.

  • plugins/tes/data/crypt4gh/tests/test_decrypt.py L1-564

Test suffix-based input classification, path normalization, and rejection of invalid or ambiguous inputs.

  • plugins/tes/data/crypt4gh/tests/test_inputs.py L1-130

Smoke-test the built image with generated keys and encrypted files, including read-only inputs and rollback after a decryption failure.

  • plugins/tes/data/crypt4gh/image/smoke.sh L1-68

Lock files and vendored code

Add the hash-pinned, compiled package lock used by the decryption image.

  • plugins/tes/data/crypt4gh/image/requirements.txt L1-283

Update the repository dependency lock for the new development dependencies.

  • uv.lock L385-454, L1011-1075, L3090-3124 (+4 small edits)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@read-the-docs-community

read-the-docs-community Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 foca-plugins | 🛠️ Build #35827675 | 📁 Comparing 58b5756 against latest (bc4bd8d)

  🔍 Preview build  

1 file changed
± catalogue/index.html

@codecov

codecov Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (bc4bd8d) to head (58b5756).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev       #66    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files            6        10     +4     
  Lines          553       826   +273     
  Branches        71       111    +40     
==========================================
+ Hits           553       826   +273     
Flag Coverage Δ
foca-plugin-generic-example-noop 100.00% <ø> (ø)
foca-plugin-generic-routing-random 100.00% <ø> (ø)
foca-plugin-tes-data-crypt4gh 100.00% <100.00%> (?)
foca-plugin-tes-routing-distance 100.00% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 11, 2026 23:46
@sourcery-ai

sourcery-ai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 58b5756

#65 feat(tes/data/crypt4gh): move the Crypt4GH middleware · 5 of 7 met · 1 to check by hand

# Requirement Status Notes
1 Add the tes.data.crypt4gh plugin for TES request-phase decryption, with documented behaviour and settings and a changelog. ✅ Met The plugin, settings, README and CHANGELOG are included.
2 Keep gateway-neutral input detection and key handling separate from the TES-specific task rewrite. ✅ Met inputs.py and decrypt.py are separate from the TES rewrite in task.py.
3 Build and publish the decryption image from this repository, or keep it where it is with a documented reason; make the plugin image reference configurable. 🟡 Partly met The image is built and smoke-tested here, and its reference is configurable, but publication is deferred to follow-up #69; the PR says CI does not push it.
4 Port tests to pytest with 100% coverage and mark test keys and encrypted fixtures as test data for secret scanners. ✅ Met The tests create keys and encrypted files at runtime, so no repository fixtures or scanner suppressions are needed.
5 Account for old-repository issue #31, issue #32, PR #29 and PR #33, stating what is included and what becomes follow-up work. ✅ Met The README describes #32 as included, #31 and PR #29 as follow-ups, and PR #33 as superseded.
6 Add the plugin README, catalogue entry and proTES configuration example. ✅ Met The README includes a proTES configuration example; the plugin README is picked up by the catalogue.
7 After the plugin's first release, point the old repository's README here and archive that repository. 👀 Check by hand (manual process) After the first release, a maintainer must update the old repository's README and archive it.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 11 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/decrypt.py" line_range="107-108" />
<code_context>
+    except Exception as error:
+        raise DecryptionError(f"Can't decrypt {source}: {error}") from error
+    finally:
+        if part is not None:
+            part.unlink(missing_ok=True)
+
+
</code_context>
<issue_to_address>
**Failed cleanup leaves plaintext behind**

When unlinking the temporary file fails while a decryption or write error is being handled and an earlier target was decrypted, `part.unlink()` raises `OSError` over the original `DecryptionError`, so `main` skips `remove(written)` and leaves earlier decrypted targets in the task volume.

Prevent a temporary-file unlink error from replacing the decryption error, while still ensuring previously written targets are removed.
</issue_to_address>

### Comment 2
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/decrypt.py" line_range="101-126" />
<code_context>
+        part.chmod(FILE_MODE)
</code_context>
<issue_to_address>
**Decrypted data is world-readable**

When a TES backend shares task volumes with untrusted host users who can traverse the task workspace, `decrypt_file` sets plaintext files to mode 0644 and `open_directories` sets the volume directory to 0755, so other host users who can traverse the task workspace can read the decrypted inputs.

Keep plaintext and directory permissions private to the task, or require isolated task-volume access rather than granting world read and traverse permissions.
</issue_to_address>

### Comment 3
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/decrypt.py" line_range="102" />
<code_context>
+            with source.open("rb") as infile:
+                decrypt(keys=key_tuples, infile=infile, outfile=outfile)
+        part.chmod(FILE_MODE)
+        part.replace(target)
+        part = None
+    except Exception as error:
</code_context>
<issue_to_address>
**Rollback deletes another attempt's files**

When a retry or concurrent executor reuses the configured volume and a target already contains another attempt's plaintext, `part.replace(target)` overwrites an existing target, and `remove(written)` later unlinks it if this attempt fails on another file. When a retry or concurrent executor shares the volume, the failing attempt therefore deletes plaintext that was already present or written by the other attempt.

Use per-attempt isolated target paths, or preserve and restore pre-existing targets rather than deleting them during rollback.

Also at `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/decrypt.py:204`.
</issue_to_address>

### Comment 4
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py" line_range="122" />
<code_context>
+    """
+    encrypted = {file.path for file in found.files}
+    for index, item in objects(task, "outputs"):
+        if item.get("path") in encrypted:
+            raise InputError(
+                f"outputs[{index}]: path is that of a Crypt4GH input, which is"
</code_context>
<issue_to_address>
**Path aliases expose encrypted files**

When an output path, executor argument, or stdin uses a non-normalized spelling of a Crypt4GH input path, `check_outputs` and `rewrite` compare raw strings, so the alias passes the output guard and remains pointed at the encrypted input; the backend can return or overwrite ciphertext instead of using the decrypted file.

Normalize paths consistently when checking outputs and rewriting executor arguments and stdin.

Also at `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py:186-187`, `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py:191`.
</issue_to_address>

### Comment 5
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/inputs.py" line_range="128" />
<code_context>
+        if path is None:
+            continue
+        name = decrypted_name(path, encrypted)
+        is_key = name is None and decrypted_name(path, keys_suffixes) is not None
+        if name is None and not is_key:
+            continue
</code_context>
<issue_to_address>
**Overlapping suffixes misclassify keys**

When configured encrypted and key suffixes overlap and a key filename ends with both, `_check_suffixes` accepts the configuration and `classify` checks encrypted suffixes first, so it treats the key as ciphertext and the task fails or tries to decrypt the key file.

Reject suffix configurations that can match the same filename, or classify matching key suffixes before encrypted suffixes.

Also at `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/__init__.py:105-106`.
</issue_to_address>

### Comment 6
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py" line_range="122" />
<code_context>
+    """
+    encrypted = {file.path for file in found.files}
+    for index, item in objects(task, "outputs"):
+        if item.get("path") in encrypted:
+            raise InputError(
+                f"outputs[{index}]: path is that of a Crypt4GH input, which is"
</code_context>
<issue_to_address>
**Malformed paths crash requests**

When a task has Crypt4GH inputs and an output object's `path` is a list or object, `check_outputs` tests the unhashable path against `encrypted`, raising `TypeError`; because `on_request` catches only `InputError`, the request fails with an internal error.

Validate that an output path is a string before testing membership in `encrypted`.
</issue_to_address>

### Comment 7
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py" line_range="32" />
<code_context>
+        Whether one of the fields is present, not null and no list.
+    """
+    return any(
+        task.get(field) is not None and not isinstance(task[field], list)
+        for field in fields
+    )
</code_context>
<issue_to_address>
**Null executors skip the workload**

When a task with Crypt4GH inputs explicitly sets `executors` to null, `malformed` treats an explicit `executors: null` as absent, then `rewrite` replaces it with a list containing only the decryption executor; the request can therefore run successfully without the task's intended workload.

Treat explicit null executors as malformed and leave the task unchanged for application validation, or reject it before rewriting.

Also at `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py:192`.
</issue_to_address>

### Comment 8
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py" line_range="98" />
<code_context>
+    for field in ("inputs", "outputs"):
+        for index, item in objects(task, field):
+            path = item.get("path")
+            if isinstance(path, str) and within(path, volume):
+                raise InputError(
+                    f"{field}[{index}]: path is reserved for decrypted files"
</code_context>
<issue_to_address>
**Ancestor paths block decryption**

When a task input or volume is an ancestor of the configured decryption volume, `check_paths` checks only whether a task path is inside the plugin volume, so it accepts an input at `/vol` when the configured volume is `/vol/crypt4gh`. TES stages the input at `/vol`, then the decryption executor cannot create `/vol/crypt4gh` and the task fails.

Reject task paths that overlap the plugin volume in either direction, including paths that are ancestors of it.

Also at `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py:103`.
</issue_to_address>

### Comment 9
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py" line_range="104" />
<code_context>
+                )
+    for index, path in enumerate(items(task, "volumes")):
+        if isinstance(path, str) and within(path, volume):
+            raise InputError(f"volumes[{index}]: path is reserved for decrypted files")
+
+
</code_context>
<issue_to_address>
**Repeated processing rejects its own task**

When the same plugin processes an already-transformed request a second time, `check_paths` rejects the volume that the first pass appended, so a second pass through this plugin returns 422 instead of preserving the already-transformed task. The task is rejected when the plugin is selected twice in a pipeline or an already-transformed request is replayed through it.

Make the rewrite idempotent or distinguish plugin-added state from conflicting task-provided volumes.

Also at `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py:196`.
</issue_to_address>

### Comment 10
<location path=".github/workflows/ci.yml" line_range="316" />
<code_context>
+        with:
+          persist-credentials: false
+      - name: Build image
+        run: docker build -f image/Dockerfile -t "${IMAGE}" .
+        working-directory: plugins/tes/data/crypt4gh
+      - name: Run smoke test
</code_context>
<issue_to_address>
**Image is not published**

The issue asks for the decryption image to be published from this repository (or kept in its old location with a documented reason). CI builds and smoke-tests it but does not publish it; the README defers publishing to follow-up work.
</issue_to_address>

### Comment 11
<location path="plugins/tes/data/crypt4gh/tests/test_crypt4gh.py" line_range="341-352" />
<code_context>
+        {"inputs": ["x", None], "executors": [1]},
+    ],
+)
+def test_on_request_takes_malformed_fields_as_absent(
+    plugin: Crypt4gh, task: dict[str, Any]
+) -> None:
+    """Fields of the wrong type don't apply; the app validates them later.
+
+    Args:
+        plugin: Plugin.
+        task: Task without Crypt4GH inputs, with fields of the wrong type.
+    """
+    request = make_inbound(task)
+    plugin.on_request(request, make_context())
+    assert request.payload == task
+
+
</code_context>
<issue_to_address>
**Malformed fields bypassed**

When the malformed-field guard stops working while the test inputs still contain no Crypt4GH files, `test_on_request_takes_malformed_fields_as_absent` passes even if the malformed-field guard is broken: neither task has a Crypt4GH input, so `on_request` returns before checking `executors` or `volumes`, and the equality assertion at line 352 only checks that the payload was unchanged.

Include a valid Crypt4GH file and key in these cases so the hook reaches the malformed-field guard.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 11 findings to address first, and the plugin passes task-supplied secret keys to a new executor and writes decrypted files, readable by all, onto the backend’s task volume. Reverting removes the feature, but cannot undo plaintext already accessed or copied.

Blocking findings: plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/decrypt.py:108, plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/decrypt.py:126, plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/decrypt.py:102, plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py:122, plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/inputs.py:128, and 6 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread .github/workflows/ci.yml Resolved
@uniqueg
uniqueg marked this pull request as draft November 11, 2026 23:52
uniqueg and others added 3 commits November 12, 2026 01:11
Address the automated review of the plugin:

- Compare the paths of outputs, arguments and stdin with the Crypt4GH
  inputs after normalizing them, so that spellings such as /in/./a.c4gh
  are rewritten or rejected; skip outputs whose path is no string.
- Reject inputs, outputs and volumes that are parents of the volume of
  the decrypted files (e.g., /vol or /).
- Treat a null executors list as malformed.
- Leave tasks that the plugin changed already as they are.
- Reject suffix settings where one suffix ends with another.
- Log, rather than raise, a failure to remove a temporary file, so that
  the decryption error is reported.
- Document the file modes, the rollback and the new checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
A task counted as changed by the plugin when its first executor had the
decryption image and command, which skipped all path checks. Count it
only if the first executor is exactly the one the plugin would add and
the volume is there once, and still check its paths and outputs (except
for that volume).

Also leave tasks with missing or empty executors to the app, check only
absolute paths for overlaps with the volume, and say in the README that
chained gateways need the same settings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Reject relative paths of inputs, outputs and volumes in tasks with
Crypt4GH inputs, as the plugin can't tell where they lead. Check outputs
with wildcards by the directory before the first wildcard, and reject
those that match a Crypt4GH input. Take inputs with a null type for
files, as the backends do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
@uniqueg
uniqueg marked this pull request as ready for review November 12, 2026 01:15
@uniqueg

uniqueg commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 9 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/__init__.py" line_range="86" />
<code_context>
+            ValueError: The path is not absolute, not normalized (e.g., with
+                `.`, `..`, `//` or a trailing slash), or `/`.
+        """
+        path = PurePosixPath(value)
+        if (
+            not path.is_absolute()
</code_context>
<issue_to_address>
**Overlapping paths bypass volume checks**

When the configured volume starts with exactly two slashes, such as `//vol/crypt4gh`, `_check_volume` accepts the double-leading-slash path, and `within` or `overlaps` compares it separately from the equivalent single-slash path. Linux resolves both spellings to the same location, so task paths can overlap or export the decryption volume.

Reject double-leading-slash volume paths or normalize them so volume checks use the same path identity as Linux.

Also at `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/inputs.py:99-100`, `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/inputs.py:115`, `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/__init__.py:89`, `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py:161`.
</issue_to_address>

### Comment 2
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py" line_range="271" />
<code_context>
+    executors = items(task, "executors")
+    volumes = items(task, "volumes")
+    expected = decryption_executor(found, image=image, command=command, volume=volume)
+    if executors[:1] != [expected] or volumes.count(volume) != 1:
+        return None
+    return volumes.index(volume)
</code_context>
<issue_to_address>
**Executors receive encrypted files**

When a submitted task contains the exact generated decryption executor and volume but retains an encrypted input in its executor arguments or `stdin`, `rewritten` accepts the matching executor and volume without checking the remaining executor arguments or `stdin`, so `on_request` returns without applying the aliases. The task executor receives ciphertext and produces incorrect results.

Have `rewritten` verify that all executor arguments and `stdin` references are rewritten before `on_request` treats the task as already processed.

Also at `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/__init__.py:200-201`.
</issue_to_address>

### Comment 3
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/decrypt.py" line_range="102" />
<code_context>
+            with source.open("rb") as infile:
+                decrypt(keys=key_tuples, infile=infile, outfile=outfile)
+        part.chmod(FILE_MODE)
+        part.replace(target)
+        part = None
+    except Exception as error:
</code_context>
<issue_to_address>
**Concurrent retries delete outputs**

When two attempts of the same task run concurrently and share a volume, a second decryption process can replace a target after the first process has written it; if the first then fails on a later file, `remove(written)` unlinks that shared target. The second process can finish successfully, but the task's next executor sees a missing decrypted file.

Serialize decryption attempts per task volume or isolate each attempt's outputs so one attempt cannot remove another's files.

Also at `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/decrypt.py:207`.
</issue_to_address>

### Comment 4
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py" line_range="177" />
<code_context>
+        Crypt4GH input, in any spelling (e.g., `//in/a.c4gh`); else `value`.
+    """
+    if absolute(value):
+        return targets.get(normalize(value), value)
+    return value
+
</code_context>
<issue_to_address>
**Arguments map to the wrong file**

When an executor argument or output contains `..` after a symlink component, `alias` uses lexical normalization for path identity, but POSIX resolves `..` after following symlinks. It therefore rewrites a path that resolves to a different file as a Crypt4GH input, causing the task to read the wrong data or receive a 422 for an unrelated output.

Use POSIX symlink-resolution semantics when matching paths to encrypted inputs instead of treating lexical normalization as filesystem identity.

Also at `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py:201`, `plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/inputs.py:83`.
</issue_to_address>

### Comment 5
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py" line_range="240-242" />
<code_context>
+    """
+    arguments = list(command)
+    for key in found.keys:
+        arguments += ["--key", key]
+    for file in found.files:
+        arguments += ["--file", file.path, target(volume, file.name)]
+    return {"image": image, "command": arguments}
+
</code_context>
<issue_to_address>
**Large tasks exceed argument limits**

When a task has enough Crypt4GH inputs or keys that the generated command exceeds the platform’s argument-size limit, `decryption_executor` adds every key and file path to the executor command, so the container runtime eventually hits the operating system’s argument-size limit and the decryption process fails to start; the task fails before its own executors run.

Pass the paths through a mounted manifest or process them in bounded batches instead of placing every path on the command line.
</issue_to_address>

### Comment 6
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/__init__.py" line_range="172" />
<code_context>
+            raise NotApplicable("payload is no task")
+        settings = self.settings
+        try:
+            found = classify(
+                input_paths(task),
+                encrypted_suffixes=settings.encrypted_suffixes,
</code_context>
<issue_to_address>
**Malformed tasks are rejected early**

When a task has no executors or malformed `executors`/`volumes` and also has a Crypt4GH input with an invalid path or no matching key, `classify` runs before the no-executor and malformed-field guards, so it raises for the input path or missing key and the plugin rejects the request instead of leaving the task for the gateway app to validate.

Run the no-executor and malformed-field guards before calling `classify`.
</issue_to_address>

### Comment 7
<location path="plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/inputs.py" line_range="159" />
<code_context>
+            continue
+        # Normalized, so that the paths of executors and outputs that name
+        # the input are recognized by plain comparison
+        if normalize(path) != path:
+            raise InputError(f"{field}[{index}]: path must be absolute and normalized")
+        if is_key:
</code_context>
<issue_to_address>
**Unrelated key inputs reject tasks**

When a task has a `.sec` input with a non-normalized path, such as `/keys/./alice.sec`, and no Crypt4GH input, `classify()` validates a `.sec` path even when there are no encrypted files, so an otherwise unrelated key input with an absolute but non-normalized path raises `InputError` and the plugin rejects a task it says it leaves unchanged.

Only validate key paths after confirming that the task has at least one encrypted file.
</issue_to_address>

### Comment 8
<location path="plugins/tes/data/crypt4gh/tests/test_crypt4gh.py" line_range="603" />
<code_context>
+    again = make_inbound(once)
+    ctx = make_context()
+    plugin.on_request(again, ctx)
+    assert again.payload == once
+    assert ctx.annotations["encrypted_inputs"] == 1
+
</code_context>
<issue_to_address>
**Repeated rewrite goes unnoticed**

When `make_inbound(once)` retains the supplied payload object and the plugin regresses by adding its executor and volume again, `test_on_request_is_idempotent` compares `again.payload` with `once` after passing `once` directly to `make_inbound`; when that helper retains the payload object, a second call that appends another executor and volume mutates both references, so the equality assertion passes.

Deep-copy `once` before the second call and compare the result with that independent snapshot.
</issue_to_address>

### Comment 9
<location path=".github/workflows/ci.yml" line_range="301" />
<code_context>
         run: uv run --no-sync mkdocs build --strict
+  # The image of `tes.data.crypt4gh`'s decryption executor
+  # (`plugins/tes/data/crypt4gh/image/`): built, not pushed (it is not
+  # published yet), and run on a key pair and a Crypt4GH file made in the
+  # test, as the plugin's executor runs it. Always runs (a minute or two), so
+  # that the gate needs no rule for a skip
</code_context>
<issue_to_address>
**Image is not published**

The issue asks for the decryption image to be published from this repository or retained in its former location with a documented reason. This change builds and smoke-tests the image here but explicitly does not push it; publication is deferred to follow-up work, so operators must build and publish it themselves.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 9 findings to address first, and the plugin passes secret-key paths to a new executor and writes decrypted inputs to a task volume, where the task’s other executors can read them. If a path or rewrite error exposes plaintext beyond the intended task, reverting cannot undo data already accessed or copied.

Blocking findings: plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/__init__.py:86, plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py:271, plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/decrypt.py:102, plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py:177, plugins/tes/data/crypt4gh/src/foca_plugins/tes/data/crypt4gh/task.py:242, and 4 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread .github/workflows/ci.yml Resolved
uniqueg and others added 2 commits November 12, 2026 02:46
- Reject volume settings with a leading //, which PurePosixPath keeps
  but the checks of task paths normalize away.
- Change the arguments of executors added to a task that the plugin
  changed already, instead of leaving them on the encrypted files.
- Leave malformed tasks to the app before checking their inputs.
- Check the paths of keys only if there are Crypt4GH files.
- Compare the idempotence test with an independent copy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
@uniqueg
uniqueg merged commit acbfb0c into dev Nov 12, 2026
177 of 252 checks passed
@uniqueg
uniqueg deleted the feat/65-crypt4gh branch November 12, 2026 01:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(tes/data/crypt4gh): move the Crypt4GH middleware

1 participant