Skip to content

Webhook Middleware Phase 3: Mutating webhook middleware with JSONPatch#4372

Open
Sanskarzz wants to merge 2 commits intostacklok:mainfrom
Sanskarzz:dynamicwebhook3
Open

Webhook Middleware Phase 3: Mutating webhook middleware with JSONPatch#4372
Sanskarzz wants to merge 2 commits intostacklok:mainfrom
Sanskarzz:dynamicwebhook3

Conversation

@Sanskarzz
Copy link
Contributor

@Sanskarzz Sanskarzz commented Mar 26, 2026

Summary

Implements Phase 3 of the Dynamic Webhook Middleware system: Mutating Webhook Middleware, as outlined in RFC THV-0017.

This PR adds support for mutating webhooks that allow external HTTP services to transform incoming MCP requests dynamically using RFC 6902 JSON Patch operations. Mutating webhooks are executed after the MCP parser but before validating webhooks, allowing organizations to cleanly intercept and rewrite requests (e.g., adding default parameters, applying transformations, or injecting audit trails) before validation or authorization logic runs.

Fixes #3398

Changes

1. pkg/webhook/mutating/ Package

Introduces the core logic for mutating webhooks:

  • config.go: Defines configuration parameter types (MiddlewareParams, FactoryMiddlewareParams) mirroring the validating package.
  • patch.go: Implements RFC 6902 JSONPatch parsing and application using github.com/evanphx/json-patch/v5.
    • Includes ValidatePatch() to ensure only supported operations are allowed.
    • Implements Scope Validation (IsPatchScopedToMCPRequest()) to ensure webhooks can only modify the mcp_request container inside the webhook payload, preventing unauthorized modification of the request principal, context, or envelope metadata.
  • middleware.go: The HTTP middleware factory and handler.
    • Skips non-MCP requests gracefully.
    • Executes chained mutating webhooks in configuration order, passing the output of one as the input to the next.
    • Extracts the raw MCP request, evaluates it against the webhook endpoints, and applies the returned JSONPatches.
    • Supports RFC-defined failure policies (fail vs ignore) for connection errors or malformed patches.

2. Runner Wiring (pkg/runner/)

  • config.go: Added MutatingWebhooks []webhook.Config to RunConfig to allow configuring mutating webhooks natively via state persistence or configuration YAML.
  • middleware.go: Registered the mutating webhook middleware factory and inserted it into the middleware execution chain. It executes proactively before the validating webhook middleware, matching the RFC specifications.

3. Dependencies

  • Added github.com/evanphx/json-patch/v5 for RFC 6902-compliant patch application.

4. Addressed Phase 2 leftover review comments

  • Inlined the variables in sendErrorResponse in the validating webhook middleware.
  • Renamed the misleading test in pkg/webhook/validating/middleware_test.go.
  • Extracted duplicate convertToJSONRPC2ID implementations from all 3 middlewares (authz, validating, mutating) to a central location (pkg/mcp/utils.go).

5. Full Middleware Chain Integration Test

  • Added TestWebhookMiddlewareChainIntegration to pkg/runner/webhook_integration_test.go to test the execution flow of both mutating and validating webhooks as initialized by the runner configuration parsing.

6. Test Coverage Improvements:

  • Added new tests checking failure states of patch extraction and application to increase pkg/webhook/mutating/patch.go and pkg/webhook/mutating/middleware.go coverage.
  • Addressed low coverage for PopulateMiddlewareConfigs in pkg/runner/middleware.go by adding TestPopulateMiddlewareConfigs_FullCoverage which spans across all configuration branch setups.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

@github-actions github-actions bot added the size/XL Extra large PR: 1000+ lines changed label Mar 26, 2026
Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Large PR Detected

This PR exceeds 1000 lines of changes and requires justification before it can be reviewed.

How to unblock this PR:

Add a section to your PR description with the following format:

## Large PR Justification

[Explain why this PR must be large, such as:]
- Generated code that cannot be split
- Large refactoring that must be atomic
- Multiple related changes that would break if separated
- Migration or data transformation

Alternative:

Consider splitting this PR into smaller, focused changes (< 1000 lines each) for easier review and reduced risk.

See our Contributing Guidelines for more details.


This review will be automatically dismissed once you add the justification section.

@github-actions github-actions bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Mar 26, 2026
@codecov
Copy link

codecov bot commented Mar 26, 2026

Codecov Report

❌ Patch coverage is 84.65116% with 33 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.56%. Comparing base (8fc2c71) to head (f4c5947).

Files with missing lines Patch % Lines
pkg/webhook/mutating/middleware.go 82.87% 19 Missing and 6 partials ⚠️
pkg/runner/middleware.go 76.47% 2 Missing and 2 partials ⚠️
pkg/webhook/mutating/patch.go 85.71% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4372      +/-   ##
==========================================
+ Coverage   69.47%   69.56%   +0.08%     
==========================================
  Files         485      489       +4     
  Lines       49805    49987     +182     
==========================================
+ Hits        34603    34772     +169     
+ Misses      12523    12522       -1     
- Partials     2679     2693      +14     

☔ View full report in Codecov by Sentry.
📢 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.

@github-actions github-actions bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Mar 26, 2026
@Sanskarzz Sanskarzz marked this pull request as ready for review March 26, 2026 21:31
@github-actions github-actions bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Mar 26, 2026
Signed-off-by: Sanskarzz <sanskar.gur@gmail.com>
@github-actions github-actions bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Mar 26, 2026
Signed-off-by: Sanskarzz <sanskar.gur@gmail.com>
@github-actions github-actions bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Mar 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Webhook Middleware Phase 3: Mutating webhook middleware with JSONPatch

1 participant