Skip to content

Fixes 38479: Enforce RFC 8707 resource parameter and aud binding in MCP OAuth - #38695

Merged
Vishnuujain merged 7 commits into
open-metadata:mainfrom
Vamsi-klu:fix/38479-mcp-oauth-rfc8707-resource
Nov 27, 2026
Merged

Vishnuujain merged 7 commits into
open-metadata:mainfrom
Vamsi-klu:fix/38479-mcp-oauth-rfc8707-resource

Conversation

@Vamsi-klu

@Vamsi-klu Vamsi-klu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

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 JWT aud claim, recorded the design contract in ADR:2026-11-25-mcp-oauth-binds-tokens-to-the-canonical-resource, and replaced the pinned gap test gapResourceParameterIsNotChecked in SsoMcpSignInChecksIT with end-to-end enforcement assertions.

Type of change:

  • Bug fix

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"]
Loading
  • Canonical resource validation (McpResourceUri):
    • Canonical resource URI is derived exclusively from ProtectedResourceMetadata.getResource() (baseUrl + "/mcp", honoring ADR:2026-10-19-mcp-oauth-discovery-stays-inside-the-base-path, never Host / X-Forwarded-*), stored in volatile fields and propagated to authProvider.setResource(...) at startup and on onConfigurationChanged / rebuildMetadata.
    • McpResourceUri enforces RFC 8707 / RFC 3986 rules: 2,048-char length cap, absolute http/https scheme and host lowercased with Locale.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.
  • Multi-value & smuggling-safe enforcement at /mcp/authorize and /mcp/token:
    • Both endpoints read request.getParameterValues("resource") directly instead of collapsing to values[0], rejecting repeated query params and query+form-body smuggling (?resource=<canonical> + body resource=<foreign>).
    • /mcp/authorize validates client_id and registered redirect_uri first (preventing open redirects on unknown clients or unregistered callbacks), then validates all resource values before creating pending requests or contacting the IdP. Invalid resource returns invalid_target with a static error description (never echoing untrusted resource): loopback/native callbacks get 302, remote https:// callbacks get the 400 HTML return-link page (ADR:2026-11-02), and policy-blocked direct-400 JSON responses preserve authResponse.getError() instead of hardcoding invalid_request.
    • /mcp/token validates all resource values for both authorization_code and refresh_token grants after client auth and required parameter checks, and before loadAuthorizationCode / exchangeAuthorizationCode or exchangeRefreshToken, so bad resource requests return 400 invalid_target without burning a valid code or rotating a refresh token.
  • JWT aud binding & /mcp enforcement (plus defense-in-depth):
    • Added additive 10-arg JWTTokenGenerator.generateJWTToken(..., clientId, audience) and 12-arg getJwtAuthMechanism(..., sessionId, clientId, audience) overloads writing a single-string "aud" claim when non-blank (existing 9-arg/11-arg overloads delegate with null). UserSSOOAuthProvider.issueAccessToken binds minted MCP access tokens to getResource() before storeAccessToken hashes the token.
    • Added TokenAudience, one aud rule for every entry point, which JwtFilter applies while verifying any OpenMetadata-signed token, so REST, the push feed handshake (polling and upgrade) and /mcp all check it. A filter built with the existing constructors serves the OpenMetadata API (REST and SocketAddressFilter) and refuses any OM-signed token that carries aud. The MCP transport and McpServer build theirs with McpResourceUri.tokenAudienceOf(...) for the /mcp resource they publish, which replaced the transport's own validateTokenAudience. Non-OM kid tokens (IdP OIDC Bearer tokens) are still judged by ProviderTokenValidator. OM-signed tokens with no aud (PATs, bot JWTs, OM session JWTs, pre-upgrade MCP tokens) are accepted everywhere as on main. A present aud that is null, empty, non-text, holds a null element or names another resource fails with AuthenticationException (HTTP 401, with WWW-Authenticate error="invalid_token" on /mcp).
  • Backward compatibility, migrations & ADR:
    • Additive public signatures only (default getResource() / setResource(URI) on OAuthAuthorizationServerProvider, overloaded JWTTokenGenerator and AuthorizationHandler, and a new three-argument JwtFilter constructor), so Collate keeps compiling. A JwtFilter built with the existing constructors gets the API rule and refuses MCP-audience tokens.
    • Zero DB migrations (single-resource server validates against canonical ProtectedResourceMetadata; 30-day refresh tokens survive baseUrl reconfiguration). Clients that omit resource (e.g., Codex CLI, mcp-remote) remain accepted and receive canonical aud-bound tokens.
    • Added docs/decisions/2026-11-25-mcp-oauth-binds-tokens-to-the-canonical-resource.md documenting these contracts.

Tests:

