Repository navigation
fix: answer bad run requests with 4xx, not 500 - #185
Conversation
Run requests that aren't forms (e.g., JSON, text/plain, or without a media type) reached Connexion's validation of form bodies as bytes, which failed with an AttributeError (500). A before_request check of the Flask app now refuses them with 415 Unsupported Media Type, and multipart/form-data requests without a boundary with 400. URL-encoded forms keep working as before. GET /runs with a malformed page_token raised an unmapped InvalidId (500), and a negative page_size listed runs as for its absolute value. Both now get 400 with the invalid parameter in `errors`; the token is not echoed. The 415 of POST /runs is declared as a proWES extension in additions.openapi.yaml, allowed in the contract tests, and documented in docs/api.md and docs/upgrading.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review findings: page sizes of 2^63 - 1 or more (valid int64, which Connexion doesn't range-check) made the query limit too large for BSON (OverflowError, 500 with a real MongoDB); they are now capped, so they list all runs. The 415 detail names both form media types; the endpoint name of POST /runs is defined before its use and pinned to the routes of the app by a test; requests other than run requests are tested to be left alone by the check; docs wording. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Round-2 review lows: the 415 detail names URL-encoded forms too, a comment says why the controllers import Flask's request, and the wrong-boundary test says that its 400 is Connexion's own. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideData structuresConstrain the configured default page size so invalid negative pagination settings fail at startup, while documenting the supported zero value.
Define the maximum MongoDB-safe query limit and convert malformed page tokens and negative page sizes into field-level client errors.
APIDeclare the proWES 415 response for unsupported POST /runs media types in the served OpenAPI additions.
Uses of the APIRegister the pre-validation request-body guard in the Flask app so invalid run media types and missing multipart boundaries are handled before Connexion parses them.
Add run-request body checks and authentication handling, and reject URL-encoded attachments in the POST /runs controller.
ImplementationMap unsupported media types, missing multipart boundaries, and URL-encoded attachments to the intended problem-detail status responses.
DocumentationDocument the added 415 response, supported run-request forms, authentication ordering, and pagination error behavior.
TestsCover the request-body guard's authentication ordering, body-free checks, endpoint matching, and isolation from other routes.
Verify problem responses for unsupported and malformed run bodies and invalid pagination parameters, and preserve handling of other request cases.
Test that negative configured page sizes are rejected while zero remains valid.
Allow the declared 415 response as a specification deviation for POST /runs.
Cover URL-encoded runs without attachments and pagination validation, safe large query limits, and valid-but-unknown page tokens.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #185 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 20 20
Lines 1039 1082 +43
=========================================
+ Hits 1039 1082 +43 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit 2c3cb7d #172 fix: answer bad run requests with 4xx, not 500 · 5 of 5 met
|
There was a problem hiding this comment.
Hey - I've found 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="pro_wes/ga4gh/wes/workflow_runs.py" line_range="310" />
<code_context>
"page_size", self.config.list_runs.default_page_size
)
page_token = kwargs.get("page_token", "")
+ if page_size < 0:
+ raise InvalidFieldsProblem(
+ [
</code_context>
<issue_to_address>
**Configured page size returns client error**
When `custom.list_runs.default_page_size` is negative, `WorkflowRuns.list_runs` uses that value when the request omits `page_size`, then raises `InvalidFieldsProblem`, so callers receive a 400 for a server-side configuration error and cannot list runs.
Validate the configured default as a configuration error before `list_runs` applies request-parameter validation.
</issue_to_address>
### Comment 2
<location path="pro_wes/ga4gh/wes/controllers.py" line_range="26" />
<code_context>
+# `multipart/form-data` only, but forms without attachments are accepted
+# URL-encoded, too
+RUN_REQUEST_MEDIA_TYPES = frozenset(
+ {"multipart/form-data", "application/x-www-form-urlencoded"}
+)
+
</code_context>
<issue_to_address>
**URL-encoded attachments disappear**
When a URL-encoded run request includes a `workflow_attachment` field, `_validate_run_request` removes the `workflow_attachment` form field, and `_read_attachments` reads only uploaded files, so the request succeeds without forwarding or storing the claimed attachment; callers see a successful run missing that input.
Reject URL-encoded requests that include `workflow_attachment`, or otherwise ensure they cannot be accepted as runs with the attachment silently omitted.
</issue_to_address>
### Comment 3
<location path="tests/ga4gh/wes/test_error_responses.py" line_range="424" />
<code_context>
+ assert_declared_error(served_spec, "get", "/runs", response, 400)
+ errors = response.json()["errors"]
+ assert [error["parameter"] for error in errors] == [parameter]
+ assert params[parameter] not in response.json()["detail"]
+
+
</code_context>
<issue_to_address>
**Page token can leak in errors**
When an invalid page token is included in the response's `errors` field but not in `detail`, if an invalid `page_token` is copied into an entry in `errors` but omitted from `detail`, `test_invalid_page` passes: line 424 checks only `detail`, despite line 422 reading the separate `errors` field. The test therefore misses a response that echoes the token.
Assert that the invalid page token is absent from the serialized response body, not only from `detail`.
</issue_to_address>
### Comment 4
<location path="tests/ga4gh/wes/test_workflow_runs.py" line_range="678-702" />
<code_context>
+ served_spec: Served specification.
+ mongodb: Database of the test (FOCA's fixture).
+ """
+ mongodb[RUN_DB][RUN_COLLECTION].insert_one(
+ {"run_log": {"run_id": "DONE01", "state": "COMPLETE"}}
+ )
</code_context>
<issue_to_address>
**Huge pages can truncate after one run**
When `list_runs` caps huge page sizes at a small value such as 1, if `list_runs` incorrectly caps every huge page size at 1, `test_list_runs_huge_page_size` still passes: it inserts only one run and asserts that this one-run result is complete, while the BSON check only verifies that the recorded limit is encodable. The test therefore misses truncation when more runs exist.
Insert more runs than the small cap and assert that the huge page size returns all of them.
</issue_to_address>Sourcery assessment
Approval pending. 4 findings to address first.
Blocking findings: pro_wes/ga4gh/wes/workflow_runs.py:310, pro_wes/ga4gh/wes/controllers.py:26, tests/ga4gh/wes/test_error_responses.py:424, tests/ga4gh/wes/test_workflow_runs.py:702
Sourcery review of #185: - URL-encoded run requests with `workflow_attachment` started the run without the attachments (URL-encoded forms can't carry files); they now get 400. - A negative `custom.list_runs.default_page_size` would have answered every GET /runs without `page_size` with 400; the config now refuses it on startup. - Tests: the invalid page token is checked to be absent from the whole response, and huge page sizes to list more than one run. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflict in the docstring of `init_app` (pro_wes/app.py): both notes kept. With tokens required, the check of run request bodies answered unauthenticated run requests with 415 or 400 instead of 401 (`test_no_token[post-/runs]`). It now refuses a body only if the request has a valid token (or auth is disabled), and leaves the others to Connexion, which answers 401 before it reads the body; tokens are validated a second time only for refused bodies. Tests: `test_run_request_body_after_token`, `test_run_request_body_auth_disabled`; the run of `test_other_requests_not_checked` gets the caller as owner. Docs: the order of 401 and body errors in docs/api.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of the auth gate: the check of run request bodies read the form of URL-encoded run requests (for `workflow_attachment`) before the token was checked, and Werkzeug parses URL-encoded bodies without memory or field limits. The check now decides by the headers only; the attachment check moved to the controller of POST /runs, after the token and Connexion's validation. Invalid tokens of refused bodies now get FOCA's 401 from the check itself, so they are validated once. Connexion 2 still reads the form of every request before its security checks, which this check can't prevent (drafted as a FOCA issue). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Client errors of
POST /runsandGET /runsthat got500 Internal server errornow get400or415, as problem details declared in the served specification.text/plain, no media type) reached Connexion's validation of form bodies as bytes (AttributeError: 'bytes' object has no attribute 'update'). Abefore_requesthook of the Flask app (check_run_request_bodyinpro_wes/ga4gh/wes/controllers.py, registered inpro_wes/app.py) now refuses them with415 Unsupported Media Typebefore Connexion reads the body, andmultipart/form-datawithout a boundary with400. URL-encoded forms (no attachments) keep working as before. The hook matches onlyPOST /runs; a test pins its endpoint name to the app's routes.GET /runs: a malformedpage_token(unmappedInvalidId) and a negativepage_size(before: listed as its absolute value) get400with the invalid parameter inerrors; the token isn't echoed. Page sizes beyond what MongoDB takes (>= 2^63 - 1, validint64; Connexion doesn't range-check) are capped instead of overflowing the BSON query limit.page_size=0still lists all runs (unchanged).415ofPOST /runsis declared as a proWES extension inadditions.openapi.yamland allowed inALLOWED_DEVIATIONSoftests/ga4gh/wes/test_spec.py.docs/api.md(deviations,GET /runspaging,400/415ofPOST /runs),docs/upgrading.md(Errors).The Connexion gap affects every FOCA app with form bodies; a FOCA issue is drafted so the hook can be dropped once FOCA refuses such bodies itself.
Verification
tests/ga4gh/wes/test_error_responses.py(test_run_request_unsupported_media_typex4,test_run_request_without_boundary,test_invalid_pagex3, validated against the declared statuses),tests/ga4gh/wes/test_workflow_runs.py(test_list_runs_invalid_page,test_list_runs_huge_page_size, which checks that the query limit encodes as BSON, since mongomock doesn't encode). Also:test_run_request_wrong_boundary,test_other_requests_not_checked,test_run_workflow_endpoint,test_post_run_url_encoded,test_list_runs_unknown_page_token.coverage run -m pytest --ignore=tests/test_chart.py: 557 passed;coverage report: 100 %.pre-commit run --all-files: all hooks pass exceptactionlint, which can't run locally (mise has no shellcheck version set); this PR changes no workflows, CI runs it.mkdocs build --strict: passed.tests/test_chart.py(needshelm dependency build; chart untouched).workflow_attachmentnow get400, as the attachments were dropped; a negativecustom.list_runs.default_page_sizestops the app on startup; stricter tests for token echo and huge page sizes).coverage run -m pytest --ignore=tests/test_chart.py: 559 passed, 100 %; pre-commit (exceptactionlint) andmkdocs build --strictpass.origin/devwith feat!: require access tokens from clients #184 (client access tokens) in 21b7322:init_appdocstring conflict resolved keeping both. With tokens required,test_no_token[post-/runs]showed that the body check answered unauthenticated run requests with415/400instead of401; the hook now refuses a body only if the request has a valid token (ordisable_auth), and leaves the rest to Connexion, which answers401first. Tokens are validated a second time only for refused bodies. New teststest_run_request_body_after_token(no token, other scheme, invalid token x JSON, no boundary) andtest_run_request_body_auth_disabled; order documented indocs/api.md. After the merge: 605 passed, 100 %; pre-commit (exceptactionlint) andmkdocs build --strictpass.workflow_attachment) before the token check, and Werkzeug parses URL-encoded bodies without memory or field limits; the hook now decides by the headers only, and the attachment check moved to thePOST /runscontroller (after token and validation). (low) invalid tokens of refused bodies were validated twice; the hook now raises FOCA's401itself. Tests:test_run_request_body_check_reads_no_body,test_invalid_token_validated_once(both failed before the fix). Note: Connexion 2 itself reads the form of every request before its security checks (FlaskApi.get_request), on all operations; this PR can't prevent that, and a FOCA issue is drafted. After 2c3cb7d: 608 passed, 100 %; pre-commit (exceptactionlint) andmkdocs build --strictpass.Declined review findings
randomize_endpointor a renamed controller. FOCA doesn't set that option;test_run_workflow_endpointand the 415 tests fail if the name drifts. The hook goes away with the FOCA fix (or Connexion 3).UnsupportedMediaTypederives fromBadRequestthough it maps to415: FOCA has no 415 class; same pattern asTasksNotServed(InternalServerError, mapped to501). The docstring says so.Open questions
None.
Closes #172
🤖 Generated with Claude Code
Summary by Sourcery
Return declared client errors for invalid run requests and pagination parameters while safely handling extreme page sizes.
Bug Fixes:
Enhancements:
Documentation:
Tests: