Skip to content

fix(gateways): return 400 for config validation errors on PUT /gateways/{id} (POST/PUT status asymmetry) - #7246

Open
chiragjangiir wants to merge 3 commits into
IBM:mainfrom
chiragjangiir:fix/gateway-update-validation-400
Open

chiragjangiir wants to merge 3 commits into
IBM:mainfrom
chiragjangiir:fix/gateway-update-validation-400

Conversation

@chiragjangiir

Copy link
Copy Markdown

🐛 Bug-fix PR

🔗 Related Issue

Fixes #7144


📝 Summary

What does this PR do and why?

PUT /gateways/{id} returns HTTP 500 for OAuth config-validation errors that POST /gateways/ correctly reports as HTTP 400. The same invalid payload (e.g. oauth_config.grant_type = "token-exchange" without target_audience) answers with "Unexpected error" on update and "Unable to process input" on create.

update_gateway wraps every unexpected exception in its final handler:

raise GatewayError(f"Failed to update gateway: {unexpected_error_detail(e)}")

The wrapped exception has no __cause__ set, so the PUT router's isinstance(ex, ValueError) -> 400 branch never matches and the request falls through to the generic 500. register_gateway (POST path) re-raises ValueError from its except* ValueError group, which is why create behaves correctly.


🐞 Root Cause

Two-part asymmetry between the create and update paths:

  1. gateway_service.update_gateway (mcpgateway/services/gateway_service.py, final except Exception wrap) swallows config-validation errors — seven distinct ValueError-producing validation paths (deprecated password-grant adoption, query-param auth guards, _validate_token_exchange_config, _validate_private_key_jwt_config) — into a plain GatewayError without exception chaining.
  2. The PUT handler in mcpgateway/main.py maps ValueError to 400 but has no way to detect that a GatewayError is wrapping one.

🔧 What Changed

  • mcpgateway/services/gateway_service.py — update_gateway's final wrap now chains the original exception (raise GatewayError(...) from e). This preserves the service's documented GatewayError contract for callers while making the failure type inspectable by the router.
  • mcpgateway/main.py — update_gateway PUT handler adds a branch (after the more specific gateway sub-error mappings) that returns 400 "Unable to process input" when a GatewayError's cause is a ValueError. The issue's suggested fix location (the update handler, not the service) is followed.

Both places are minimal: the service keeps raising GatewayError, and the router keeps existing status codes — GatewayNotFoundError (404), GatewayCredentialError (422), GatewayConnectionError (502), conflict errors (409), and generic GatewayError (500) are all unchanged.


🧪 Tests and Verification

New regression tests (fail on main, pass with this patch):

  1. tests/unit/mcpgateway/services/test_gateway_service.py::TestGatewayService::test_update_gateway_config_validation_wraps_value_error_as_cause — drives the real validation path (_validate_token_exchange_config raising PublicValidationError for a token-exchange update without target_audience) and asserts the wrapped GatewayError preserves the ValueError cause.
  2. tests/unit/mcpgateway/test_main_error_handlers.py::TestGatewayUpdateErrorHandlers::test_update_gateway_wrapped_config_validation_error — PUT returns 400 "Unable to process input" for the chained failure.
  3. tests/unit/mcpgateway/test_main_error_handlers.py::TestGatewayUpdateErrorHandlers::test_update_gateway_gateway_error_without_validation_cause_still_500 — a GatewayError with a non-validation cause must keep returning 500.

Exact commands and results (Python 3.12.15, uv 0.13.1, macOS):

Check Command Result
Pre-fix failing pytest ...::test_update_gateway_wrapped_config_validation_error ...::test_update_gateway_config_validation_wraps_value_error_as_cause (fix stashed) 2 failed (PUT answered 500; __cause__ was None) ✅ expected failures
Regression tests same commands with the fix applied 3 passed
Update-handler suite uv run pytest tests/unit/mcpgateway/test_main_error_handlers.py -q 49 passed
Gateway service suite uv run pytest tests/unit/mcpgateway/services/test_gateway_service.py -q 24 passed, 1 skipped (pre-existing skip)
Whitespace git diff --check clean

Per make targets (exact commands executed, pinned tool versions per Makefile):

