Repository navigation
Fixes 38479: Enforce RFC 8707 resource parameter and aud binding in MCP OAuth - #38695
Vishnuujain merged 7 commits into
Conversation
…binding in MCP OAuth Validate RFC 8707 resource indicators against the server's canonical protected resource URI on /mcp/authorize and /mcp/token (both authorization_code and refresh_token grants), bind minted MCP OAuth access tokens via the JWT aud claim, and enforce aud matching on OpenMetadata-signed JWTs at /mcp while preserving backward compatibility for clients that omit resource and for PAT, bot, session, and IdP tokens. Signed-off-by: deepinsight coder <nrvamsi13@gmail.com>
|
Local Java test run: PASSED — details
Tests run locally
Per-class counts come from the test reports, which can credit a test to the wrong class when classes run concurrently, and keep only the last run of a nested class that several test classes inherit. The summary's step totals are Maven's own counts. Broader coverage not executed by this focused run
Why these tests
Impacted, not run locally (12)
Commandsmvn -B package -pl openmetadata-mcp,openmetadata-service -am -Dspring-boot.repackage.skip=true -Dtest=AuthorizationHandlerTest,JWTTokenGeneratorTest,JwtFilterTest,McpResourceUriTest,McpServerRequestContextTest,OAuthHttpStatelessServerTransportProviderTest,UserSSOOAuthProviderTest -Dsurefire.failIfNoSpecifiedTests=false
mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=parallel -Dit.test=CredentialMcpRevocationIT,McpOAuthIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=global-state -Dit.test=SsoMcpClientProfilesIT,SsoMcpSignInChecksIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false |
❌ PR checklist incompleteThis PR cannot be merged until the following are addressed on its linked issue:
The fields live on the linked issue in the Shipping project (open the issue → right sidebar → Projects). After you set them, re-run this check (or push a commit) — issue/project changes do not re-trigger it automatically. Maintainers can bypass this check by adding the |
pmbrull
left a comment
There was a problem hiding this comment.
Thanks for working on MCP resource binding.
🔴 Enforce the audience at each authentication entry point. The new locally issued OAuth access tokens carry an MCP-only audience. The REST filter and WebSocket handshake validate locally issued tokens without checking that audience against the resource they serve. Please enforce the resource binding on both paths and add regression coverage for acceptance at MCP and rejection at the other two entry points. Cover the intended behavior for legacy tokens as well. REST authentication, WebSocket authentication.
|
@Vamsi-klu thanks for the PR, can you check above comment and work on it. |
The access tokens the MCP OAuth server mints name /mcp in aud, but the REST filter and the push-feed handshake accepted them like any other OpenMetadata-signed token. Move the audience rule into TokenAudience and have JwtFilter apply it while verifying every OpenMetadata-signed token, so filter, getCatalogSecurityContext, validateJwtAndGetClaims, verifySignatureOnly and validatePrefixedTokenRequest all enforce it. A JwtFilter serves the OpenMetadata API unless it is built with a TokenAudience, and no audience names the API, so REST and the push feed answer an MCP access token with a 401. The MCP transport and McpServer build their filters for the protected resource the transport publishes, which replaces the transport's own copy of the check. Tokens without aud (login and session tokens, bot tokens, personal access tokens, MCP tokens minted before audience binding) behave as before everywhere.
Mint an access token through a refresh grant on /mcp/token and check it is accepted at /mcp and refused with 401 by /api/v1/users/loggedInUser and by the push-feed handshake, with the token in the header or the query. Login, bot and personal access tokens keep working on all three.
Update the RFC 8707 decision record: the audience rule lives in TokenAudience and JwtFilter applies it on every entry point, REST and the push feed refuse aud-bound tokens, /mcp accepts tokens for its own resource, and tokens without aud keep working everywhere.
|
@pmbrull thanks, that was a real hole. The REST filter and the push feed handshake accepted the new MCP tokens like any other OpenMetadata token. The fix is in 2aed9b0. The Tokens without The new REST and socket cases in @Vishnuujain updated, ready for another look. |
pmbrull
left a comment
There was a problem hiding this comment.
✅ No issues found
| Blockers | ✅ prior code finding resolved |
| Nits | ✅ none |
| Tests | ✅ MCP acceptance, REST and feed rejection, and legacy credentials are covered |
| Cross-repo | ✅ checked the MCP transport and Collate’s inherited MCP filter |
| Trade-off | ✅ none |
| Auto-approved | ➖ authorization changes require maintainer review and passing checks |
Thanks for enforcing the audience at each entry point and adding an integration test that uses a token issued through the normal flow. This addresses the earlier review.
Please update from current main and rerun CI. Backend and Python workload selection both stop because the PR’s older tree lacks files that the current workflows require. The linked issue also needs its Shipping fields. Backend job · Python job · Shipping fields
What I checked
Traced how REST, the push feed and MCP choose the expected audience and read the integration tests for each outcome. The author reports passing MySQL and Elasticsearch coverage on this commit. CI stopped before the backend tests ran and PostgreSQL and OpenSearch coverage remains pending.
claude-verdict {"sha":"ad69c3c71ffb234556ad18cdf22ba5c26aae0212","recommendation":"human","blocking":0,"nits_to_fix":0,"human_decision":true,"tradeoff":"none","cross_repo":"checked","tests_ok":true}
manerow
left a comment
There was a problem hiding this comment.
Thanks for this, and for the follow-up on REST and the push feed. The audience rule now lives in one place and only adds checks. Two small things before it merges. Neither is blocking.
1. The direct-400 error on /mcp/authorize now repeats what the caller sent. That branch used to return a fixed error_description. It now passes the handler's message through, and for an unregistered callback that message includes the caller's input: Redirect URI '<caller input>' not registered for client. It's JSON, so it can't run in a browser. Still, the ADR says error descriptions never echo untrusted input, and this is the one path where they do. Could you forward only the error code (so invalid_target still reaches the client) and keep "Authorization request failed" as the description? Transport · message source
2. If the server's own resource URI can't be canonicalized, sign-in still mints tokens that /mcp then refuses, and nothing in the logs says why. issueAccessToken falls back to the raw URI for aud. /mcp fails closed because matches can't canonicalize the expected value. One way to hit this is a base URL whose host has an underscore (http://my_server:8585): URI.getHost() returns null there. On such a deployment, clients that omit resource sign in and then get a 401 on every call, while clients that send it get invalid_target. Failing closed is right. Could you log an error when the transport publishes a resource that doesn't canonicalize (at startup and in rebuildMetadata), and add a unit test for that case? Issuance
Vishnuujain
left a comment
There was a problem hiding this comment.
@Vamsi-klu thanks, the token binding looks right and the REST/feed gap is closed. Two small gaps inline, plus a few ways to make this smaller:
- We only ever accept one value here, our own
/mcpURL. So "clean it up (lowercase scheme and host, drop :443/:80, drop one trailing slash) and compare the whole string to ours" is enough. Anything odd (query, fragment,user@,..,//, encoded letters, a stray:) just won't match. I tried a ~10 line version of that against 28 cases and it gave the same answers, so most ofMcpResourceUriand its tests could go. - The resource URL is always the same as the issuer URL (
baseUrl + mcpEndpointfor both). Could we keep one copy instead of addinggetResource/setResourceand a second field? Right now authorize reads one copy and token and/mcpread the other. extractResourceValues:getParameterValues()andgetParameterMap()read the same data, so the fallback never adds anything outside mocks.
| targetResource != null | ||
| ? McpResourceUri.canonicalize(targetResource) | ||
| .map(URI::toString) | ||
| .orElse(targetResource.toString()) |
There was a problem hiding this comment.
If the resource can't be cleaned up, this still mints a token that /mcp will reject, so the user gets a token that never works and no error. Can we fail here instead?
There was a problem hiding this comment.
Good catch, Vishnu. The authorization code and refresh exchanges now return server_error when the configured MCP resource URL is invalid. The check runs before either grant is consumed. I added a test that corrects the base URL and retries both grants successfully. This is in 876c769db64.
| // Validate RFC 8707 resource parameter(s) only after client_id and redirect_uri are | ||
| // verified so unknown clients or unregistered callbacks cannot become open redirects. | ||
| URI expectedResource = provider.getResource(); | ||
| if (!McpResourceUri.validateRequested(resourceValues, expectedResource)) { |
There was a problem hiding this comment.
When a resource is rejected, can we log the expected and received value at WARN (here and in validateRequestedResource on the token path)? Behind a proxy (http vs https) or with a host alias, admins will only see invalid_target with no hint why.
There was a problem hiding this comment.
I added WARN logs on both /mcp/authorize and /mcp/token with the expected URI and the first rejected value. Scheme, host, port, and path are visible, with user info, query strings, and fragments redacted. I also made the issuer the shared source, removed the parameter-map fallback, and simplified the URI normalization. The existing URI edge cases still pass. This is in 876c769db64.
|
@manerow thanks for pointing out both paths. The direct 400 now keeps the OAuth error code and uses |
|
@Vamsi-klu thanks for the fixes, can you please resolve merge conflict? |
Code Review ✅ Approved 🔴 High riskBinding MCP OAuth tokens to a canonical audience and changing JWT checks across REST, WebSocket, and MCP could reject legitimate access or admit tokens at unintended entry points. Enforces RFC 8707 resource parameters across the MCP OAuth authorize, token, and resource-server flow, and binds minted MCP access tokens to the canonical VerificationRules No rules evaluated Functional validation Not enabledAuto-approval Not enabledFor more verification details, comment OptionsDisplay: compact → Showing compact verification results. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source |
|
🤖 Backport to |
|
🤖 Backport to |
|
🤖 Backport to |
|
🤖 Backport to |
…CP OAuth (#38695) (#38996) * Fix #38479: Enforce RFC 8707 resource parameter and aud binding in MCP OAuth Validate RFC 8707 resource indicators against the server's canonical protected resource URI on /mcp/authorize and /mcp/token (both authorization_code and refresh_token grants), bind minted MCP OAuth access tokens via the JWT aud claim, and enforce aud matching on OpenMetadata-signed JWTs at /mcp while preserving backward compatibility for clients that omit resource and for PAT, bot, session, and IdP tokens. * Reject MCP-audience tokens at the REST and WebSocket entry points The access tokens the MCP OAuth server mints name /mcp in aud, but the REST filter and the push-feed handshake accepted them like any other OpenMetadata-signed token. Move the audience rule into TokenAudience and have JwtFilter apply it while verifying every OpenMetadata-signed token, so filter, getCatalogSecurityContext, validateJwtAndGetClaims, verifySignatureOnly and validatePrefixedTokenRequest all enforce it. A JwtFilter serves the OpenMetadata API unless it is built with a TokenAudience, and no audience names the API, so REST and the push feed answer an MCP access token with a 401. The MCP transport and McpServer build their filters for the protected resource the transport publishes, which replaces the transport's own copy of the check. Tokens without aud (login and session tokens, bot tokens, personal access tokens, MCP tokens minted before audience binding) behave as before everywhere. * Cover the MCP token audience across MCP, REST and the push feed Mint an access token through a refresh grant on /mcp/token and check it is accepted at /mcp and refused with 401 by /api/v1/users/loggedInUser and by the push-feed handshake, with the token in the header or the query. Login, bot and personal access tokens keep working on all three. * Record where each entry point checks the token audience Update the RFC 8707 decision record: the audience rule lives in TokenAudience and JwtFilter applies it on every entry point, REST and the push feed refuse aud-bound tokens, /mcp accepts tokens for its own resource, and tokens without aud keep working everywhere. * Fail MCP OAuth token exchange for an invalid resource --------- (cherry picked from commit 9078572) Signed-off-by: deepinsight coder <nrvamsi13@gmail.com> Co-authored-by: deepinsight coder <32898216+Vamsi-klu@users.noreply.github.com> Co-authored-by: Pere Miquel Brull <peremiquelbrull@gmail.com> Co-authored-by: Vishnu Jain <vishnujtimes@gmail.com>
Describe your changes:
Fixes #38479
Enforced RFC 8707 resource indicators across the MCP OAuth flow (
/mcp/authorize,/mcp/token, and/mcp), bound minted MCP OAuth access tokens to the server's canonical protected resource URI via the JWTaudclaim, recorded the design contract inADR:2026-11-25-mcp-oauth-binds-tokens-to-the-canonical-resource, and replaced the pinned gap testgapResourceParameterIsNotCheckedinSsoMcpSignInChecksITwith end-to-end enforcement assertions.Type of change:
High-level design:
flowchart LR A["GET/POST /mcp/authorize"] -->|"1. Validate all resource params vs canonical URI"| B["AuthorizationHandler"] B -->|"Invalid -> invalid_target (302 loopback / 400 HTML remote / 400 JSON policy)"| E1["Reject before IdP/login/consent"] B -->|"Valid or absent"| C["SSO / Login / Consent -> Code"] C --> D["POST /mcp/token (code or refresh)"] D -->|"2. Validate all resource params before burning code/refresh"| E2["400 JSON invalid_target"] D -->|"Valid or absent"| F["JWTTokenGenerator: aud = canonicalResource"] F --> G["POST /mcp Bearer JWT"] G -->|"3. OM-signed & aud present -> must match canonicalResource"| H["200 OK or 401 invalid_token"]McpResourceUri):ProtectedResourceMetadata.getResource()(baseUrl + "/mcp", honoringADR:2026-10-19-mcp-oauth-discovery-stays-inside-the-base-path, neverHost/X-Forwarded-*), stored involatilefields and propagated toauthProvider.setResource(...)at startup and ononConfigurationChanged/rebuildMetadata.McpResourceUrienforces RFC 8707 / RFC 3986 rules: 2,048-char length cap, absolutehttp/httpsscheme and host lowercased withLocale.ROOT, IPv6 literals, default port normalization (:443/:80), case-sensitive raw path with at most one trailing/stripped, and strict rejection of whitespace, fragments (#), query (?), userinfo (@), dangling port colons (om.example:,[::1]:), invalid ports, dot-segments (/.,/..), double slashes (//), and percent-encoding tricks (/%6dcp). Fails closed when the canonical URI is null/invalid./mcp/authorizeand/mcp/token:request.getParameterValues("resource")directly instead of collapsing tovalues[0], rejecting repeated query params and query+form-body smuggling (?resource=<canonical>+ bodyresource=<foreign>)./mcp/authorizevalidatesclient_idand registeredredirect_urifirst (preventing open redirects on unknown clients or unregistered callbacks), then validates allresourcevalues before creating pending requests or contacting the IdP. Invalidresourcereturnsinvalid_targetwith a static error description (never echoing untrustedresource): loopback/native callbacks get 302, remotehttps://callbacks get the 400 HTML return-link page (ADR:2026-11-02), and policy-blocked direct-400 JSON responses preserveauthResponse.getError()instead of hardcodinginvalid_request./mcp/tokenvalidates allresourcevalues for bothauthorization_codeandrefresh_tokengrants after client auth and required parameter checks, and beforeloadAuthorizationCode/exchangeAuthorizationCodeorexchangeRefreshToken, so badresourcerequests return 400invalid_targetwithout burning a valid code or rotating a refresh token.audbinding &/mcpenforcement (plus defense-in-depth):JWTTokenGenerator.generateJWTToken(..., clientId, audience)and 12-arggetJwtAuthMechanism(..., sessionId, clientId, audience)overloads writing a single-string"aud"claim when non-blank (existing 9-arg/11-arg overloads delegate withnull).UserSSOOAuthProvider.issueAccessTokenbinds minted MCP access tokens togetResource()beforestoreAccessTokenhashes the token.TokenAudience, oneaudrule for every entry point, whichJwtFilterapplies while verifying any OpenMetadata-signed token, so REST, the push feed handshake (polling and upgrade) and/mcpall check it. A filter built with the existing constructors serves the OpenMetadata API (REST andSocketAddressFilter) and refuses any OM-signed token that carriesaud. The MCP transport andMcpServerbuild theirs withMcpResourceUri.tokenAudienceOf(...)for the/mcpresource they publish, which replaced the transport's ownvalidateTokenAudience. Non-OMkidtokens (IdP OIDC Bearer tokens) are still judged byProviderTokenValidator. OM-signed tokens with noaud(PATs, bot JWTs, OM session JWTs, pre-upgrade MCP tokens) are accepted everywhere as on main. A presentaudthat is null, empty, non-text, holds a null element or names another resource fails withAuthenticationException(HTTP 401, withWWW-Authenticateerror="invalid_token"on/mcp).default getResource()/setResource(URI)onOAuthAuthorizationServerProvider, overloadedJWTTokenGeneratorandAuthorizationHandler, and a new three-argumentJwtFilterconstructor), so Collate keeps compiling. AJwtFilterbuilt with the existing constructors gets the API rule and refuses MCP-audience tokens.ProtectedResourceMetadata; 30-day refresh tokens survivebaseUrlreconfiguration). Clients that omitresource(e.g., Codex CLI,mcp-remote) remain accepted and receive canonicalaud-bound tokens.docs/decisions/2026-11-25-mcp-oauth-binds-tokens-to-the-canonical-resource.mddocumenting these contracts.Tests:
Use cases covered
resourceparameters are rejected withinvalid_targetat/mcp/authorize(loopback 302, remote Claude.ai 400 HTML return-link perADR:2026-11-02, policy-blocked 400 JSON; IdP never contacted; unknown client/unregistered URI still fails with direct 400invalid_requestand no redirect).resourceparameters at/mcp/token(authorization_codeandrefresh_token) return 400invalid_targetwithout burning the authorization code or invalidating the refresh token; subsequent retry with the canonicalresourcesucceeds withaud == canonicalResourceand/mcptools/listreturns 200.audclaim are rejected at/mcpwith HTTP 401 andWWW-Authenticateerror="invalid_token", while PATs, bot tokens, session tokens, aud-less pre-upgrade tokens, IdP OIDC tokens, and all 9 MCP client profiles (including clients that omitresource) continue to work. Theaud-bound MCP access tokens themselves are refused with 401 by the REST API and the push feed handshake, and accepted at/mcp(McpTokenAudienceIT).Unit tests
openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/util/McpResourceUriTest.java(new, 63 tests)openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/handlers/AuthorizationHandlerTest.java(31 tests)openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/transport/OAuthHttpStatelessServerTransportProviderTest.java(68 tests)openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/provider/UserSSOOAuthProviderTest.java(32 tests)openmetadata-mcp/src/test/java/org/openmetadata/mcp/McpServerRequestContextTest.java(12 tests)openmetadata-service/src/test/java/org/openmetadata/service/security/JWTTokenGeneratorTest.java(25 tests)openmetadata-service/src/test/java/org/openmetadata/service/security/TokenAudienceTest.java(new, 17 tests)openmetadata-service/src/test/java/org/openmetadata/service/security/JwtFilterTest.java(131 tests, 25 new audience cases)openmetadata-service/src/test/java/org/openmetadata/service/socket/SocketAddressFilterTest.java(28 tests)openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpTokenAudienceIT.java(new, 2 tests)AuthorizationHandlerTest,JWTTokenGeneratorTest,JwtFilterTest,McpResourceUriTest,McpServerRequestContextTest,OAuthHttpStatelessServerTransportProviderTest,UserSSOOAuthProviderTest): 337 passed, 0 failed, 0 skipped.openmetadata-mcpunit suite (mvn -B jacoco:prepare-agent package jacoco:report -Pstatic-code-analysis -pl openmetadata-mcp -am -DskipITs): 1,054 passed, 0 failed, 0 skipped.-Pstatic-code-analysis):McpResourceUri.java: 97.2% line (69/71), 96.9% branch (93/96)AuthorizationHandler.java: 100.0% line (94/94)OAuthAuthorizationServerProvider.java: 100.0% line (3/3), 100.0% branch (4/4)JWTTokenGenerator.java: 100.0% changed lines (4/4)JwtFilter.java: 90.0% class line (352/391)OAuthHttpStatelessServerTransportProvider.java: 94.6% changed lines (53/56)UserSSOOAuthProvider.java: 93.3% changed lines (14/15)McpServer.java: 80.0% changed lines (4/5; remaining constructor wiring exercised in ITs)Backend integration tests
openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/SsoMcpSignInChecksIT.java(gapResourceParameterIsNotChecked→resourceParameterIsEnforcedAcrossAuthorizeTokenAndResourceServer) and verified sibling MCP OAuth/profile/revocation ITs (McpOAuthIT,SsoMcpClientProfilesIT,CredentialMcpRevocationIT).Local Java test run: PASSED
f94ec70d39cc(baseorigin/main)--scope full).Ingestion integration tests
Playwright (UI) tests
Manual testing performed
openmetadata-mcpunit suite (1,054/1,054 passed) and targetedopenmetadata-serviceJWT unit tests (JWTTokenGeneratorTest25 +JwtFilterTest106 = 131/131 passed) with JaCoCo coverage verification.CredentialMcpRevocationIT5/5,McpOAuthIT19/19,SsoMcpClientProfilesIT10/10 across all 9 MCP client profiles,SsoMcpSignInChecksIT16/16 including live Jetty multi-value query and query+body smuggling checks and foreign-aud401 rejection on/mcp).mvn -B spotless:check -pl openmetadata-service,openmetadata-mcp,openmetadata-integration-tests,python3 scripts/harness/check_decision_records.py, andpython3 .github/scripts/plan_local_java_tests.py --check-branchall pass cleanly.openmetadata-servicesecurity and socket unit tests 221/221, the touchedopenmetadata-mcpunit classes 209/209,McpTokenAudienceIT2/2,McpOAuthIT22/22,CredentialMcpRevocationIT2/2 andSsoMcpSignInChecksIT16/16. The REST and socket rejection cases inJwtFilterTestandSocketAddressFilterTestfail on f94ec70, where the MCP token was accepted. Not run: the Postgres/OpenSearch lane, and a full WebSocket upgrade with an MCP token (the IT covers the polling handshake; the upgrade calls the same validator).UI screen recording:
Not applicable: backend MCP OAuth and JWT authentication changes only; no UI source files changed.
Checklist:
I have read the CONTRIBUTING document.
My PR title is
Fixes 38479: Enforce RFC 8707 resource parameter and aud binding in MCP OAuthMy PR is linked to a GitHub issue via
Fixes #38479above.I have commented on my code, particularly in hard-to-understand areas.
For JSON Schema changes: Not applicable (no JSON Schema or DB schema changes).
For a UI feature or feature task: Not applicable (backend MCP OAuth security fix with no UI changes).
I have added tests (unit and backend integration tests) and listed them above.
Self-review: I reviewed the final diff against
REVIEW.md(commitf94ec70d39cc35471ad34e5af01b74da21b13e1a. Pass 1 returned 0 🔴 findings and 2 nits which were both resolved by deleting write-onlyAuthorizationParams.resourceand adding live Jetty smuggling checks inSsoMcpSignInChecksIT; Pass 2 caught the Servlet 6.0 query-before-body parameter ordering in the/mcp/tokensmuggling test, which was flipped inf94ec70d39ccand verified passing against live Jetty).Decision check: Added
docs/decisions/2026-11-25-mcp-oauth-binds-tokens-to-the-canonical-resource.mdrecording the single-resource canonical validation contract, backward-compatible acceptance of omittedresourceand absentaud, and why no DB columns were added (python3 scripts/harness/check_decision_records.pyclean).I have added a test that covers the exact scenario we are fixing.