Skip to content

feat(plugins): define the WES run request - #782

Merged
uniqueg merged 8 commits into
devfrom
feat/781-wes-run-request
Nov 17, 2026
Merged

uniqueg merged 8 commits into
devfrom
feat/781-wes-run-request

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Summary

Defines how plugins of WES gateways get runs (POST /runs), the same in every gateway and without web-framework types, so that wes plugins (e.g., ones that fetch workflows from TRS) are reusable:

  • foca.plugins.wes: the run is a dict of the form fields, with workflow_params, tags and workflow_engine_parameters parsed from JSON, and the files under workflow_attachment as a list of the new immutable foca.plugins.Attachment(filename, content, media_type) (size, digest). Framework-neutral app helpers: parse_run_request, check_run_request, run_request_form; errors InvalidRunRequest (400) and AttachmentsTooLarge (413), whose messages name fields and positions, never values.
  • Engine: after every request and forward hook of a WES gateway that got a run, the run is checked as payloads are re-validated (invalid_output): safe relative filenames (no absolute paths, drives, backslashes, ./.., control, format or line-separator characters, size limits; also after NFKC), no duplicates or file/directory clashes (also after NFKC and case folding), media types, JSON fields of JSON values, exact types (no subclasses), and the new limits plugins.attachments (max_count 256, max_size 32 MiB).
  • host.start() reads the tags of WES runs from the payload, as for TES tasks.
  • Provenance describes attachments by filename, media type, size and digest, never content.
  • Test kit: make_run_request(), make_inbound(api="wes"); harnesses default to the harness's API.
  • Docs: "WES requests" (plugins guide), "Attachments" (configuration), reference entry, migration notes for 0.23.0 (breaking for WES apps passing another payload shape), FOCA and chart release notes.
  • Chart: maxCount mapped in the plugin keys of foca-common 0.6.0 (unreleased), with a template test.

Closes #781

Verification

  • coverage run -m pytest (with MongoDB on localhost:12345): all passed, 100% coverage.
  • ruff check, ruff format --check, mypy, mkdocs build --strict, pre-commit (semgrep, ast-grep): clean.
  • pytest charts/foca-common/tests with Helm 3.22.1: 435 passed.
  • CI: all checks passed on 9eae3ca (image push/publish and Trivy skipped on PRs, as intended).
  • Sourcery: 9 threads; 8 fixed in 9eae3ca (Windows trailing dots/spaces in segments, exact list for workflow_attachment, check after the app's sanitizer, recursive JSON checks with depth 64, UTF-8 strings, RFC 9110 media type parameters, body-limit hint in the example), 1 declined with reasons (moving run checks inside hook deadlines: checks are linear and bounded by the body limit, and TES payload checks run the same way); all resolved.
  • Reviews: two rounds of adversarial and quality reviewer subagents; all high and medium findings fixed (non-JSON values, NFKC/case duplicates, subclass length and method tricks, line separators, NFKC sizes, docs wording, migration notes).

Declined review findings

  • make_inbound keeps a positional tuple of per-API defaults (low): readable enough; changing it is churn.
  • The error-case loops in test_check_attachments and test_check_run_request stay loops (low): each case asserts its own message, so failures are easy to place.
  • The cached Attachment.digest goes stale only if a plugin deliberately uses object.__setattr__: hostile code, out of scope.
  • The engine doesn't check the client's original run itself (defence in depth): apps call check_run_request before host.start(), as documented.

🤖 Generated with Claude Code

uniqueg and others added 6 commits November 17, 2026 07:40
Plugins of WES gateways get POST /runs as a plain dict of the form
fields (JSON fields parsed) with the files as a list of the new
immutable `Attachment` values, so that `wes` plugins can add workflow
files and work with every gateway (foca.plugins.wes).

The engine checks WES runs after each request and forward hook, as it
re-validates payloads: safe relative filenames (also after NFKC),
unique files, media types, and the new limits `plugins.attachments`
(max_count, max_size). It reads WES tags from the payload, and
provenance describes attachments by name, type, size and digest.

The test kit builds WES runs (make_run_request, make_inbound(api=)).

Closes #781

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe the payload of WES runs, the attachment rules and the app
helpers on the plugins page, `plugins.attachments` in the configuration
reference, and map `maxCount` in the library chart (foca-common 0.6.0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Subclasses could override `size` or the checked fields and so bypass
the limits; the checks now require exact `Attachment` instances and
count the content's length directly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Say that runs are checked after every hook that got one (not only
after changes), document files inside other files, rename the engine's
forward check to `_check_forward_output`, check attachment types only
in `check_run_request`, and complete the docs example.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
From the adversarial review:

- JSON fields must be dicts of JSON values: NaN and Infinity are
  refused when parsing and checking, not only when forwarding.
- Duplicate files and file/directory clashes are compared after NFKC
  normalization and case folding, as backends may do.
- Attachment contents must be exact bytes, and attachment lists are
  copied before counting, so that subclasses cannot misreport lengths.
- Line and paragraph separators are refused in filenames, and segment
  sizes are checked after NFKC too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
From the second review round: filenames, media types and text fields
must be exact strings, as subclasses could override the methods the
checks use; the NFKC form of filenames is limited in total size too;
messages follow the field-prefixed style. Document the change for WES
apps in the 0.23.0 migration guide.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Define the immutable attachment value that WES payloads and provenance depend on, and export it from the plugin package.

  • foca/plugins/__init__.py L37, L53
  • foca/plugins/model.py L18-21, L269-351, L364-366

Add the attachment-count and total-size configuration model and expose it through plugin configuration.

  • foca/plugins/config.py L583-603 (+3 small edits)

API

Specify the framework-neutral WES run-request contract and provide helpers to parse, validate, and serialize its fields and attachments.

  • foca/plugins/wes.py L1-470

Expose attachment descriptions in provenance snapshots so file content is not recorded while changes remain identifiable.

  • foca/plugins/provenance.py L37, L307-309, L328-369

Uses of the API

Apply WES run validation around request and forward hooks, including after sanitation, and derive WES tags from the payload like TES tags.

  • foca/plugins/engine.py L207-210, L923-927, L1520-1554 (+6 small edits)

Configuration

Map the new attachment-count setting from chart values to the plugin configuration key and test the rendered settings.

  • charts/foca-common/templates/_gateway.tpl L24
  • charts/foca-common/tests/test_templates.py L3077-3091

Documentation

Document the WES payload contract, attachment limits, migration impact, reference entry, and chart release note.

  • docs/configuration/plugins.md L79-81, L325-336
  • docs/migration-0.23.md L15-17, L196-217
  • docs/plugins.md L144-147, L311-422, L642-647 (+1 small edits)
  • docs/reference.md L218-219
  • docs/releases/chart/0.6.0.md L1, L6

Tests

Add WES-specific tests for request helpers, attachment validation, engine enforcement, tags, and API-aware test builders.

  • tests/plugins/test_plugin_selection.py L8, L411-430, L440-443
  • tests/plugins/test_plugin_wes.py L1-595

Extend the plugin test kit with WES run builders and API-specific inbound defaults, and use the harness API for default requests.

  • foca/plugins/testing.py L140-195, L200-212, L217-231 (+9 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

@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (3ca02ab) to head (9eae3ca).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #782    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           74        75     +1     
  Lines         9788     10025   +237     
==========================================
+ Hits          9788     10025   +237     
Flag Coverage Δ
test_unit 100.00% <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 17, 2026 08:26
@sourcery-ai

sourcery-ai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 9eae3ca

#781 feat(plugins): define the WES run request for plugins · 6 of 6 met

# Requirement Status Notes
1 Define a framework-neutral WES run payload with JSON fields parsed and attachments as values plugins can read and modify. ✅ Met foca.plugins.wes provides the parsing and serialization helpers, and the payload uses exported immutable Attachment values.
2 Check WES runs after each plugin for safe relative filenames and configurable attachment count and size limits. ✅ Met The engine checks request and forward hook output, and the request path checks again after sanitation; plugins.attachments configures the limits.
3 Provide WES run builders in the test kit and contract checks with api="wes". ✅ Met make_inbound(api="wes") supplies a run with an attached workflow, and contract checks default to make_inbound(api=api).
4 Document the WES payload, attachment rules, and app multipart build and forwarding on the plugins page. ✅ Met The WES requests section documents the payload contract, checks, and framework-neutral app helpers.
5 Provide a contract against which foca-plugins#87 and #88 can be implemented. ✅ Met The payload exposes workflow_url and workflow_type alongside modifiable workflow attachments; the docs include a workflow-fetching example.
6 Add tests for the model and checks, with 100% coverage. ✅ Met The diff adds extensive WES payload, validation, and engine tests; the PR verification reports 100% coverage.

@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="foca/plugins/wes.py" line_range="123" />
<code_context>
+    for segment in path.split("/"):
+        if not segment:
+            raise InvalidRunRequest("filename has an empty segment")
+        if segment in (".", ".."):
+            raise InvalidRunRequest("filename has a '.' or '..' segment")
+
</code_context>
<issue_to_address>
**Attachments escape run directory**

When a validated attachment path contains a segment such as `.. ` and a plugin or backend materializes it using Windows path rules, `_check_path` rejects only segments exactly equal to `.` or `..`, so it accepts `.. `; Windows trims the trailing space and resolves the segment as `..`, allowing the attachment to be written outside the run directory.

Reject path segments that Windows would trim into `.` or `..`, including segments ending in spaces or dots.

Also at `foca/plugins/wes.py:124`.
</issue_to_address>

### Comment 2
<location path="foca/plugins/wes.py" line_range="194-196" />
<code_context>
+    Returns:
+        Run request (cf. :py:mod:`foca.plugins.wes`).
+    """
+    if attachments is None:
+        attachments = [Attachment("main.cwl", SAMPLE_CWL, "text/plain")]
+    return {
</code_context>
<issue_to_address>
**Invalid attachment shapes pass validation**

When a hook removes `workflow_attachment`, sets it to `None`, returns a tuple, or returns a list subclass whose iterator omits attachments, `_check_files` treats a missing field or `None` as empty, accepts tuples and list subclasses, and `list(attachments)` can invoke an overridden iterator; invalid shapes or unchecked attachments therefore pass validation, and later plugins can fail or receive an unchecked run.

Require `workflow_attachment` to be a present, exact built-in list and validate that list directly without copying it through an overridable iterator.

Also at `foca/plugins/wes.py:199`, `foca/plugins/wes.py:313-314`, `foca/plugins/wes.py:345`.
</issue_to_address>

### Comment 3
<location path="foca/plugins/engine.py" line_range="1577-1578" />
<code_context>
+            Exception: The output is invalid (cf. `foca.plugins.checks` and
+                :py:meth:`_check_run`).
+        """
+        self._check_run(candidate.payload, given.payload)
+        return _check_forward(candidate, given)
+
</code_context>
<issue_to_address>
**Sanitized runs bypass WES checks**

When the configured sanitizer changes a hook-checked run into one with invalid attachments or another shape that WES validation would reject, `self._check_run` runs before `self.host.check_payload`, so the sanitizer’s transformed payload is committed without another WES check and can be forwarded in an invalid state.

Run WES validation on the payload after `self.host.check_payload` has sanitized it.
</issue_to_address>

### Comment 4
<location path="foca/plugins/wes.py" line_range="288-289" />
<code_context>
+            `NaN`, sets or bytes).
+    """
+    try:
+        return json.dumps(
+            value, ensure_ascii=False, allow_nan=False, separators=(",", ":")
+        )
+    except (TypeError, ValueError, RecursionError):
</code_context>
<issue_to_address>
**Non-JSON values change when forwarded**

When a plugin puts a tuple or a mapping with non-string keys in a JSON field, `_to_json` uses `json.dumps`, which converts tuples to arrays and non-string keys to strings; `_check_fields` therefore accepts values outside the JSON shape and `run_request_form` forwards different data.

Validate JSON values recursively, rejecting tuples and mappings with non-string keys before serializing them.

Also at `foca/plugins/wes.py:316-318`.
</issue_to_address>

### Comment 5
<location path="foca/plugins/wes.py" line_range="74" />
<code_context>
+# RFC 9110, section 8.3.1: type "/" subtype, with optional parameters of
+# printable ASCII characters
+_TCHARS = r"[!#$%&'*+.^_`|~0-9A-Za-z-]+"
+_MEDIA_TYPE = re.compile(rf"{_TCHARS}/{_TCHARS}(?:[ \t]*;[\x20-\x7e]*)?")
+_DRIVE = re.compile(r"[A-Za-z]:")
+# control, format (e.g., bidirectional overrides), surrogate characters, and
</code_context>
<issue_to_address>
**Malformed media types pass validation**

When a plugin supplies a media type with an incomplete or invalid parameter after `;`, `_MEDIA_TYPE` accepts arbitrary printable text after a semicolon, including `text/plain;` and `text/plain; charset`, so `check_run_request` accepts malformed metadata and `run_request_form` forwards invalid part headers.

Make `_MEDIA_TYPE` validate parameter syntax rather than accepting arbitrary printable text after a semicolon.

Also at `foca/plugins/wes.py:216`.
</issue_to_address>

### Comment 6
<location path="foca/plugins/wes.py" line_range="289" />
<code_context>
+    """
+    try:
+        return json.dumps(
+            value, ensure_ascii=False, allow_nan=False, separators=(",", ":")
+        )
+    except (TypeError, ValueError, RecursionError):
</code_context>
<issue_to_address>
**Surrogates break UTF-8 forwarding**

When a client or plugin supplies an unpaired surrogate in a string field or a JSON string value, `_to_json` leaves JSON-value surrogates literal with `ensure_ascii=False`, and ordinary string fields pass through unchanged; the resulting form contains text that cannot be UTF-8 encoded, so forwarding fails.

Reject unpaired surrogates in all string fields and nested JSON values before returning the run form.

Also at `foca/plugins/wes.py:319`, `foca/plugins/wes.py:414`.
</issue_to_address>

### Comment 7
<location path="docs/plugins.md" line_range="388-392" />
<code_context>
+    run = parse_run_request(
+        form,  # the text fields, e.g., {"workflow_url": "main.cwl", "tags": "{}"}
+        [  # the uploaded files; filenames are checked below
+            Attachment(f.filename or "", f.read(), f.mimetype or "text/plain")
+            for f in files
+        ],
+    )
+    check_run_request(run, host.conf.attachments)
+except InvalidRunRequest as exc:
+    ...  # answer with exc.status (400, or 413 for too many or large files)
</code_context>
<issue_to_address>
**Oversized uploads exhaust memory**

When a WES app follows the example and its deployment leaves the web-server request-body limit unset, the example reads each uploaded file fully into an `Attachment` before calling `check_run_request`; the attachment limit therefore rejects an oversized run only after its bytes are in memory. With no web-server body limit, a large upload consumes memory before the 413 response and can exhaust the process.

Enforce a request-body limit before buffering uploaded files, configured no higher than the intended attachment allowance plus multipart overhead.
</issue_to_address>

### Comment 8
<location path="foca/plugins/wes.py" line_range="318" />
<code_context>
+        if name in JSON_FIELDS:
+            if not isinstance(value, dict):
+                raise InvalidRunRequest(f"{name}: no JSON object")
+            _to_json(name, value)
+        elif type(value) is not str:
+            raise InvalidRunRequest(f"{name}: no string")
</code_context>
<issue_to_address>
**Payload checks evade hook deadlines**

When a WES run contains a large JSON field and a request or forward hook completes near its configured deadline, `check_run_request` serializes every JSON field through `_to_json` after each request or forward hook, and this validation runs synchronously outside the timed `host.call`. A large WES JSON field therefore keeps the request busy beyond the configured hook deadline, even when the hook itself returns promptly.

Bound JSON-field size and include run validation in the deadline enforcement.

Also at `foca/plugins/engine.py:1534`.
</issue_to_address>

### Comment 9
<location path="foca/plugins/wes.py" line_range="219" />
<code_context>
+        if not _MEDIA_TYPE.fullmatch(attachment.media_type):
+            raise InvalidRunRequest(f"{field}: invalid media type")
+        # as servers may normalize filenames, or ignore their case
+        key = unicodedata.normalize("NFKC", name).casefold()
+        if key in files:
+            raise InvalidRunRequest(f"{field}: filename used twice")
</code_context>
<issue_to_address>
**Windows filenames can collide**

When a run with names that differ only by a trailing dot or space is stored by a Windows filesystem, the duplicate key applies NFKC and case folding but does not account for Windows trimming trailing dots or spaces. Two distinct accepted names such as `main.cwl` and `main.cwl.` therefore pass validation but resolve to the same file on Windows, so one attachment overwrites the other when stored.

Reject trailing dots and spaces in path segments or include the target platform’s filename normalization in collision checks.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 9 findings to address first, and WES uploads are now converted into plugin-visible attachments, validated after hooks, and forwarded as multipart requests; a validation or forwarding defect could send unsafe files to downstream plugins or workflow engines, where they may be consumed before a revert. Reverting would stop future requests but would not undo runs already triggered or data already exposed.

Blocking findings: foca/plugins/wes.py:123, foca/plugins/wes.py:196, foca/plugins/engine.py:1578, foca/plugins/wes.py:289, foca/plugins/wes.py:74, and 4 more


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

Comment thread foca/plugins/wes.py Resolved
Comment thread foca/plugins/wes.py Resolved
Comment thread foca/plugins/engine.py Resolved
Comment thread foca/plugins/wes.py Resolved
Comment thread foca/plugins/wes.py Resolved
Comment thread foca/plugins/wes.py Resolved
Comment thread docs/plugins.md Resolved
Comment thread foca/plugins/wes.py Resolved
Comment thread foca/plugins/wes.py Resolved
From Sourcery's review of #782:

- Refuse filename segments ending in a dot or space, which Windows
  drops (e.g., `.. ` becomes `..`, `a.` collides with `a`).
- Require `workflow_attachment` as an exact list, also present.
- Check runs again after the app's sanitizer.
- Check JSON fields recursively: string keys, no tuples or sets, finite
  numbers, at most 64 levels; strings must be valid UTF-8.
- Validate media type parameters as in RFC 9110.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 7bc6d9c into dev Nov 17, 2026
83 checks passed
@uniqueg
uniqueg deleted the feat/781-wes-run-request branch November 17, 2026 09:01
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(plugins): define the WES run request for plugins

1 participant