Skip to content

Fix adding www-authenticate header#13821

Open
e19166 wants to merge 3 commits into
wso2:masterfrom
e19166:master
Open

Fix adding www-authenticate header#13821
e19166 wants to merge 3 commits into
wso2:masterfrom
e19166:master

Conversation

@e19166

@e19166 e19166 commented Apr 29, 2026

Copy link
Copy Markdown
Contributor

This pull request introduces several improvements and fixes related to MCP (Multi-Channel Protocol) request handling, authentication, and protocol validation in the API Gateway. The changes primarily focus on consistent usage of constants, improving authentication flows for MCP requests, refining error responses, and enhancing protocol version validation. Below are the most important changes grouped by theme:

MCP Request Handling and Protocol Validation:

  • Standardized the usage of the MCP_HTTP_METHOD constant across the codebase for setting and retrieving the MCP HTTP method, improving maintainability and reducing hard-coded string usage.
  • Improved protocol version validation in MCP initialization requests by ensuring that the protocolVersion field is present and non-empty, and removing redundant protocol version checks.
  • Removed the check for allowed methods in MCPUtils.validateRequest, deferring method validation to other parts of the code.
  • Updated the logic to remove the MCP session ID header for INITIALIZE methods, ensuring session management is handled correctly.
  • Adjusted the isNoAuthMCPRequest method to return false for unsupported methods instead of throwing an exception, making the flow more robust.

Authentication Flow and Error Handling:

  • Enhanced the handling of unauthenticated MCP requests by aligning the flow with REST no-auth cases, including invoking handleNoAuthentication, setting API parameters, and calling extension listeners.
  • Refined the construction of the WWW-Authenticate header for authentication failures by directly building the resource metadata URL and optionally including a DCR (Dynamic Client Registration) endpoint if available. This provides better guidance to clients on how to register and obtain tokens.
  • Introduced a new method to retrieve the DCR endpoint based on the key manager configuration, supporting improved interoperability with external identity providers.

Scopes and Resource Management:

  • Ensured the "default" scope is always included in the list of all scopes for an API, both when iterating over resources and as a fallback, to guarantee proper scope assignment.

These changes collectively improve the reliability, maintainability, and interoperability of MCP request handling and authentication in the API Gateway.

Resolves: wso2/api-manager#4681

@coderabbitai

coderabbitai Bot commented Apr 29, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 93396883-9aff-48bd-93ca-c2c66ad72315

📥 Commits

Reviewing files that changed from the base of the PR and between a5f2e69 and 5c5ecbf.

📒 Files selected for processing (1)
  • components/apimgt/org.wso2.carbon.apimgt.gateway/src/test/java/org/wso2/carbon/apimgt/gateway/handlers/security/APIAuthenticationHandlerTestCase.java

📝 Walkthrough

Walkthrough

Removed MCP-specific logic that modified the WWW-Authenticate header on authentication failures, deleted an unused constant, and updated/removals in related unit tests and metric-timer assertions.

Changes

Cohort / File(s) Summary
Authentication Handler — MCP header logic removed
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/APIAuthenticationHandler.java
Deleted MCP-specific augmentation of the WWW-Authenticate header and associated debug logging and exception handling from handleAuthFailure. Removed the now-unused HttpHeaders import.
Utility cleanup
components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/utils/GatewayUtils.java
Removed an unused static constant apiType derived from APIConstants.ApiTypes.API.
Test updates
components/apimgt/org.wso2.carbon.apimgt.gateway/src/test/java/org/wso2/carbon/apimgt/gateway/handlers/security/APIAuthenticationHandlerTestCase.java
Removed two MCP-specific tests (no-auth success and DCR-based auth-failure) and related static mocking/assertions. Updated an exception-based test handler to throw APISecurityException with hardcoded status 1000. Adjusted metric-timer tests: testStartMetricTimer captures and asserts the returned Timer.Context and enforces exact timer.start() call count; testStopMetricTimer now verifies context.stop() is invoked exactly once. Cleaned imports and reduced @PrepareForTest usage.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Fix adding www-authenticate header' directly describes the primary change visible in the code modifications, which involve removing augmentation of the WWW-Authenticate header for MCP APIs.
Description check ✅ Passed The description comprehensively addresses multiple aspects of the PR including MCP request handling, authentication flows, protocol validation, and scope management, all of which relate to the changeset.
Linked Issues check ✅ Passed The PR addresses the authentication flow issue (#4681) by removing the WWW-Authenticate header augmentation logic, aligning with the objective to fix the auth path for 3rd-party clients when Authorization header is missing.
Out of Scope Changes check ✅ Passed The changes are narrowly scoped to removing WWW-Authenticate header augmentation and an unused constant, directly supporting the linked issue's authentication flow fix objective.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR adjusts MCP authentication failure handling in the API Gateway, focusing on how the WWW-Authenticate header is produced (and where that logic lives), while also cleaning up related gateway utilities and tests.

Changes:

  • Removed MCP-specific WWW-Authenticate header mutation logic from APIAuthenticationHandler.handleAuthFailure(...) (delegating to GatewayUtils.handleAuthFailure(...) only).
  • Removed an unused apiType constant from GatewayUtils.
  • Updated APIAuthenticationHandlerTestCase by deleting MCP-related tests and modifying metric-timer related assertions.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.

File Description
.../APIAuthenticationHandlerTestCase.java Removes MCP tests and changes assertions in metric timer tests (currently reducing meaningful coverage).
.../GatewayUtils.java Removes an unused static apiType constant.
.../APIAuthenticationHandler.java Deletes in-handler MCP WWW-Authenticate header construction logic, relying on shared auth-failure handling.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@components/apimgt/org.wso2.carbon.apimgt.gateway/src/test/java/org/wso2/carbon/apimgt/gateway/handlers/security/APIAuthenticationHandlerTestCase.java`:
- Around line 377-380: The test currently uses a no-op assertion; replace it
with a real verification that stopMetricTimer delegates to the context by
verifying the mocked context's stop() was invoked (e.g., use
Mockito.verify(context, times(1)).stop() or equivalent) after calling
APIAuthenticationHandler.stopMetricTimer(context) so the test fails if stop() is
not called; reference APIAuthenticationHandler.stopMetricTimer and the mocked
context.stop() in the assertion.
- Around line 325-328: Replace the hardcoded error code in the test helper with
the production constant: in APIAuthenticationHandlerTestCase::isAuthenticate
where it currently throws new APISecurityException(1000, "test"), use
APISecurityConstants.API_AUTH_INVALID_CREDENTIALS instead (or add a comment if a
different code was intentional) so the test mirrors production error-code usage.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 89417889-5f0a-4889-b8e4-386e66d2dc98

📥 Commits

Reviewing files that changed from the base of the PR and between cc35c97 and a5f2e69.

📒 Files selected for processing (3)
  • components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/APIAuthenticationHandler.java
  • components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/utils/GatewayUtils.java
  • components/apimgt/org.wso2.carbon.apimgt.gateway/src/test/java/org/wso2/carbon/apimgt/gateway/handlers/security/APIAuthenticationHandlerTestCase.java
💤 Files with no reviewable changes (2)
  • components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/utils/GatewayUtils.java
  • components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/APIAuthenticationHandler.java

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.

[MCP] APIM 4.6.0 MCP Auth flow is not working with 3rd party clients.

2 participants