Check Command Status
Lint suite (partial) uv tool run isort==6.1.0 --check-only, uv tool run black==26.3.1 --check on the four touched files baseline-neutral: the same files fail isort/black checks identically with my changes stashed (pre-existing drift in untouched import blocks). My hunks are clean; proven by baseline comparison. ✅ but see Notes
Unit tests (focused) uv run pytest tests/unit/mcpgateway/test_main_error_handlers.py tests/unit/mcpgateway/services/test_gateway_service.py -q (with PORT set per local shell requirement) ✅ pass
Full make test / make coverage not executed locally in this session; CI runs the full suite + coverage gate ⏳ CI

Local environment: uv sync --frozen + make ensure-secrets for .env; PORT defaulted to 0 in this shell and must be overridden for Settings validation (environment quirk, unrelated to the patch).


📏 Reviewability


🏷️ Type of Change

  • Bug fix
  • Feature / Enhancement
  • Documentation
  • Refactor
  • Chore (deps, CI, tooling)
  • Other (describe below)

✅ Checklist

  • Code formatted (make black isort pre-commit) — my hunks are black==26.3.1/isort==6.1.0 clean (verified against baseline), but I deliberately did not run repo-wide formatting tools because make black/isort would reformat large untouched parts of these same files (see Notes)
  • Tests added/updated for changes
  • Documentation updated (if applicable) — no docs describe the PUT/POST status asymmetry; not updated to keep scope minimal
  • No secrets or credentials committed

📓 Notes

  • Authorship disclosure: parts of this PR were produced with AI assistance. I reviewed, reproduced, tested, and can explain every change (per the If AI-assisted reviewability item). DCO sign-off carried on the commit.
  • Pre-existing lint drift: with this PR's four files checked at their main state (changes stashed), isort 6.1.0 and black 26.3.1 already flag the same files at the same volume — including large untouched areas (e.g. the isort diff points at import blocks and # First-Party comment markers far from my patch). I ran the tools pinned in the Makefile and compared baseline-vs-patch to confirm neither check newly degrade with this change. Happy to split the pre-existing formatting churn into a separate PR if maintainers want it — deliberately not bundled to keep review size small.
  • Scope guard honored from the issue discussion: any fix changes the status for every ValueError path through update_gateway, including the token-exchange token_url SSRF rejection. That deny-path (PublicValidationError from SecurityValidator.validate_url) now also returns 400; the chained-cause tests cover the general ValueError mapping, and named gateway sub-errors keep their specific codes. If maintainers prefer the SSRF case to stay a 500, an exclude-guard is trivial to add — happy to adapt.
  • The generic 500 for plain Exceptions is unchanged (except Exception remains the fall-through), so "gateway crashed" vs "my payload is invalid" is now distinguishable, as the issue's Expected Behavior section asks.

…teways/{id}

Config validation failures inside gateway_service.update_gateway (e.g. a
token-exchange oauth_config missing target_audience) were swallowed by the
final wrap (raise GatewayError with "Failed to update gateway: ..."), so the
PUT router's ValueError branch never matched and clients received a generic
500, while POST /gateways/ returns 400 for the same invalid payload (IBM#7144).

- gateway_service.update_gateway: preserve the original exception as the
  GatewayError's cause (raise ... from e) so the router can identify
  validation failures without changing the service's documented error
  contract.
- PUT /gateways/{id} handler: map a GatewayError whose cause is a ValueError
  to 400 "Unable to process input", matching the POST create path. Gateway
  errors with a non-validation cause still return 500 (regression-covered);
  named gateway sub-errors keep their existing status codes.
- Regression tests: service-level cause-chain test and router-level 400 / 500
  branch tests, verified failing before the fix and passing after.

Fixes IBM#7144

Signed-off-by: Chirag Jangir <184008125+chiragjangiir@users.noreply.github.com>
@chiragjangiir
chiragjangiir force-pushed the fix/gateway-update-validation-400 branch from 7f6f5c1 to f7ca1bd Compare October 28, 2026 15:45

This branch has not been deployed

No deployments
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.

[BUG]: PUT /gateways/{id} returns 500 for config validation errors that POST /gateways returns 400 for

1 participant