Use cases covered

  • Foreign, blank, fragment, query, userinfo, dot-segment, and multi-valued/smuggled resource parameters are rejected with invalid_target at /mcp/authorize (loopback 302, remote Claude.ai 400 HTML return-link per ADR:2026-11-02, policy-blocked 400 JSON; IdP never contacted; unknown client/unregistered URI still fails with direct 400 invalid_request and no redirect).
  • Foreign and query+body smuggled resource parameters at /mcp/token (authorization_code and refresh_token) return 400 invalid_target without burning the authorization code or invalidating the refresh token; subsequent retry with the canonical resource succeeds with aud == canonicalResource and /mcp tools/list returns 200.
  • Stored, active OM-signed JWTs carrying a foreign or malformed aud claim are rejected at /mcp with HTTP 401 and WWW-Authenticate error="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 omit resource) continue to work. The aud-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

  • I added/updated unit tests for all new and changed logic.
  • Files added/updated:
    • 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)
  • Commands & results:
    • Focused unit step (AuthorizationHandlerTest, JWTTokenGeneratorTest, JwtFilterTest, McpResourceUriTest, McpServerRequestContextTest, OAuthHttpStatelessServerTransportProviderTest, UserSSOOAuthProviderTest): 337 passed, 0 failed, 0 skipped.
    • Full openmetadata-mcp unit suite (mvn -B jacoco:prepare-agent package jacoco:report -Pstatic-code-analysis -pl openmetadata-mcp -am -DskipITs): 1,054 passed, 0 failed, 0 skipped.
  • JaCoCo line coverage (-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

  • I replaced the pinned gap test in 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

  • Commit: f94ec70d39cc (base origin/main)
  • Finished: 2026-11-25 13:41 UTC · 51.1 min
  • Scope: focused; merge readiness is not established. Broader steps deferred: 7 (run --scope full).
Step Scope Classes Tests Failed Skipped Min Result
unit openmetadata-mcp (5 classes), openmetadata-service (2 classes) 7 337 0 0 10.9 passed
integration mysql-elasticsearch · parallel 2 24 0 0 18.5 passed
integration mysql-elasticsearch · isolated 2 26 0 0 21.7 passed
  • Impacted, not run locally: 12 classes (listed in the details)

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

Manual testing performed

  1. Ran full openmetadata-mcp unit suite (1,054/1,054 passed) and targeted openmetadata-service JWT unit tests (JWTTokenGeneratorTest 25 + JwtFilterTest 106 = 131/131 passed) with JaCoCo coverage verification.
  2. Ran live MySQL + Elasticsearch Testcontainers MCP integration tests (CredentialMcpRevocationIT 5/5, McpOAuthIT 19/19, SsoMcpClientProfilesIT 10/10 across all 9 MCP client profiles, SsoMcpSignInChecksIT 16/16 including live Jetty multi-value query and query+body smuggling checks and foreign-aud 401 rejection on /mcp).
  3. Verified mvn -B spotless:check -pl openmetadata-service,openmetadata-mcp,openmetadata-integration-tests, python3 scripts/harness/check_decision_records.py, and python3 .github/scripts/plan_local_java_tests.py --check-branch all pass cleanly.
  4. After review, on ad69c3c with MySQL + Elasticsearch: openmetadata-service security and socket unit tests 221/221, the touched openmetadata-mcp unit classes 209/209, McpTokenAudienceIT 2/2, McpOAuthIT 22/22, CredentialMcpRevocationIT 2/2 and SsoMcpSignInChecksIT 16/16. The REST and socket rejection cases in JwtFilterTest and SocketAddressFilterTest fail 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 OAuth

  • My PR is linked to a GitHub issue via Fixes #38479 above.

  • 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 (commit f94ec70d39cc35471ad34e5af01b74da21b13e1a. Pass 1 returned 0 🔴 findings and 2 nits which were both resolved by deleting write-only AuthorizationParams.resource and adding live Jetty smuggling checks in SsoMcpSignInChecksIT; Pass 2 caught the Servlet 6.0 query-before-body parameter ordering in the /mcp/token smuggling test, which was flipped in f94ec70d39cc and verified passing against live Jetty).

  • Decision check: Added docs/decisions/2026-11-25-mcp-oauth-binds-tokens-to-the-canonical-resource.md recording the single-resource canonical validation contract, backward-compatible acceptance of omitted resource and absent aud, and why no DB columns were added (python3 scripts/harness/check_decision_records.py clean).

  • I have added a test that covers the exact scenario we are fixing.

…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>
@Vamsi-klu
Vamsi-klu requested a review from a team as a code owner November 25, 2026 13:48
@Vamsi-klu
Vamsi-klu requested a review from harshach November 25, 2026 13:48
@Vamsi-klu

Copy link
Copy Markdown
Contributor Author

Local Java test run: PASSED — details

  • Commit: f94ec70d39cc (base origin/main)
  • The summary is in the PR description.

Tests run locally

  • unit · openmetadata-mcp (5 classes), openmetadata-service (2 classes): AuthorizationHandlerTest (31 passed), JWTTokenGeneratorTest (25 passed), JwtFilterTest (106 passed), McpResourceUriTest (63 passed), McpServerRequestContextTest (12 passed), OAuthHttpStatelessServerTransportProviderTest (68 passed), UserSSOOAuthProviderTest (32 passed)
  • integration · mysql-elasticsearch · parallel: CredentialMcpRevocationIT (5 passed), McpOAuthIT (19 passed)
  • integration · mysql-elasticsearch · isolated: SsoMcpClientProfilesIT (10 passed), SsoMcpSignInChecksIT (16 passed)

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

  • mvn -B package -pl openmetadata-mcp,openmetadata-service -am -Dspring-boot.repackage.skip=true -Dtest=AIAssetStatusSyncTest,AuthenticationCodeFlowHandlerTest,AuthorizationHandlerTest,BasicAuthLoginServletTest,BotTokenCheckTest,BotTokenRegeneratorTest,ChangeEventsTest,ChangePreviewUtilsTest,ClientAuthenticatorTest,CollectionDAOMcpTest,DefaultAuthorizerTest,EntityTypeNameTest,InternalActionTokenSignerTest,JWTTokenGeneratorTest,JwtFilterTest,McpCallbackServletTest,McpExecutionIndexTest,McpExecutionResourceTest,McpImpersonationTest,McpReadOnlyModeTest,McpResourceUriTest,McpResponseUtilsTest,McpSdkUpgradeTest,McpServerFatalErrorTest,McpServerIndexTest,McpServerMapperTest,McpServerMaskerTest,McpServerRepositoryTest,McpServerRequestContextTest,McpServerResourceTest,McpServerUnconfirmedTokenTest,MintedTokensAreRecognizedTest,MultiUrlJwkProviderTest,OAuthHttpStatelessServerTransportProviderTest,OpenMetadataOperationsSecurityConfigTest,RdfJsonLdContextTest,RdfToolGatingTest,RdfUtilsTest,ReindexingUtilTest,SamlAuthServletHandlerTest,SearchIndexFactoryTest,SocketAddressFilterSpoofRevalidationBypassTest,SocketAddressFilterTest,SystemRepositorySecurityConfigValidationTest,SystemRepositorySecuritySettingsTest,SystemResourceSecurityConfigApplyTest,UserSSOOAuthProviderTest,UserUtilTest -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pmysql-elasticsearch -DintegrationTests.lane=parallel '-Dit.test=<248 classes>' -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=<35 classes>' -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=rdf '-Dit.test=<37 classes>' -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pcache-tests -DintegrationTests.lane=parallel -Dit.test=AlertStateIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Pcache-tests -DintegrationTests.lane=global-state -Dit.test=CredentialRedisDownIT,CredentialRedisNoRoundTripIT,SessionRedisMultiNodeIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
  • mvn -B verify -pl :openmetadata-integration-tests -am -Dspring-boot.repackage.skip=true -Psearch-it -DdatabaseType=postgres -DsearchType=opensearch -Djpw.data.mode=ingest -Dit.test=ColumnIndexingToggleIT,CustomPropertyAggregationIT,DbToEsCountReconciliationIT,ExtensionHighlightSearchIT,GlossarySynonymNgramIT,IndexFieldExplosionIT,IndexMappingTemplatesIT,LiveIndexRetryIT,LiveSearchSettingsChangeIT,NestedHierarchyIndexIT,NoDuplicatesDuringReindexIT,OntologyTermSearchIT,OwnersNestedMappingIT,PerEntitySearchDefaultsIT,ReindexAliasSwapIT,ReindexDocSurvivalIT,ReindexOutageRecoveryIT,ReindexStatsIT,ReindexStopUnderLoadIT,SearchAccessRulesIT,SearchAggregateRbacIT,SearchClusterFitnessReindexE2EIT,SearchCountConsistencyIT,SearchEntityRankingIT,SearchRelevancyPreviewIT,SearchScoringIT,StagedIndexUnrefreshedCountIT,TestCaseStaleDefinitionReindexIT,UnsafeReindexConfigIT -Dfailsafe.failIfNoSpecifiedTests=false -Dtest=NoUnitTestsInThisRun -Dsurefire.failIfNoSpecifiedTests=false
Why these tests
  • added by author: Verify all 9 MCP client profiles, Basic/PAT/bot auth, and token revocation remain green alongside SsoMcpSignInChecksIT ← CredentialMcpRevocationIT, McpOAuthIT, SsoMcpClientProfilesIT
Impacted, not run locally (12)
  • RdfCatalogScaleIT → only with -DrdfCatalogScale=true, which no CI lane sets
  • GoogleSsoSignInUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • EntityLoaderSmokeUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • LongCompoundNameSearchUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • PipelineOwnerIndexUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • DistributedAutoTuneReindexUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • SearchAvailableAllKindsDuringReindexUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • SearchAvailableDuringReindexUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • SelectiveFieldReindexUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • SimpleReindexTriggerUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • GoogleSsoBootstrapUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
  • MockIdpSmokeUIIT → nightly: openmetadata-nightly k8s-java-it (ui-it + embedded JavaUIIT)
Commands
mvn -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

@github-actions

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

This 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 skip-pr-checks label.

@Vishnuujain Vishnuujain self-assigned this Nov 25, 2026

@pmbrull pmbrull left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@Vishnuujain

Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Contributor Author

@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 aud rule now lives in one small class, TokenAudience, and JwtFilter applies it while verifying every OpenMetadata signed token, so REST, the socket handshake (polling and upgrade) and /mcp all go through it. A filter serves the API unless it's built with an audience, so REST and the socket answer an MCP token with a plain 401. The MCP transport and McpServer build theirs for /mcp, which also let me drop the separate check I had in the transport.

Tokens without aud (session JWTs, bot tokens, PATs, and MCP tokens issued before this change) behave exactly as on main everywhere, /mcp included. IdP tokens are unchanged, since ProviderTokenValidator already checks their audience. The flip side is that a newly issued MCP token can't be used against REST anymore, so I spelled out what each entry point accepts in the ADR (ad69c3c).

The new REST and socket cases in JwtFilterTest and SocketAddressFilterTest fail on the previous commit. McpTokenAudienceIT (2f8d689) mints a real token and checks it gets 200 at /mcp and 401 at REST and the push feed, while login, bot and PAT tokens still work in all three places. McpOAuthIT, CredentialMcpRevocationIT and SsoMcpSignInChecksIT pass on MySQL and Elasticsearch. I haven't run the Postgres lane, and the IT covers the polling handshake rather than a full WebSocket upgrade, though both call the same validator.

@Vishnuujain updated, ready for another look.

@pmbrull pmbrull left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

✅ 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 manerow 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.

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

@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 /mcp URL. 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 of McpResourceUri and its tests could go.
  • The resource URL is always the same as the issuer URL (baseUrl + mcpEndpoint for both). Could we keep one copy instead of adding getResource/setResource and a second field? Right now authorize reads one copy and token and /mcp read the other.
  • extractResourceValues: getParameterValues() and getParameterMap() read the same data, so the fallback never adds anything outside mocks.

targetResource != null
? McpResourceUri.canonicalize(targetResource)
.map(URI::toString)
.orElse(targetResource.toString())

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.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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)) {

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

@manerow thanks for pointing out both paths. The direct 400 now keeps the OAuth error code and uses Authorization request failed as the description. An invalid MCP resource URI also logs an error at startup and on reload, and token exchange returns server_error before it consumes the grant. Both changes have regression coverage in 876c769db64, and all 404 focused Java unit tests passed.

@Vishnuujain

Copy link
Copy Markdown
Contributor

@Vamsi-klu thanks for the fixes, can you please resolve merge conflict?

@Vishnuujain
Vishnuujain enabled auto-merge (squash) November 27, 2026 13:22
@Vishnuujain Vishnuujain added the To release Will cherry-pick this PR into the release branch label Nov 27, 2026
@gitar-bot

gitar-bot Bot commented Nov 27, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 🔴 High risk

Binding 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 /mcp resource via the JWT aud claim. No issues found.

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

@Vishnuujain
Vishnuujain merged commit 9078572 into open-metadata:main Nov 27, 2026
34 of 35 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

🤖 Backport to 2.1 is under way. It is built from openmetadata-collate, which holds the credentials needed to open a PR here, and it will comment again with the result — nothing is needed from you unless it reports otherwise.

@github-actions

Copy link
Copy Markdown
Contributor

🤖 Backport to 2.0 is under way. It is built from openmetadata-collate, which holds the credentials needed to open a PR here, and it will comment again with the result — nothing is needed from you unless it reports otherwise.

@gh-bot-collate

Copy link
Copy Markdown

🤖 Backport to 2.1 opened as #38996 (clean cherry-pick). It merges itself once the checks pass.

@gh-bot-collate

Copy link
Copy Markdown

🤖 Backport to 2.0 failed. The conflict could not be resolved, so this change is not on that branch. Resolver run.

Vishnuujain added a commit that referenced this pull request Nov 27, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

To release Will cherry-pick this PR into the release branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP OAuth ignores the resource parameter

4 participants