Skip to content

fix: answer bad run requests with 4xx, not 500 - #185

Merged
uniqueg merged 6 commits into
devfrom
fix/172-bad-request-4xx
Nov 19, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/172-bad-request-4xx

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Client errors of POST /runs and GET /runs that got 500 Internal server error now get 400 or 415, as problem details declared in the served specification.

  • Run requests that aren't forms (JSON, text/plain, no media type) reached Connexion's validation of form bodies as bytes (AttributeError: 'bytes' object has no attribute 'update'). A before_request hook of the Flask app (check_run_request_body in pro_wes/ga4gh/wes/controllers.py, registered in pro_wes/app.py) now refuses them with 415 Unsupported Media Type before Connexion reads the body, and multipart/form-data without a boundary with 400. URL-encoded forms (no attachments) keep working as before. The hook matches only POST /runs; a test pins its endpoint name to the app's routes.
  • GET /runs: a malformed page_token (unmapped InvalidId) and a negative page_size (before: listed as its absolute value) get 400 with the invalid parameter in errors; the token isn't echoed. Page sizes beyond what MongoDB takes (>= 2^63 - 1, valid int64; Connexion doesn't range-check) are capped instead of overflowing the BSON query limit. page_size=0 still lists all runs (unchanged).
  • Spec: 415 of POST /runs is declared as a proWES extension in additions.openapi.yaml and allowed in ALLOWED_DEVIATIONS of tests/ga4gh/wes/test_spec.py.
  • Docs: docs/api.md (deviations, GET /runs paging, 400/415 of POST /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

  • Regression tests first (failing before the fix): tests/ga4gh/wes/test_error_responses.py (test_run_request_unsupported_media_type x4, test_run_request_without_boundary, test_invalid_page x3, 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 except actionlint, which can't run locally (mise has no shellcheck version set); this PR changes no workflows, CI runs it.
  • mkdocs build --strict: passed.
  • Not run locally: tests/test_chart.py (needs helm dependency build; chart untouched).
  • Review: adversarial + quality reviewers, two rounds. Round 1 fixed: overflow of huge page sizes (500 with a real MongoDB), 415 detail wording, endpoint constant order and a test pinning it, test that other requests aren't checked, docs wording. Round 2 (both reviewers, no high/medium): the 415 detail names URL-encoded forms too, comments.
  • Sourcery: four threads, all fixed in 6091073 (URL-encoded run requests with workflow_attachment now get 400, as the attachments were dropped; a negative custom.list_runs.default_page_size stops the app on startup; stricter tests for token echo and huge page sizes).
  • After 6091073: coverage run -m pytest --ignore=tests/test_chart.py: 559 passed, 100 %; pre-commit (except actionlint) and mkdocs build --strict pass.
  • CI: see the checks of the latest commit.
  • Merged origin/dev with feat!: require access tokens from clients #184 (client access tokens) in 21b7322: init_app docstring conflict resolved keeping both. With tokens required, test_no_token[post-/runs] showed that the body check answered unauthenticated run requests with 415/400 instead of 401; the hook now refuses a body only if the request has a valid token (or disable_auth), and leaves the rest to Connexion, which answers 401 first. Tokens are validated a second time only for refused bodies. New tests test_run_request_body_after_token (no token, other scheme, invalid token x JSON, no boundary) and test_run_request_body_auth_disabled; order documented in docs/api.md. After the merge: 605 passed, 100 %; pre-commit (except actionlint) and mkdocs build --strict pass.
  • Extra adversarial review of the auth gate (round 3, by exception), fixed in 2c3cb7d: (medium) the hook read the form of URL-encoded run requests (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 the POST /runs controller (after token and validation). (low) invalid tokens of refused bodies were validated twice; the hook now raises FOCA's 401 itself. 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 (except actionlint) and mkdocs build --strict pass.

Declined review findings

  • Adversarial (low): the endpoint match rebuilds Connexion 2's endpoint name and would stop matching with randomize_endpoint or a renamed controller. FOCA doesn't set that option; test_run_workflow_endpoint and the 415 tests fail if the name drifts. The hook goes away with the FOCA fix (or Connexion 3).
  • Quality (low): unit and HTTP tests of invalid page parameters overlap; they test different layers (the field errors, and the declared response).
  • Quality (low): UnsupportedMediaType derives from BadRequest though it maps to 415: FOCA has no 415 class; same pattern as TasksNotServed (InternalServerError, mapped to 501). 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:

  • Return 400 or 415 responses for invalid POST /runs media types, multipart boundaries, URL-encoded attachments, malformed page tokens, and negative page sizes instead of 500 errors or unintended behavior.
  • Prevent oversized pagination limits from overflowing MongoDB query encoding.

Enhancements:

  • Validate run request media types before form parsing while preserving supported URL-encoded requests without attachments.
  • Declare the POST /runs 415 response and document updated pagination and error behavior.

Documentation:

  • Update API and upgrade documentation for the new run request and pagination error responses.

Tests:

  • Add regression coverage for invalid run request bodies, pagination parameters, endpoint matching, supported URL-encoded requests, and MongoDB-safe page limits.

uniqueg and others added 3 commits November 19, 2026 02:08
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]>
@sourcery-ai

sourcery-ai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Constrain the configured default page size so invalid negative pagination settings fail at startup, while documenting the supported zero value.

  • pro_wes/config.yaml L218-219
  • pro_wes/config_models.py L255-257, L263

Define the maximum MongoDB-safe query limit and convert malformed page tokens and negative page sizes into field-level client errors.

  • pro_wes/ga4gh/wes/workflow_runs.py L73-107, L310-319, L326-331 (+3 small edits)

API

Declare the proWES 415 response for unsupported POST /runs media types in the served OpenAPI additions.

  • pro_wes/api/additions.openapi.yaml L72-82

Uses of the API

Register 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.

  • pro_wes/app.py L17, L29-31, L48-49

Add run-request body checks and authentication handling, and reject URL-encoded attachments in the POST /runs controller.

  • pro_wes/ga4gh/wes/controllers.py L14-27, L79-88, L249-322 (+2 small edits)

Implementation

Map unsupported media types, missing multipart boundaries, and URL-encoded attachments to the intended problem-detail status responses.

  • pro_wes/exceptions.py L171-187, L272-291 (+2 small edits)

Documentation

Document the added 415 response, supported run-request forms, authentication ordering, and pagination error behavior.

  • docs/api.md L25-194 (4 small edits)
  • docs/upgrading.md L200-211

Tests

Cover the request-body guard's authentication ordering, body-free checks, endpoint matching, and isolation from other routes.

  • tests/ga4gh/wes/endpoints/test_auth.py L9-14, L186-303
  • tests/ga4gh/wes/test_error_responses.py L14, L297-367

Verify problem responses for unsupported and malformed run bodies and invalid pagination parameters, and preserve handling of other request cases.

  • tests/ga4gh/wes/test_error_responses.py L368-446

Test that negative configured page sizes are rejected while zero remains valid.

  • tests/ga4gh/wes/test_models.py L10, L145-154

Allow the declared 415 response as a specification deviation for POST /runs.

  • tests/ga4gh/wes/test_spec.py L129-134

Cover URL-encoded runs without attachments and pagination validation, safe large query limits, and valid-but-unknown page tokens.

  • tests/ga4gh/wes/test_workflow_runs.py L12-16, L171-184, L641-724

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 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (168d848) to head (2c3cb7d).

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.
📢 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 19, 2026 02:15
@sourcery-ai

sourcery-ai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 2c3cb7d

#172 fix: answer bad run requests with 4xx, not 500 · 5 of 5 met

# Requirement Status Notes
1 Return 400 or 415 problem details for POST /runs bodies that aren't forms. ✅ Met The request hook returns 415 for unsupported media types, and the regression tests verify the declared response for JSON, text/plain, and missing media types.
2 Return 400 for malformed GET /runs page_token values. ✅ Met Malformed tokens are converted to InvalidFieldsProblem; the endpoint test checks the declared 400 response and confirms the token isn't echoed.
3 Return 400 for negative GET /runs page_size values. ✅ Met Negative sizes raise InvalidFieldsProblem, and the endpoint test checks the declared 400 response.
4 Add regression tests for the affected requests and validate responses against declared statuses. ✅ Met The POST /runs and GET /runs tests use the served specification to verify the response statuses.
5 If using 415, declare it in additions.openapi.yaml, the allowed spec deviations, and docs/api.md. ✅ Met The 415 response is added to the OpenAPI additions, permitted by the spec deviation test, and documented in docs/api.md.

@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 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 is free for open source - if you like our reviews please consider sharing them ✨

Comment thread pro_wes/ga4gh/wes/workflow_runs.py Resolved
Comment thread pro_wes/ga4gh/wes/controllers.py Resolved
Comment thread tests/ga4gh/wes/test_error_responses.py Resolved
Comment thread tests/ga4gh/wes/test_workflow_runs.py Resolved
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]>

@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.

Sourcery assessment

Approved.

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]>
@uniqueg
uniqueg merged commit 421214e into dev Nov 19, 2026
30 checks passed
@uniqueg
uniqueg deleted the fix/172-bad-request-4xx branch November 19, 2026 03:48
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.

fix: answer bad run requests with 4xx, not 500

1 participant