Repository navigation
feat(plugins): define the WES run request - #782
Conversation
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]>
Reviewer's GuideData structuresDefine the immutable attachment value that WES payloads and provenance depend on, and export it from the plugin package.
Add the attachment-count and total-size configuration model and expose it through plugin configuration.
APISpecify the framework-neutral WES run-request contract and provide helpers to parse, validate, and serialize its fields and attachments.
Expose attachment descriptions in provenance snapshots so file content is not recorded while changes remain identifiable.
Uses of the APIApply WES run validation around request and forward hooks, including after sanitation, and derive WES tags from the payload like TES tags.
ConfigurationMap the new attachment-count setting from chart values to the plugin configuration key and test the rendered settings.
DocumentationDocument the WES payload contract, attachment limits, migration impact, reference entry, and chart release note.
TestsAdd WES-specific tests for request helpers, attachment validation, engine enforcement, tags, and API-aware test builders.
Extend the plugin test kit with WES run builders and API-specific inbound defaults, and use the harness API for default requests.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit 9eae3ca #781 feat(plugins): define the WES run request for plugins · 6 of 6 met
|
There was a problem hiding this comment.
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
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]>
Summary
Defines how plugins of WES gateways get runs (
POST /runs), the same in every gateway and without web-framework types, so thatwesplugins (e.g., ones that fetch workflows from TRS) are reusable:foca.plugins.wes: the run is adictof the form fields, withworkflow_params,tagsandworkflow_engine_parametersparsed from JSON, and the files underworkflow_attachmentas a list of the new immutablefoca.plugins.Attachment(filename, content, media_type)(size,digest). Framework-neutral app helpers:parse_run_request,check_run_request,run_request_form; errorsInvalidRunRequest(400) andAttachmentsTooLarge(413), whose messages name fields and positions, never values.requestandforwardhook 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 limitsplugins.attachments(max_count256,max_size32 MiB).host.start()reads the tags of WES runs from the payload, as for TES tasks.make_run_request(),make_inbound(api="wes"); harnesses default to the harness's API.maxCountmapped 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/testswith Helm 3.22.1: 435 passed.listforworkflow_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.Declined review findings
make_inboundkeeps a positional tuple of per-API defaults (low): readable enough; changing it is churn.test_check_attachmentsandtest_check_run_requeststay loops (low): each case asserts its own message, so failures are easy to place.Attachment.digestgoes stale only if a plugin deliberately usesobject.__setattr__: hostile code, out of scope.check_run_requestbeforehost.start(), as documented.🤖 Generated with Claude Code