From e3cceaf097a82209937c35754e3134244821c987 Mon Sep 17 00:00:00 2001 From: Kia Yun Date: Wed, 25 Nov 2026 22:07:35 +0800 Subject: [PATCH 1/8] Fix MCP sign-in for public OIDC clients (#38480) --- ...back-needs-the-state-of-a-pending-login.md | 13 +++- docs/sso-integration-testing.md | 2 +- .../it/sso/config/SsoConfigs.java | 3 +- .../it/sso/oidc/MockOidcProvider.java | 37 +++++++++-- .../it/sso/oidc/MockOidcTokenEndpoint.java | 6 ++ .../it/tests/mcp/SsoMcpSignInChecksIT.java | 51 +++++++++----- .../auth/handlers/McpCallbackServlet.java | 15 +---- .../auth/provider/UserSSOOAuthProvider.java | 18 +++-- .../security/AuthServeletHandlerFactory.java | 6 +- .../security/AuthServeletHandlerRegistry.java | 10 +++ .../AuthenticationCodeFlowHandler.java | 39 +++++++++-- .../security/NoopAuthServeletHandler.java | 3 +- .../PublicOidcAuthServletHandler.java | 66 +++++++++++++++++++ .../PublicOidcAuthServletHandlerTest.java | 41 ++++++++++++ 14 files changed, 250 insertions(+), 60 deletions(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java diff --git a/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md b/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md index a291ab1dad4b..810ceaadf74d 100644 --- a/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md +++ b/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md @@ -1,10 +1,10 @@ # The MCP callback needs the state of a pending login - **Status:** Accepted -- **Revisions:** v1 2026-10-30 (initial) +- **Revisions:** v1 2026-10-30 (initial) · v2 2026-11-25 (public OIDC clients) - **Deciders:** Vishnu Jain - **Guard:** `McpCallbackServletTest` (`doGet_idTokenWithoutState_returns400AndIssuesNoCode`) -- **Related:** #29228, #36655, ADR:2026-10-23-mcp-sso-asks-consent-after-the-idp-round-trip +- **Related:** #29228, #36655, #38480, ADR:2026-10-23-mcp-sso-asks-consent-after-the-idp-round-trip ## Context @@ -26,3 +26,12 @@ when its pending request has expired (10 minutes), and that login has to be rest - A provider set up to return the ID token in the URL fragment cannot complete an MCP login; it needs the authorization-code flow, as the web login does. - Adding a second callback path again means repeating every check `handleCallback` makes. + +## Amendment — public OIDC clients + +MCP uses the same pending login, registered callback and consent step when the OpenMetadata +OIDC client is public. The server exchanges the provider's authorization code using the public +client ID and an S256 PKCE verifier. The provider registration must allow that exchange from +the server and register the OpenMetadata `/callback` URL. The browser's ordinary sign-in keeps +its own flow. `SsoMcpSignInChecksIT.publicOidcClientSignsInAndCallsATool` exercises both the +provider exchange and the agent's first tool call. diff --git a/docs/sso-integration-testing.md b/docs/sso-integration-testing.md index 253421d6411a..e7e71c961b16 100644 --- a/docs/sso-integration-testing.md +++ b/docs/sso-integration-testing.md @@ -83,7 +83,7 @@ reports success. | Session renewal | `SsoTokenRenewalIT` | RN-01 to RN-09, RN-12, RN-16 | | Provider shapes (Okta, Google, Auth0, Cognito, Keycloak, Entra) | `SsoOidcProviderProfilesIT` | OC-02, OC-03, OP-01 per provider | | MCP client sign-in, per recorded client profile | `SsoMcpClientProfilesIT` | confidential OIDC and the password form | -| MCP sign-in per provider shape, refusals and known gaps | `SsoMcpSignInChecksIT` | provider shapes, code replay, consent denial, cross-client refresh, no account, `gap...` | +| MCP sign-in per provider shape, refusals and known gaps | `SsoMcpSignInChecksIT` | public client sign-in with S256 PKCE, confidential provider shapes, code replay, consent denial, cross-client refresh, no account, `gap...` | SAML, LDAP, identity resolution, role sync, settings changes, Test Login, multi-node sessions and SCIM follow the same pattern and are added phase by phase. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/config/SsoConfigs.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/config/SsoConfigs.java index fad59539fb21..7d1929264717 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/config/SsoConfigs.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/config/SsoConfigs.java @@ -56,7 +56,8 @@ public static SecurityConfiguration publicOidc( .withProviderName(PROVIDER_NAME) .withClientType(ClientType.PUBLIC) .withAuthority(provider.issuer()) - .withClientId(MockOidcProvider.CLIENT_ID) + .withClientId(provider.clientId()) + .withOidcConfiguration(null) .withCallbackUrl(SsoServer.url(SsoServer.CALLBACK_PATH)) .withPublicKeyUrls(List.of(provider.jwksUri())); return config; diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcProvider.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcProvider.java index 7bb0d4139277..65d81ceffe58 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcProvider.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcProvider.java @@ -53,6 +53,7 @@ public final class MockOidcProvider implements AutoCloseable { private final MockHttp.LoopbackServer server; private final OidcProviderProfile profile; + private final boolean publicClient; private final String baseUrl; private final String issuer; private final MockOidcKeys keys = new MockOidcKeys(); @@ -65,13 +66,16 @@ public final class MockOidcProvider implements AutoCloseable { private final AtomicReference nextJwksGate = new AtomicReference<>(); private final AtomicReference nextAuthorizationError = new AtomicReference<>(); - private MockOidcProvider(MockHttp.LoopbackServer server, OidcProviderProfile profile) { + private MockOidcProvider( + MockHttp.LoopbackServer server, OidcProviderProfile profile, boolean publicClient) { this.server = server; this.profile = profile; + this.publicClient = publicClient; this.baseUrl = server.localhostUrl(); this.issuer = profile.discoveryIssuer(baseUrl); - this.tokens = new MockOidcTokens(profile.tokenIssuer(baseUrl), CLIENT_ID, keys, profile); - this.tokenEndpoint = new MockOidcTokenEndpoint(tokens, journal, CLIENT_ID, CLIENT_SECRET); + this.tokens = new MockOidcTokens(profile.tokenIssuer(baseUrl), clientId(), keys, profile); + this.tokenEndpoint = + new MockOidcTokenEndpoint(tokens, journal, clientId(), publicClient ? null : CLIENT_SECRET); } public static MockOidcProvider start() { @@ -80,11 +84,24 @@ public static MockOidcProvider start() { /** A provider that shapes its issuer and claims the way {@code profile}'s real one does. */ public static MockOidcProvider start(OidcProviderProfile profile) { - MockOidcProvider provider = new MockOidcProvider(MockHttp.bindLoopbackServer(), profile); + return start(profile, false); + } + + public static MockOidcProvider startPublicClient() { + return start(OidcProviderProfile.CUSTOM, true); + } + + private static MockOidcProvider start(OidcProviderProfile profile, boolean publicClient) { + MockOidcProvider provider = + new MockOidcProvider(MockHttp.bindLoopbackServer(), profile, publicClient); provider.server.start(provider.routes()); return provider; } + public String clientId() { + return publicClient ? "om-sso-it-public-client" : CLIENT_ID; + } + public OidcProviderProfile profile() { return profile; } @@ -245,6 +262,12 @@ private Map authorizationResult(Map query) { if (refusal != null) { return Map.of(ERROR, refusal); } + if (publicClient + && (!clientId().equals(query.get(MockOidcProtocol.CLIENT_ID)) + || !"S256".equals(query.get("code_challenge_method")) + || query.getOrDefault(CODE_CHALLENGE, "").isBlank())) { + return Map.of(ERROR, "invalid_request"); + } MockOidcIdentity user = signedInUser.get(); return user == null ? Map.of(ERROR, LOGIN_REQUIRED) : Map.of(CODE, issueCode(user, query)); } @@ -285,9 +308,11 @@ private Discovery discovery() { List.of("code", "id_token", "code id_token"), List.of("public"), List.of("RS256"), - List.of(CLIENT_SECRET_BASIC, CLIENT_SECRET_POST), + publicClient ? List.of("none") : List.of(CLIENT_SECRET_BASIC, CLIENT_SECRET_POST), List.of("S256"), - List.of(GRANT_AUTHORIZATION_CODE, GRANT_REFRESH_TOKEN, GRANT_CLIENT_CREDENTIALS), + publicClient + ? List.of(GRANT_AUTHORIZATION_CODE) + : List.of(GRANT_AUTHORIZATION_CODE, GRANT_REFRESH_TOKEN, GRANT_CLIENT_CREDENTIALS), mode.isAdvertised() ? Boolean.TRUE : null); } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokenEndpoint.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokenEndpoint.java index fe1880eab72d..a832fb47a541 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokenEndpoint.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokenEndpoint.java @@ -152,6 +152,12 @@ private static void respondWith(HttpExchange exchange, RefreshOutcome outcome) private boolean isRegisteredClient(HttpExchange exchange, Map form) { String authorization = exchange.getRequestHeaders().getFirst(MockHttp.AUTHORIZATION); + if (clientSecret == null) { + return authorization == null + && !form.containsKey(CLIENT_SECRET) + && clientId.equals(form.get(CLIENT_ID)) + && GRANT_AUTHORIZATION_CODE.equals(form.get(GRANT_TYPE)); + } String[] credentials = authorization == null ? new String[] {form.get(CLIENT_ID), form.get(CLIENT_SECRET)} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/SsoMcpSignInChecksIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/SsoMcpSignInChecksIT.java index 83f4102a176f..f2594d30904f 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/SsoMcpSignInChecksIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/SsoMcpSignInChecksIT.java @@ -22,6 +22,7 @@ import org.openmetadata.it.sso.browser.SsoNavigation; import org.openmetadata.it.sso.config.SecurityConfigSwap; import org.openmetadata.it.sso.config.SsoConfigs; +import org.openmetadata.it.sso.config.SsoServer; import org.openmetadata.it.sso.oidc.MockOidcIdentity; import org.openmetadata.it.sso.oidc.MockOidcProvider; import org.openmetadata.it.sso.oidc.OidcProviderProfile; @@ -237,25 +238,41 @@ void gapResourceParameterIsNotChecked(TestNamespace ns) throws Exception { } } - /** A public OIDC client has no server-side login for the MCP sign-in to hand over to. */ @Test - void gapPublicOidcClientCannotSignIn() throws Throwable { - securityConfig.withVariant( - config -> SsoConfigs.publicOidc(securityConfig.originalCopy(), provider), - () -> { - provider.clearJournal(); - JsonNode server = discoverAuthorizationServer(); - Authorization authorization = authorizationFor(CLIENT, server, register(CLIENT, server)); - - SsoNavigation navigation = navigateUntilTheClient(server, authorization); + void publicOidcClientSignsInAndCallsATool(TestNamespace ns) throws Throwable { + try (MockOidcProvider publicProvider = MockOidcProvider.startPublicClient()) { + securityConfig.withVariant( + config -> SsoConfigs.publicOidc(config, publicProvider), + () -> { + User user = createUser(new CreateUser(), ns.shortPrefix("public")); + try { + publicProvider.signIn(MockOidcIdentity.forEmail(user.getEmail())); + assertClientConnects(CLIENT, user, this::approveConsent); - assertThat(navigation.finalUrl().toString()) - .as(navigation.describe()) - .startsWith(CLIENT.redirectUri()) - .contains("error=authorization_failed"); - // The sign-in stops at the server: the provider is never asked to authorize. - assertThat(provider.authorizeRequests()).isEmpty(); - }); + assertThat(publicProvider.authorizeRequests()).hasSize(1); + assertThat(publicProvider.tokenRequests()).hasSize(1); + var authorization = publicProvider.authorizeRequests().getFirst(); + var exchange = publicProvider.tokenRequests().getFirst(); + String callback = SsoServer.url(SsoServer.CALLBACK_PATH); + assertThat(authorization.parameter("state")).isNotBlank(); + assertThat(authorization.parameter("nonce")).isNotBlank(); + assertThat(exchange.parameter("code_verifier")).isNotBlank(); + assertThat(authorization.parameters()) + .containsEntry("client_id", publicProvider.clientId()) + .containsEntry("redirect_uri", callback) + .containsEntry("code_challenge_method", "S256") + .containsEntry("code_challenge", s256(exchange.parameter("code_verifier"))); + assertThat(exchange.parameters()) + .containsEntry("grant_type", "authorization_code") + .containsEntry("client_id", publicProvider.clientId()) + .containsEntry("redirect_uri", callback) + .doesNotContainKey("client_secret"); + assertThat(exchange.authorization()).isNull(); + } finally { + hardDelete(user); + } + }); + } } private User signedInUser(TestNamespace ns) { diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/handlers/McpCallbackServlet.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/handlers/McpCallbackServlet.java index ef10ae816527..06516022c5f8 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/handlers/McpCallbackServlet.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/handlers/McpCallbackServlet.java @@ -28,7 +28,6 @@ import org.openmetadata.mcp.server.auth.validators.IdTokenValidator; import org.openmetadata.schema.api.configuration.MCPConfiguration; import org.openmetadata.schema.api.configuration.OpenMetadataBaseUrlConfiguration; -import org.openmetadata.schema.services.connections.metadata.AuthProvider; import org.openmetadata.schema.settings.Settings; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.SystemRepository; @@ -95,19 +94,7 @@ public McpCallbackServlet(UserSSOOAuthProvider userSSOProvider) { } protected AuthenticationCodeFlowHandler resolveSsoHandler() { - try { - var authConfig = SecurityConfigurationManager.getCurrentAuthConfig(); - if (authConfig == null - || authConfig.getProvider() == null - || authConfig.getProvider() == AuthProvider.BASIC - || authConfig.getProvider() == AuthProvider.LDAP) { - return null; - } - return AuthenticationCodeFlowHandler.getInstance(); - } catch (Exception e) { - LOG.warn("SSO handler not available: {}", e.getMessage()); - return null; - } + return userSSOProvider.getSsoHandler(getServletConfig() == null ? null : getServletContext()); } private String resolveBaseUrl() { diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/provider/UserSSOOAuthProvider.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/provider/UserSSOOAuthProvider.java index 3a6e08e6ac3d..35db51d43068 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/provider/UserSSOOAuthProvider.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/provider/UserSSOOAuthProvider.java @@ -4,6 +4,7 @@ import static org.openmetadata.service.security.AuthenticationCodeFlowHandler.getHttpSession; import static org.openmetadata.service.util.UserUtil.getRoleListFromUser; +import jakarta.servlet.ServletContext; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequestWrapper; import jakarta.servlet.http.HttpServletResponse; @@ -47,6 +48,7 @@ import org.openmetadata.service.jdbi3.McpGrantTransaction; import org.openmetadata.service.jdbi3.oauth.OAuthRecords.McpPendingAuthRequest; import org.openmetadata.service.jdbi3.oauth.OAuthRecords.OAuthAuthorizationCodeRecord; +import org.openmetadata.service.security.AuthServeletHandlerRegistry; import org.openmetadata.service.security.AuthenticationCodeFlowHandler; import org.openmetadata.service.security.McpClientPolicy; import org.openmetadata.service.security.auth.SamlAuthServletHandler; @@ -162,13 +164,10 @@ public void setIssuer(String issuer) { this.issuer = issuer; } - /** - * Gets the SSO handler from SecurityConfigurationManager. This is resolved dynamically from - * database configuration, allowing configuration changes without server restart. - */ - private AuthenticationCodeFlowHandler getSsoHandler() { + /** Both ends of the OIDC round trip resolve the handler installed for this server. */ + public AuthenticationCodeFlowHandler getSsoHandler(ServletContext context) { try { - return AuthenticationCodeFlowHandler.getInstance(); + return AuthServeletHandlerRegistry.getOidcHandlerForMcp(context, getBaseUrl()); } catch (Exception e) { LOG.warn("SSO handler not available: {}", e.getMessage()); return null; @@ -336,7 +335,8 @@ private String validateAndCreatePendingRequest( private CompletableFuture handleSSOAuthorization( OAuthClientInformation client, AuthorizationParams params) throws AuthorizeException { - AuthenticationCodeFlowHandler ssoHandler = getSsoHandler(); + AuthenticationCodeFlowHandler ssoHandler = + getSsoHandler(currentRequest.get().getServletContext()); if (ssoHandler == null) { throw new AuthorizeException( "server_error", "SSO authentication is not available. SSO handler not initialized."); @@ -355,9 +355,7 @@ private CompletableFuture handleSSOAuthorization( // AuthenticationCodeFlowHandler.handleLogin() matches this against expectedMcpCallback // to detect MCP flow, then uses the SSO-registered callback URL for the actual redirect_uri // sent to the SSO provider. After auth, AuthCallbackServlet forwards to /mcp/callback. - String serverUrl = - SecurityConfigurationManager.getCurrentAuthConfig().getOidcConfiguration().getServerUrl(); - String mcpCallbackUrl = serverUrl + "/mcp/callback"; + String mcpCallbackUrl = ssoHandler.getMcpCallbackUrl(); LOG.info("Starting SSO redirect for MCP OAuth (MCP callback: {})", mcpCallbackUrl); HttpServletRequest wrappedRequest = diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthServeletHandlerFactory.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthServeletHandlerFactory.java index 0c1f054c30a5..3147002be6c6 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthServeletHandlerFactory.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthServeletHandlerFactory.java @@ -57,6 +57,9 @@ public static AuthServeletHandler getHandler( case AWS_COGNITO: // OIDC providers use AuthenticationCodeFlowHandler LOG.info("OIDC provider {} detected, clientType: {}", provider, authConfig.getClientType()); + if (ClientType.PUBLIC.equals(authConfig.getClientType())) { + return new PublicOidcAuthServletHandler(authConfig, authzConfig, sessionService); + } if (ClientType.CONFIDENTIAL.equals(authConfig.getClientType())) { try { AuthenticationCodeFlowHandler handler = @@ -76,8 +79,7 @@ public static AuthServeletHandler getHandler( } } LOG.warn( - "OIDC provider {} requires CONFIDENTIAL client type, but got: {}. " - + "Set AUTHENTICATION_CLIENT_TYPE=confidential to enable SSO.", + "OIDC provider {} has unsupported client type: {}.", provider, authConfig.getClientType()); return NoopAuthServeletHandler.getInstance(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthServeletHandlerRegistry.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthServeletHandlerRegistry.java index 441d6ec0015e..a85b21a5ba86 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthServeletHandlerRegistry.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthServeletHandlerRegistry.java @@ -27,6 +27,16 @@ public static AuthServeletHandler getHandler(ServletContext servletContext) { return getHandler(); } + /** Resolve from the live servlet context so a provider change also replaces the MCP login. */ + public static AuthenticationCodeFlowHandler getOidcHandlerForMcp( + ServletContext context, String baseUrl) { + return switch (getHandler(context)) { + case AuthenticationCodeFlowHandler confidential -> confidential; + case PublicOidcAuthServletHandler publicClient -> publicClient.forMcp(baseUrl); + default -> null; + }; + } + public static void setHandler(AuthServeletHandler handler) { currentHandler = handler; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthenticationCodeFlowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthenticationCodeFlowHandler.java index b4ee10ff6352..573e3edb39a8 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthenticationCodeFlowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthenticationCodeFlowHandler.java @@ -168,6 +168,7 @@ public class AuthenticationCodeFlowHandler implements AuthServeletHandler { private static volatile AuthenticationCodeFlowHandler latestInstance; + private final boolean publicMcpClient; private OidcClient client; private List claimsOrder; private Map claimsMapping; @@ -222,6 +223,14 @@ public AuthenticationCodeFlowHandler( AuthenticationConfiguration authenticationConfiguration, AuthorizerConfiguration authorizerConfiguration, SessionService sessionService) { + this(authenticationConfiguration, authorizerConfiguration, sessionService, false); + } + + AuthenticationCodeFlowHandler( + AuthenticationConfiguration authenticationConfiguration, + AuthorizerConfiguration authorizerConfiguration, + SessionService sessionService, + boolean publicMcpClient) { // Assert oidcConfig and Callback Url CommonHelper.assertNotNull( "OidcConfiguration", authenticationConfiguration.getOidcConfiguration()); @@ -238,8 +247,11 @@ public AuthenticationCodeFlowHandler( new OidcProviderTokenRefresher( grant -> createTokenRequest(client.getConfiguration(), clientAuthentication, grant), request -> executeTokenHttpRequest(client.getConfiguration(), request)); + this.publicMcpClient = publicMcpClient; initializeFields(); - latestInstance = this; + if (!publicMcpClient) { + latestInstance = this; + } } public static AuthenticationCodeFlowHandler getInstance() { @@ -273,7 +285,8 @@ public synchronized void updateConfiguration( } private void initializeFields() { - this.client = buildOidcClient(authenticationConfiguration.getOidcConfiguration()); + this.client = + buildOidcClient(authenticationConfiguration.getOidcConfiguration(), publicMcpClient); client.setCallbackUrl(authenticationConfiguration.getOidcConfiguration().getCallbackUrl()); // Create the OIDC metadata resolver during single-threaded startup so concurrent logins never // race to lazily initialize it. pac4j 6 normally does this in client.init(), but OM does not @@ -345,16 +358,21 @@ static String normalizePrompt(String configuredPrompt) { } static OidcClient buildOidcClient(OidcClientConfig clientConfig) { + return buildOidcClient(clientConfig, false); + } + + private static OidcClient buildOidcClient( + OidcClientConfig clientConfig, boolean publicMcpClient) { String id = clientConfig.getId(); String secret = clientConfig.getSecret(); - if (CommonHelper.isNotBlank(id) && CommonHelper.isNotBlank(secret)) { + if (CommonHelper.isNotBlank(id) && (publicMcpClient || CommonHelper.isNotBlank(secret))) { OidcConfiguration configuration = new OidcConfiguration(); configuration.setClientId(id); configuration.setResponseMode("query"); // Add Secret - if (CommonHelper.isNotBlank(secret)) { + if (!publicMcpClient && CommonHelper.isNotBlank(secret)) { configuration.setSecret(secret); } @@ -447,6 +465,13 @@ static OidcClient buildOidcClient(OidcClientConfig clientConfig) { oidcClient = new OidcClient(configuration); } + if (publicMcpClient) { + final OidcConfiguration publicConfiguration = oidcClient.getConfiguration(); + publicConfiguration.setWithState(true); + publicConfiguration.setUseNonce(true); + publicConfiguration.setDisablePkce(false); + publicConfiguration.setPkceMethod(CodeChallengeMethod.S256); + } oidcClient.setName(String.format("OMOidcClient%s", oidcClient.getName())); return oidcClient; } @@ -550,8 +575,12 @@ private static boolean isForcedLogin(String prompt) { && Arrays.stream(prompt.split("\\s+")).anyMatch(FORCED_LOGIN_PROMPT::equalsIgnoreCase); } + public String getMcpCallbackUrl() { + return serverUrl + MCP_CALLBACK_PATH; + } + private boolean isMcpRedirectUri(String redirectUri) { - return (serverUrl + MCP_CALLBACK_PATH).equals(redirectUri); + return getMcpCallbackUrl().equals(redirectUri); } /** diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/NoopAuthServeletHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/NoopAuthServeletHandler.java index 88d7b82d6276..e31ef382cc38 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/NoopAuthServeletHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/NoopAuthServeletHandler.java @@ -9,8 +9,7 @@ public class NoopAuthServeletHandler implements AuthServeletHandler { private static final NoopAuthServeletHandler INSTANCE = new NoopAuthServeletHandler(); - // Private constructor to prevent instantiation - private NoopAuthServeletHandler() {} + NoopAuthServeletHandler() {} // Public method to access the singleton instance public static NoopAuthServeletHandler getInstance() { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java new file mode 100644 index 000000000000..c9586f1a4353 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java @@ -0,0 +1,66 @@ +package org.openmetadata.service.security; + +import java.util.Objects; +import org.apache.commons.lang3.StringUtils; +import org.openmetadata.schema.api.security.AuthenticationConfiguration; +import org.openmetadata.schema.api.security.AuthorizerConfiguration; +import org.openmetadata.schema.security.client.OidcClientConfig; +import org.openmetadata.schema.services.connections.metadata.AuthProvider; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.security.session.SessionService; +import org.openmetadata.service.util.ValidationHttpUtil; + +/** Public web logins stay in the SPA. Only MCP needs a server-side code exchange for this client. */ +final class PublicOidcAuthServletHandler extends NoopAuthServeletHandler { + private static final String DISCOVERY_PATH = "/.well-known/openid-configuration"; + private final AuthenticationConfiguration authentication; + private final AuthorizerConfiguration authorizer; + private final SessionService sessions; + private AuthenticationCodeFlowHandler handler; + private String baseUrl; + + PublicOidcAuthServletHandler( + AuthenticationConfiguration authentication, + AuthorizerConfiguration authorizer, + SessionService sessions) { + this.authentication = authentication; + this.authorizer = authorizer; + this.sessions = sessions; + } + + synchronized AuthenticationCodeFlowHandler forMcp(String configuredBaseUrl) { + final String base = StringUtils.stripEnd(configuredBaseUrl, "/"); + if (handler == null || !Objects.equals(baseUrl, base)) { + // Only public-client deployments that actually use MCP need backend discovery. + final AuthenticationConfiguration effective = + JsonUtils.deepCopy(authentication, AuthenticationConfiguration.class); + effective.setOidcConfiguration(publicCodeFlow(authentication, base)); + handler = new AuthenticationCodeFlowHandler(effective, authorizer, sessions, true); + baseUrl = base; + } + return handler; + } + + static OidcClientConfig publicCodeFlow(AuthenticationConfiguration authentication, String base) { + String authority = + StringUtils.stripEnd(StringUtils.defaultString(authentication.getAuthority()).strip(), "/"); + if (authority.isBlank() + || StringUtils.isBlank(authentication.getClientId()) + || StringUtils.isBlank(base)) { + throw new IllegalArgumentException( + "MCP public OIDC sign-in needs an authority, client ID and server URL"); + } + if (authentication.getProvider() == AuthProvider.AZURE && !authority.endsWith("/v2.0")) { + authority += "/v2.0"; + } + final String discovery = authority + DISCOVERY_PATH; + ValidationHttpUtil.validateUrl(discovery); + return new OidcClientConfig() + .withId(authentication.getClientId()) + .withDiscoveryUri(discovery) + .withDisablePkce(false) + .withServerUrl(base) + .withCallbackUrl( + StringUtils.defaultIfBlank(authentication.getCallbackUrl(), base + "/callback")); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java new file mode 100644 index 000000000000..be24d351d422 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java @@ -0,0 +1,41 @@ +package org.openmetadata.service.security; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.openmetadata.schema.api.security.AuthenticationConfiguration; +import org.openmetadata.schema.security.client.OidcClientConfig; +import org.openmetadata.schema.services.connections.metadata.AuthProvider; + +class PublicOidcAuthServletHandlerTest { + @ParameterizedTest + @CsvSource({ + "CUSTOM_OIDC, /realms/catalog/, /realms/catalog", + "AUTH_0, /, ''", + "AZURE, /tenant, /tenant/v2.0", + "AZURE, /tenant/v2.0/, /tenant/v2.0" + }) + void derivesDiscoveryFromThePublicAuthority( + AuthProvider provider, String authorityPath, String discoveryPath) { + String authority = "https://localhost" + authorityPath; + String callback = "https://catalog.example.com/callback"; + AuthenticationConfiguration authentication = + new AuthenticationConfiguration() + .withProvider(provider) + .withAuthority(authority) + .withCallbackUrl(callback) + .withClientId("public-client") + .withOidcConfiguration( + new OidcClientConfig().withId("old-client").withSecret("unused")); + + OidcClientConfig client = + PublicOidcAuthServletHandler.publicCodeFlow(authentication, "https://catalog.example.com"); + assertThat(client.getDiscoveryUri()) + .isEqualTo("https://localhost" + discoveryPath + "/.well-known/openid-configuration"); + assertThat(client.getId()).isEqualTo("public-client"); + assertThat(client.getCallbackUrl()).isEqualTo(callback); + assertThat(client.getSecret()).isNull(); + assertThat(client.getDisablePkce()).isFalse(); + } +} From 18e1aa313ed81621116889388924c101adfd0182 Mon Sep 17 00:00:00 2001 From: Kia Yun Date: Wed, 25 Nov 2026 22:38:55 +0800 Subject: [PATCH 2/8] Bind public MCP sign-in to its callback and provider configuration --- ...back-needs-the-state-of-a-pending-login.md | 23 ++- .../it/sso/config/SsoConfigs.java | 2 +- .../it/sso/oidc/MockOidcProvider.java | 5 + .../it/sso/oidc/MockOidcTokenEndpoint.java | 9 +- .../it/tests/mcp/SsoMcpSignInChecksIT.java | 130 +++++++++++++- .../auth/handlers/McpCallbackServlet.java | 103 +++-------- .../auth/provider/UserSSOOAuthProvider.java | 6 +- .../auth/validators/IdTokenValidator.java | 69 ++++++-- .../auth/handlers/McpCallbackServletTest.java | 50 ++---- .../auth/validators/IdTokenValidatorTest.java | 165 +++++++++++++++++- .../AuthenticationCodeFlowHandler.java | 94 +++++++--- .../security/IdentityProviderKeys.java | 56 +++--- .../security/ProviderTokenValidator.java | 56 ++++-- .../PublicOidcAuthServletHandler.java | 22 ++- .../security/PublicOidcConfiguration.java | 127 ++++++++++++++ .../security/ProviderTokenValidatorTest.java | 8 +- .../PublicOidcAuthServletHandlerTest.java | 37 +++- .../security/PublicOidcConfigurationTest.java | 157 +++++++++++++++++ 18 files changed, 905 insertions(+), 214 deletions(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcConfiguration.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcConfigurationTest.java diff --git a/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md b/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md index 810ceaadf74d..fef60f7c4a3b 100644 --- a/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md +++ b/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md @@ -29,9 +29,20 @@ when its pending request has expired (10 minutes), and that login has to be rest ## Amendment — public OIDC clients -MCP uses the same pending login, registered callback and consent step when the OpenMetadata -OIDC client is public. The server exchanges the provider's authorization code using the public -client ID and an S256 PKCE verifier. The provider registration must allow that exchange from -the server and register the OpenMetadata `/callback` URL. The browser's ordinary sign-in keeps -its own flow. `SsoMcpSignInChecksIT.publicOidcClientSignsInAndCallsATool` exercises both the -provider exchange and the agent's first tool call. +For a public OIDC client, MCP uses the top-level client ID and discovers the provider at +`/.well-known/openid-configuration`. For Azure, the authority gains `/v2.0` if needed. +The public flow derives its own settings independently of the confidential `oidcConfiguration`. +The MCP base URL comes from the MCP settings, falling back to the system OpenMetadata URL. + +Register `/mcp/callback` at the identity provider +for a server-side authorization-code exchange using the public client ID and S256 PKCE. Include +the deployment base path, if configured. OpenMetadata sends this same URI when it requests and +redeems the code. The browser application retains its own registered redirect. MCP requires a pending login and asks for consent before issuing a grant. + +A Microsoft Entra redirect registered as a single-page application requires a browser origin +during redemption. Keep the browser redirect registered for the SPA and configure the MCP redirect +for server-side redemption under the same public client ID. A browser-only registration +fails before consent. [Microsoft Entra authorization code flow](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow#redirect-uris-for-single-page-apps) + +`SsoMcpSignInChecksIT` exercises the provider exchange, the agent's first tool call and refusal +by a browser-only provider registration. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/config/SsoConfigs.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/config/SsoConfigs.java index 7d1929264717..4db25ef07202 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/config/SsoConfigs.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/config/SsoConfigs.java @@ -58,7 +58,7 @@ public static SecurityConfiguration publicOidc( .withAuthority(provider.issuer()) .withClientId(provider.clientId()) .withOidcConfiguration(null) - .withCallbackUrl(SsoServer.url(SsoServer.CALLBACK_PATH)) + .withCallbackUrl(SsoServer.url(SsoServer.SPA_CALLBACK_PATH)) .withPublicKeyUrls(List.of(provider.jwksUri())); return config; } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcProvider.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcProvider.java index 65d81ceffe58..ba05c77d271f 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcProvider.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcProvider.java @@ -147,6 +147,11 @@ public void defectNextIdToken(IdTokenDefect defect) { tokens.defectNextIdToken(defect); } + /** Models a provider registration which permits redemption only from a browser. */ + public void registerRedirectForBrowserOnly() { + tokenEndpoint.registerRedirectForBrowserOnly(); + } + public void answerRefreshesWith(RefreshOutcome outcome) { tokenEndpoint.answerRefreshesWith(outcome); } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokenEndpoint.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokenEndpoint.java index a832fb47a541..d17b34481c90 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokenEndpoint.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/sso/oidc/MockOidcTokenEndpoint.java @@ -44,6 +44,7 @@ final class MockOidcTokenEndpoint implements HttpHandler { private final MockRequestJournal journal; private final String clientId; private final String clientSecret; + private volatile boolean browserOnlyRedirect; private final AtomicReference refreshOutcome = new AtomicReference<>(RefreshOutcome.renew()); private final AtomicReference nextCodeExchangeFailure = new AtomicReference<>(); @@ -57,6 +58,10 @@ final class MockOidcTokenEndpoint implements HttpHandler { this.clientSecret = clientSecret; } + void registerRedirectForBrowserOnly() { + browserOnlyRedirect = true; + } + void answerRefreshesWith(RefreshOutcome outcome) { refreshOutcome.set(outcome); } @@ -105,7 +110,9 @@ private void respondToGrant(HttpExchange exchange, Map form) thr private void respondToCodeExchange(HttpExchange exchange, Map form) throws IOException { RefreshOutcome failure = nextCodeExchangeFailure.getAndSet(null); - if (failure == null) { + if (browserOnlyRedirect && exchange.getRequestHeaders().getFirst("Origin") == null) { + respondError(exchange, BAD_REQUEST, "invalid_request"); + } else if (failure == null) { respondWithTokens(exchange, redeemCode(form)); } else { respondWith(exchange, failure); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/SsoMcpSignInChecksIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/SsoMcpSignInChecksIT.java index f2594d30904f..5abc39c80d80 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/SsoMcpSignInChecksIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/SsoMcpSignInChecksIT.java @@ -8,29 +8,38 @@ import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.api.parallel.Isolated; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.openmetadata.it.sso.MockHttp; +import org.openmetadata.it.sso.MockResponseGate; import org.openmetadata.it.sso.browser.SsoBrowser; import org.openmetadata.it.sso.browser.SsoNavigation; import org.openmetadata.it.sso.config.SecurityConfigSwap; import org.openmetadata.it.sso.config.SsoConfigs; import org.openmetadata.it.sso.config.SsoServer; +import org.openmetadata.it.sso.oidc.IdTokenDefect; import org.openmetadata.it.sso.oidc.MockOidcIdentity; import org.openmetadata.it.sso.oidc.MockOidcProvider; import org.openmetadata.it.sso.oidc.OidcProviderProfile; import org.openmetadata.it.util.OssTestServer; import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.configuration.MCPConfiguration; import org.openmetadata.schema.api.teams.CreateUser; import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.fluent.Users; +import org.openmetadata.service.security.auth.SecurityConfigurationManager; /** * What a real sign-in to {@code /mcp} must hold beyond the happy path: each identity provider's @@ -241,8 +250,8 @@ void gapResourceParameterIsNotChecked(TestNamespace ns) throws Exception { @Test void publicOidcClientSignsInAndCallsATool(TestNamespace ns) throws Throwable { try (MockOidcProvider publicProvider = MockOidcProvider.startPublicClient()) { - securityConfig.withVariant( - config -> SsoConfigs.publicOidc(config, publicProvider), + withPublicProvider( + publicProvider, () -> { User user = createUser(new CreateUser(), ns.shortPrefix("public")); try { @@ -253,7 +262,7 @@ void publicOidcClientSignsInAndCallsATool(TestNamespace ns) throws Throwable { assertThat(publicProvider.tokenRequests()).hasSize(1); var authorization = publicProvider.authorizeRequests().getFirst(); var exchange = publicProvider.tokenRequests().getFirst(); - String callback = SsoServer.url(SsoServer.CALLBACK_PATH); + String callback = SsoServer.url("/mcp/callback"); assertThat(authorization.parameter("state")).isNotBlank(); assertThat(authorization.parameter("nonce")).isNotBlank(); assertThat(exchange.parameter("code_verifier")).isNotBlank(); @@ -275,6 +284,121 @@ void publicOidcClientSignsInAndCallsATool(TestNamespace ns) throws Throwable { } } + @Test + void browserOnlyProviderRegistrationStopsBeforeConsent(TestNamespace ns) throws Throwable { + try (MockOidcProvider publicProvider = MockOidcProvider.startPublicClient()) { + publicProvider.registerRedirectForBrowserOnly(); + withPublicProvider( + publicProvider, + () -> { + publicProvider.signIn( + MockOidcIdentity.forEmail(ns.shortPrefix("browser") + EMAIL_DOMAIN)); + JsonNode server = discoverAuthorizationServer(); + Authorization authorization = + authorizationFor(CLIENT, server, register(CLIENT, server)); + + SsoNavigation navigation = navigateUntilTheClient(server, authorization); + + assertThat(publicProvider.tokenRequests()).hasSize(1); + assertThat(navigation.last().status()).isEqualTo(502); + assertThat(navigation.last().body()) + .contains("server-side code exchange") + .doesNotContain("consent_token"); + assertThat(navigation.pendingUrl()).isNull(); + }); + } + } + + @Test + void unexpectedPublicProviderIssuerLeavesTheUserSignedOut(TestNamespace ns) throws Throwable { + try (MockOidcProvider publicProvider = MockOidcProvider.startPublicClient()) { + withPublicProvider( + publicProvider, + () -> { + User user = createUser(new CreateUser(), ns.shortPrefix("issuer")); + try { + publicProvider.signIn(MockOidcIdentity.forEmail(user.getEmail())); + publicProvider.defectNextIdToken(IdTokenDefect.WRONG_ISSUER); + JsonNode server = discoverAuthorizationServer(); + Authorization authorization = + authorizationFor(CLIENT, server, register(CLIENT, server)); + SsoBrowser browser = new SsoBrowser(); + SsoNavigation navigation = + browser.navigate( + authorizeUrl(server, authorization), + next -> next.toString().startsWith(CLIENT.redirectUri())); + assertThat(publicProvider.tokenRequests()).hasSize(1); + assertThat(navigation.last().status()).isGreaterThanOrEqualTo(400); + assertThat(navigation.last().body()).doesNotContain("consent_token"); + assertThat(Users.get(user.getId().toString(), "lastLoginTime").getLastLoginTime()) + .isNull(); + assertThat(browser.get(SsoServer.url(SsoServer.LOGGED_IN_USER_PATH)).statusCode()) + .isEqualTo(401); + } finally { + hardDelete(user); + } + }); + } + } + + @Test + void publicCallbackUsesItsProvidersKeysDuringConfigurationReload(TestNamespace ns) + throws Throwable { + try (MockOidcProvider publicProvider = MockOidcProvider.startPublicClient()) { + withPublicProvider( + publicProvider, + () -> { + User user = createUser(new CreateUser(), ns.shortPrefix("reload")); + try { + publicProvider.signIn(MockOidcIdentity.forEmail(user.getEmail())); + JsonNode server = discoverAuthorizationServer(); + Authorization authorization = + authorizationFor(CLIENT, server, register(CLIENT, server)); + MockResponseGate exchange = publicProvider.holdNextTokenResponse(); + CompletableFuture login = + CompletableFuture.supplyAsync( + () -> navigateUntilTheClient(server, authorization)); + try { + assertThat(exchange.awaitArrival(TIMEOUT)) + .as("public callback reached its provider") + .isTrue(); + securityConfig.restoreBaseline(); + } finally { + exchange.release(); + } + SsoNavigation result = login.get(TIMEOUT.toSeconds(), TimeUnit.SECONDS); + assertThat(result.last().status()).isEqualTo(200); + assertThat(result.last().body()).contains("consent_token"); + assertThat(publicProvider.jwksRequests()).isNotEmpty(); + } finally { + hardDelete(user); + } + }); + } + } + + private static void withPublicProvider(MockOidcProvider provider, Executable check) + throws Throwable { + securityConfig.withVariant( + config -> SsoConfigs.publicOidc(config, provider), + () -> { + // The embedded server listens on an ephemeral port. Advertise that public MCP base to the + // provider. + final MCPConfiguration original = SecurityConfigurationManager.getCurrentMcpConfig(); + final MCPConfiguration local = + original == null + ? new MCPConfiguration() + : JsonUtils.deepCopy(original, MCPConfiguration.class); + final SecurityConfigurationManager manager = SecurityConfigurationManager.getInstance(); + try { + manager.setCurrentMcpConfig(local.withBaseUrl(SsoServer.root())); + check.execute(); + } finally { + manager.setCurrentMcpConfig(original); + } + }); + } + private User signedInUser(TestNamespace ns) { User user = createUser(new CreateUser(), ns.shortPrefix("mcp")); provider.signIn(MockOidcIdentity.forEmail(user.getEmail())); diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/handlers/McpCallbackServlet.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/handlers/McpCallbackServlet.java index 06516022c5f8..b02dd577de46 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/handlers/McpCallbackServlet.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/handlers/McpCallbackServlet.java @@ -1,7 +1,5 @@ package org.openmetadata.mcp.server.auth.handlers; -import static org.openmetadata.service.security.AuthenticationCodeFlowHandler.OIDC_CREDENTIAL_PROFILE; - import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.oauth2.sdk.id.State; import com.nimbusds.oauth2.sdk.pkce.CodeVerifier; @@ -33,12 +31,12 @@ import org.openmetadata.service.jdbi3.SystemRepository; import org.openmetadata.service.jdbi3.oauth.OAuthRecords.McpPendingAuthRequest; import org.openmetadata.service.security.AuthenticationCodeFlowHandler; +import org.openmetadata.service.security.AuthenticationCodeFlowHandler.McpTokenVerification; import org.openmetadata.service.security.OidcIdentityResolver.ResolvedOidcIdentity; import org.openmetadata.service.security.SignInFailure; import org.openmetadata.service.security.auth.SecurityConfigurationManager; import org.openmetadata.service.util.UserUtil; import org.pac4j.oidc.client.OidcClient; -import org.pac4j.oidc.credentials.OidcCredentials; /** * Unified MCP callback servlet that handles SSO provider callbacks for MCP OAuth flow. @@ -78,8 +76,10 @@ public class McpCallbackServlet extends HttpServlet { private final UserSSOOAuthProvider userSSOProvider; private final McpPendingAuthRequestRepository pendingAuthRepository; - private volatile IdTokenValidator idTokenValidator; - private volatile AuthenticationCodeFlowHandler validatorBuiltFrom; + + private record ValidatorBinding(McpTokenVerification settings, IdTokenValidator validator) {} + + private ValidatorBinding validatorBinding; public McpCallbackServlet(UserSSOOAuthProvider userSSOProvider) { this.userSSOProvider = userSSOProvider; @@ -129,57 +129,12 @@ private String resolveBaseUrl() { return "http://localhost:8585"; } - private IdTokenValidator getIdTokenValidator(AuthenticationCodeFlowHandler ssoHandler) { - if (idTokenValidator != null && validatorBuiltFrom == ssoHandler) { - return idTokenValidator; - } - synchronized (this) { - if (idTokenValidator == null || validatorBuiltFrom != ssoHandler) { - idTokenValidator = createIdTokenValidator(ssoHandler); - validatorBuiltFrom = ssoHandler; - } - return idTokenValidator; + synchronized IdTokenValidator getIdTokenValidator(AuthenticationCodeFlowHandler handler) { + final McpTokenVerification settings = handler.getMcpTokenVerification(); + if (validatorBinding == null || validatorBinding.settings() != settings) { + validatorBinding = new ValidatorBinding(settings, new IdTokenValidator(settings)); } - } - - private IdTokenValidator createIdTokenValidator(AuthenticationCodeFlowHandler ssoHandler) { - var authConfig = SecurityConfigurationManager.getCurrentAuthConfig(); - if (authConfig == null) { - throw new IllegalStateException( - "Authentication configuration not initialized. Cannot validate ID tokens."); - } - - String expectedIssuer; - try { - // pac4j 6 removed getProviderMetadata(); metadata now loads lazily via the resolver, which - // must be initialized first because OM builds the OidcClient without calling client.init(). - ssoHandler.getClient().getConfiguration().ensuresMetadataResolverInitialized(); - expectedIssuer = - ssoHandler - .getClient() - .getConfiguration() - .getOpMetadataResolver() - .load() - .getIssuer() - .getValue(); - } catch (Exception e) { - expectedIssuer = authConfig.getAuthority(); - LOG.warn( - "Could not extract issuer from OIDC provider metadata, using default: {}", - expectedIssuer, - e); - } - - String expectedAudience = null; - try { - expectedAudience = ssoHandler.getClient().getConfiguration().getClientId(); - LOG.debug("ID token audience validation enabled for client ID: {}", expectedAudience); - } catch (Exception e) { - LOG.warn( - "Could not extract SSO client ID for audience validation, skipping: {}", e.getMessage()); - } - - return new IdTokenValidator(authConfig.getPublicKeyUrls(), expectedIssuer, expectedAudience); + return validatorBinding.validator(); } @Override @@ -290,7 +245,11 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) BufferedServletResponseWrapper callbackResponse = new BufferedServletResponseWrapper(response); - ssoHandler.handleCallback(request, callbackResponse); + final JWTClaimsSet claimsSet = + ssoHandler.handleMcpCallback( + request, + callbackResponse, + token -> getIdTokenValidator(ssoHandler).validateAndDecode(token)); if (request.getAttribute(AuthenticationCodeFlowHandler.SIGN_IN_FAILURE_ATTRIBUTE) == SignInFailure.ACCOUNT_NOT_ALLOWED) { @@ -299,6 +258,16 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) return; } + if (ssoHandler.isPublicMcpClient() + && request.getAttribute(AuthenticationCodeFlowHandler.SIGN_IN_FAILURE_ATTRIBUTE) + == SignInFailure.TOKEN_EXCHANGE_FAILED) { + response.sendError( + HttpServletResponse.SC_BAD_GATEWAY, + "The identity provider could not complete the server-side code exchange. " + + "Ask your administrator to check the public client registration for /mcp/callback."); + return; + } + if (callbackResponse.getStatusCode() >= HttpServletResponse.SC_BAD_REQUEST) { String errorBody = callbackResponse.getCapturedBody(); LOG.error( @@ -312,26 +281,8 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) + errorBody); } - OidcCredentials credentials = (OidcCredentials) request.getAttribute(OIDC_CREDENTIAL_PROFILE); - if (credentials == null || credentials.getIdToken() == null) { - throw new IllegalStateException("No OIDC credentials found on request after SSO callback"); - } - - // pac4j 6 stores the id token as a serialized String; use it directly for validation. - String idTokenString = credentials.getIdToken(); - - JWTClaimsSet claimsSet; - try { - claimsSet = getIdTokenValidator(ssoHandler).validateAndDecode(idTokenString); - LOG.debug("ID token signature validated successfully in standard SSO flow"); - } catch (IdTokenValidator.IdTokenValidationException e) { - LOG.error( - "SECURITY ALERT: ID token validation failed in standard SSO flow. Reason: {}. IP: {}", - e.getMessage(), - request.getRemoteAddr()); - throw new IllegalStateException( - "ID token validation failed: " + e.getMessage() + ". Please restart authentication.", - e); + if (claimsSet == null) { + throw new IllegalStateException("No verified MCP identity after SSO callback"); } Map claims = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/provider/UserSSOOAuthProvider.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/provider/UserSSOOAuthProvider.java index 35db51d43068..7dd330a21209 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/provider/UserSSOOAuthProvider.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/provider/UserSSOOAuthProvider.java @@ -351,10 +351,8 @@ private CompletableFuture handleSSOAuthorization( LOG.debug("Created pending auth request: {}", authRequestId); - // Use serverUrl + "/mcp/callback" as the redirectUri parameter for MCP flow detection. - // AuthenticationCodeFlowHandler.handleLogin() matches this against expectedMcpCallback - // to detect MCP flow, then uses the SSO-registered callback URL for the actual redirect_uri - // sent to the SSO provider. After auth, AuthCallbackServlet forwards to /mcp/callback. + // Public OIDC returns directly to the MCP callback. Confidential OIDC can share the + // registered web callback, which forwards the pending MCP state to this same servlet. String mcpCallbackUrl = ssoHandler.getMcpCallbackUrl(); LOG.info("Starting SSO redirect for MCP OAuth (MCP callback: {})", mcpCallbackUrl); diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/validators/IdTokenValidator.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/validators/IdTokenValidator.java index d32340c317f4..9e6dba9b7a99 100644 --- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/validators/IdTokenValidator.java +++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/server/auth/validators/IdTokenValidator.java @@ -15,7 +15,6 @@ import com.auth0.jwk.Jwk; import com.auth0.jwk.JwkException; -import com.auth0.jwk.JwkProvider; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTDecodeException; @@ -24,6 +23,7 @@ import com.nimbusds.jwt.JWTParser; import java.net.MalformedURLException; import java.net.URL; +import java.security.GeneralSecurityException; import java.security.interfaces.RSAPublicKey; import java.time.Duration; import java.util.Calendar; @@ -31,6 +31,8 @@ import java.util.TimeZone; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; +import org.openmetadata.schema.services.connections.metadata.AuthProvider; +import org.openmetadata.service.security.AuthenticationCodeFlowHandler.McpTokenVerification; import org.openmetadata.service.security.IdentityProviderKeys; import org.openmetadata.service.security.ProviderTokenValidator; @@ -75,7 +77,8 @@ public class IdTokenValidator { private static final Duration KEY_LIFETIME = Duration.ofHours(6); - private final JwkProvider jwkProvider; + private final IdentityProviderKeys jwkProvider; + private final AuthProvider provider; private final String expectedIssuer; private final String expectedAudience; // Client ID private final String tokenValidationAlgorithm; @@ -105,13 +108,44 @@ public IdTokenValidator( String expectedIssuer, String expectedAudience, String tokenValidationAlgorithm) { - if (publicKeyUrls == null || publicKeyUrls.isEmpty()) { - throw new IllegalArgumentException("publicKeyUrls cannot be null or empty"); - } + this( + providerKeys(publicKeyUrls, false), + expectedIssuer, + expectedAudience, + tokenValidationAlgorithm, + null); + } + + public IdTokenValidator(McpTokenVerification settings) { + this( + providerKeys(settings.keySetUrls(), settings.publicClient()), + settings.issuer(), + settings.audience(), + "RS256", + settings.provider()); + } + + private IdTokenValidator( + IdentityProviderKeys jwkProvider, + String expectedIssuer, + String expectedAudience, + String tokenValidationAlgorithm, + AuthProvider provider) { if (expectedIssuer == null || expectedIssuer.trim().isEmpty()) { throw new IllegalArgumentException("expectedIssuer cannot be null or empty"); } + this.jwkProvider = jwkProvider; + this.expectedIssuer = expectedIssuer; + this.expectedAudience = expectedAudience; + this.tokenValidationAlgorithm = tokenValidationAlgorithm; + this.provider = provider; + } + private static IdentityProviderKeys providerKeys( + List publicKeyUrls, boolean publicMcpClient) { + if (publicKeyUrls == null || publicKeyUrls.isEmpty()) { + throw new IllegalArgumentException("publicKeyUrls cannot be null or empty"); + } // Convert URLs and initialize multi-URL JWKS provider with caching List urls = publicKeyUrls.stream() @@ -126,16 +160,9 @@ public IdTokenValidator( }) .collect(Collectors.toList()); - this.jwkProvider = IdentityProviderKeys.forUrls(urls, KEY_LIFETIME); - this.expectedIssuer = expectedIssuer; - this.expectedAudience = expectedAudience; - this.tokenValidationAlgorithm = tokenValidationAlgorithm; - - LOG.info( - "Initialized IdTokenValidator with issuer: {}, audience: {}, algorithm: {}", - expectedIssuer, - expectedAudience != null ? expectedAudience : "not validated", - tokenValidationAlgorithm); + return publicMcpClient + ? IdentityProviderKeys.forPublicMcp(urls, KEY_LIFETIME) + : IdentityProviderKeys.forUrls(urls, KEY_LIFETIME); } /** @@ -190,8 +217,7 @@ public JWTClaimsSet validateAndDecode(String idTokenString) throws IdTokenValida throw new IdTokenValidationException("ID token is missing required 'iss' (issuer) claim"); } - if (!expectedIssuer.equals(issuer) - && !ProviderTokenValidator.isGoogleSchemelessIssuer(expectedIssuer, issuer)) { + if (!ProviderTokenValidator.isIssuedBy(expectedIssuer, jwt)) { LOG.warn( "ID token issuer mismatch. Expected: {}, Got: {}. This may indicate a token from a different OIDC provider.", expectedIssuer, @@ -230,7 +256,12 @@ public JWTClaimsSet validateAndDecode(String idTokenString) throws IdTokenValida try { // Fetch public key from JWKS endpoint (with caching) - Jwk jwk = jwkProvider.get(keyId); + final var publishedKey = jwkProvider.getWithSource(keyId); + final Jwk jwk = publishedKey.key(); + if (!ProviderTokenValidator.signingKeyAllowsIssuer( + provider, expectedIssuer, publishedKey, jwt)) { + throw new IdTokenValidationException("Signing key issuer does not match the token issuer"); + } RSAPublicKey publicKey = (RSAPublicKey) jwk.getPublicKey(); // Create algorithm for verification @@ -306,7 +337,7 @@ private Algorithm getAlgorithm(String algorithm, RSAPublicKey publicKey) { *
  • JWKS endpoint unreachable * */ - public static class IdTokenValidationException extends Exception { + public static class IdTokenValidationException extends GeneralSecurityException { public IdTokenValidationException(String message) { super(message); } diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/handlers/McpCallbackServletTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/handlers/McpCallbackServletTest.java index 962ba64cef25..55b475f997d9 100644 --- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/handlers/McpCallbackServletTest.java +++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/handlers/McpCallbackServletTest.java @@ -4,13 +4,14 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -24,10 +25,8 @@ import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Constructor; -import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; -import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; @@ -39,6 +38,7 @@ import org.openmetadata.schema.api.security.AuthorizerConfiguration; import org.openmetadata.service.jdbi3.oauth.OAuthRecords.McpPendingAuthRequest; import org.openmetadata.service.security.AuthenticationCodeFlowHandler; +import org.openmetadata.service.security.AuthenticationCodeFlowHandler.McpIdTokenVerifier; import org.openmetadata.service.security.OidcIdentityResolver; import org.openmetadata.service.security.SignInFailure; import org.openmetadata.service.util.UserUtil; @@ -85,7 +85,7 @@ void doGet_idTokenWithoutState_returns400AndIssuesNoCode() throws Exception { verify(response) .sendError(HttpServletResponse.SC_BAD_REQUEST, McpCallbackServlet.ERR_MISSING_STATE); verify(provider, never()).handleSSOCallbackWithDbState(any(), any(), any(), any(), any()); - verify(holder[0], never()).handleCallback(any(), any()); + verify(holder[0], never()).handleMcpCallback(any(), any(), any()); } // ── doGet: IdP error callback is relayed to the MCP client ──────────────── @@ -156,7 +156,7 @@ void doGet_idpErrorCallback_loginRequired_relaysErrorToMcpClient() throws Except verify(provider) .handleSSOErrorCallback( any(), eq("auth-req-1"), eq("login_required"), eq("The user is not logged in.")); - verify(holder[0], never()).handleCallback(any(), any()); + verify(holder[0], never()).handleMcpCallback(any(), any(), any()); } @Test @@ -177,7 +177,7 @@ void doGet_idpErrorCallback_accessDenied_relaysErrorToMcpClient() throws Excepti verify(provider) .handleSSOErrorCallback( any(), eq("auth-req-1"), eq("access_denied"), eq("The user denied the request.")); - verify(holder[0], never()).handleCallback(any(), any()); + verify(holder[0], never()).handleMcpCallback(any(), any(), any()); } @Test @@ -194,7 +194,7 @@ void doGet_idpErrorCallback_nullErrorDescription_passesNull() throws Exception { servlet.doGet(request, response); verify(provider).handleSSOErrorCallback(any(), eq("auth-req-1"), eq("server_error"), eq(null)); - verify(holder[0], never()).handleCallback(any(), any()); + verify(holder[0], never()).handleMcpCallback(any(), any(), any()); } @Test @@ -254,13 +254,12 @@ void doGet_callbackWithoutLogin_ignoresCredentialsLeftInSession() throws Excepti return null; }) .when(ssoHandler) - .handleCallback(any(), any()); - McpCallbackServlet servlet = makeServletWithHandler(provider, pendingRepo, ssoHandler); + .handleMcpCallback(any(), any(), any()); + McpCallbackServlet servlet = spy(makeServletWithHandler(provider, pendingRepo, ssoHandler)); IdTokenValidator validator = mock(IdTokenValidator.class); when(validator.validateAndDecode("earlier.id.token")) .thenReturn(new JWTClaimsSet.Builder().claim("email", "alice@example.com").build()); - setField(servlet, "idTokenValidator", validator); - setField(servlet, "validatorBuiltFrom", ssoHandler); + doReturn(validator).when(servlet).getIdTokenValidator(ssoHandler); OidcCredentials earlierLogin = mock(OidcCredentials.class); when(earlierLogin.getIdToken()).thenReturn("earlier.id.token"); @@ -273,7 +272,7 @@ void doGet_callbackWithoutLogin_ignoresCredentialsLeftInSession() throws Excepti servlet.doGet(request, response); - verify(ssoHandler).handleCallback(eq(request), any()); + verify(ssoHandler).handleMcpCallback(eq(request), any(), any()); verify(response).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); verify(provider, never()).handleSSOCallbackWithDbState(any(), any(), any(), any(), any()); } @@ -293,7 +292,7 @@ void doGet_accountNotAllowed_showsAccessDeniedNotAnInternalError() throws Except return null; }) .when(ssoHandler) - .handleCallback(any(), any()); + .handleMcpCallback(any(), any(), any()); McpCallbackServlet servlet = makeServletWithHandler(provider, pendingRepo, ssoHandler); HttpServletRequest request = mockCallbackRequest("pac4j-state-abc", null, null); when(request.getSession(true)).thenReturn(mock(HttpSession.class)); @@ -356,37 +355,26 @@ private static HttpServletRequest completeLogin( when(pendingRepo.findByPac4jState("pac4j-state-abc")).thenReturn(samplePendingRequest()); HttpServletRequest request = mockCallbackRequest("pac4j-state-abc", null, null); when(request.getSession(true)).thenReturn(mock(HttpSession.class)); - Map attributes = new HashMap<>(); - doAnswer(call -> attributes.put(call.getArgument(0), call.getArgument(1))) - .when(request) - .setAttribute(anyString(), any()); - when(request.getAttribute(anyString())) - .thenAnswer(call -> attributes.get(call.getArgument(0))); - OidcCredentials thisLogin = mock(OidcCredentials.class); - when(thisLogin.getIdToken()).thenReturn("this.id.token"); AuthenticationCodeFlowHandler ssoHandler = mock(AuthenticationCodeFlowHandler.class, RETURNS_DEEP_STUBS); doAnswer( call -> { - call.getArgument(0) - .setAttribute(AuthenticationCodeFlowHandler.OIDC_CREDENTIAL_PROFILE, thisLogin); call.getArgument(1).sendRedirect("https://om.test/mcp/callback"); - return null; + return call.getArgument(2).verify("this.id.token"); }) .when(ssoHandler) - .handleCallback(any(), any()); + .handleMcpCallback(any(), any(), any()); when(ssoHandler.resolveOidcIdentity(any())) .thenAnswer( call -> new OidcIdentityResolver( authConfig, new AuthorizerConfiguration(), Map.of(), List.of("email"), "") .resolve(call.getArgument(0))); - McpCallbackServlet servlet = makeServletWithHandler(provider, pendingRepo, ssoHandler); + McpCallbackServlet servlet = spy(makeServletWithHandler(provider, pendingRepo, ssoHandler)); IdTokenValidator validator = mock(IdTokenValidator.class); when(validator.validateAndDecode("this.id.token")) .thenReturn(new JWTClaimsSet.Builder().claim("email", email).build()); - setField(servlet, "idTokenValidator", validator); - setField(servlet, "validatorBuiltFrom", ssoHandler); + doReturn(validator).when(servlet).getIdTokenValidator(ssoHandler); servlet.doGet(request, mock(HttpServletResponse.class)); return request; @@ -404,12 +392,6 @@ protected AuthenticationCodeFlowHandler resolveSsoHandler() { }; } - private static void setField(Object target, String name, Object value) throws Exception { - Field field = McpCallbackServlet.class.getDeclaredField(name); - field.setAccessible(true); - field.set(target, value); - } - @Test void doGet_noErrorParam_doesNotInvokeErrorRelay() throws Exception { // Regression guard: a success callback (no error param) must never trigger the error relay. diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/validators/IdTokenValidatorTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/validators/IdTokenValidatorTest.java index 847c931b6423..87463b67614c 100644 --- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/validators/IdTokenValidatorTest.java +++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/validators/IdTokenValidatorTest.java @@ -25,7 +25,12 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; import org.openmetadata.mcp.server.auth.validators.IdTokenValidator.IdTokenValidationException; +import org.openmetadata.schema.services.connections.metadata.AuthProvider; +import org.openmetadata.service.security.AuthenticationCodeFlowHandler.McpTokenVerification; /** * Unit tests for IdTokenValidator - JWKS-based ID token signature verification. @@ -35,6 +40,13 @@ */ public class IdTokenValidatorTest { + private static final String TENANT_ID = "8f6bd38f-4e6a-4f8e-9c5b-0d2a5e1c7b11"; + private static final String TENANT_ISSUER = + "https://login.microsoftonline.com/" + TENANT_ID + "/v2.0"; + private static final String ENTRA_TEMPLATE = "https://login.microsoftonline.com/{tenantid}/v2.0"; + private static final String ENCODED_ENTRA_TEMPLATE = + "https://login.microsoftonline.com/%7Btenantid%7D/v2.0"; + private volatile String signingKeyIssuer; private final AtomicInteger jwksRequests = new AtomicInteger(); private HttpServer jwksServer; private String jwksUrl; @@ -63,19 +75,25 @@ void setUp() throws Exception { private void startJwksServer() throws IOException { jwksServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); - final byte[] body = createJwksResponse(publicKey, keyId).getBytes(StandardCharsets.UTF_8); + publishKeySet("/jwks", keyId); + jwksServer.start(); + jwksUrl = "http://127.0.0.1:" + jwksServer.getAddress().getPort() + "/jwks"; + } + + private String publishKeySet(String path, String publishedKeyId) { jwksServer.createContext( - "/jwks", + path, exchange -> { jwksRequests.incrementAndGet(); + final byte[] body = + createJwksResponse(publicKey, publishedKeyId).getBytes(StandardCharsets.UTF_8); try (exchange) { exchange.getResponseHeaders().set("Content-Type", "application/json"); exchange.sendResponseHeaders(200, body.length); exchange.getResponseBody().write(body); } }); - jwksServer.start(); - jwksUrl = "http://127.0.0.1:" + jwksServer.getAddress().getPort() + "/jwks"; + return "http://localhost:" + jwksServer.getAddress().getPort() + path; } @AfterEach @@ -124,6 +142,141 @@ void googleIssuerWithoutASchemeIsRefusedForAnotherProvider() { .hasMessageContaining("issuer mismatch"); } + @ParameterizedTest + @ValueSource(strings = {ENTRA_TEMPLATE, TENANT_ISSUER}) + void acceptsSignedTokenForTenantAndSigningKeyIssuer(String keyIssuer) throws Exception { + signingKeyIssuer = keyIssuer; + final IdTokenValidator entra = + new IdTokenValidator(List.of(jwksUrl), ENCODED_ENTRA_TEMPLATE, expectedAudience); + + assertThat(entra.validateAndDecode(tenantToken(TENANT_ISSUER, TENANT_ID)).getIssuer()) + .isEqualTo(TENANT_ISSUER); + } + + @ParameterizedTest + @NullSource + @ValueSource( + strings = {"https://login.microsoftonline.com/00000000-0000-0000-0000-000000000001/v2.0"}) + void refusesSigningKeyOutsideItsIssuerScope(String keyIssuer) { + signingKeyIssuer = keyIssuer; + final IdTokenValidator entra = + new IdTokenValidator(List.of(jwksUrl), ENCODED_ENTRA_TEMPLATE, expectedAudience); + + assertThatThrownBy(() -> entra.validateAndDecode(tenantToken(TENANT_ISSUER, TENANT_ID))) + .isInstanceOf(IdTokenValidationException.class) + .hasMessageContaining("Signing key issuer"); + } + + @ParameterizedTest + @NullSource + @ValueSource(strings = {"other", "00000000-0000-0000-0000-000000000001"}) + void refusesTokenWhenTenantCannotResolveItsIssuer(String tenant) { + signingKeyIssuer = ENTRA_TEMPLATE; + final IdTokenValidator entra = + new IdTokenValidator(List.of(jwksUrl), ENCODED_ENTRA_TEMPLATE, expectedAudience); + + assertThatThrownBy(() -> entra.validateAndDecode(tenantToken(TENANT_ISSUER, tenant))) + .isInstanceOf(IdTokenValidationException.class) + .hasMessageContaining("issuer mismatch"); + } + + @Test + void refusesNonGuidTenantEvenWhenTheIssuerMatchesTheClaim() { + signingKeyIssuer = ENTRA_TEMPLATE; + final IdTokenValidator entra = + new IdTokenValidator(List.of(jwksUrl), ENCODED_ENTRA_TEMPLATE, expectedAudience); + final String token = tenantToken("https://login.microsoftonline.com/common/v2.0", "common"); + + assertThatThrownBy(() -> entra.validateAndDecode(token)) + .isInstanceOf(IdTokenValidationException.class) + .hasMessageContaining("issuer mismatch"); + } + + @ParameterizedTest + @ValueSource(strings = {"/common/discovery/keys", "/organizations/discovery/v2.0/keys"}) + void concreteEntraAuthorityChecksTheSetThatSuppliedTheKey(String sharedPath) throws Exception { + final String tenantKeys = publishKeySet("/" + TENANT_ID + "/discovery/v2.0/keys", "tenant-key"); + final String sharedKeys = publishKeySet(sharedPath, "shared-key"); + final IdTokenValidator entra = + new IdTokenValidator( + new McpTokenVerification( + List.of(sharedKeys, tenantKeys), + TENANT_ISSUER, + expectedAudience, + true, + AuthProvider.AZURE)); + + assertThat( + entra + .validateAndDecode(tenantToken(TENANT_ISSUER, TENANT_ID, "tenant-key")) + .getIssuer()) + .isEqualTo(TENANT_ISSUER); + assertThatThrownBy( + () -> entra.validateAndDecode(tenantToken(TENANT_ISSUER, TENANT_ID, "shared-key"))) + .isInstanceOf(IdTokenValidationException.class) + .hasMessageContaining("Signing key issuer"); + } + + @ParameterizedTest + @ValueSource(strings = {"/common/discovery/v2.0/keys", "/tenant/discovery/v2.0/keys"}) + void concreteEntraAuthorityHonorsAnExplicitKeyScope(String keySetPath) { + signingKeyIssuer = + "https://login.microsoftonline.com/00000000-0000-0000-0000-000000000001/v2.0"; + final String keys = publishKeySet(keySetPath, keyId); + final IdTokenValidator entra = + new IdTokenValidator( + new McpTokenVerification( + List.of(keys), TENANT_ISSUER, expectedAudience, true, AuthProvider.AZURE)); + + assertThatThrownBy(() -> entra.validateAndDecode(tenantToken(TENANT_ISSUER, TENANT_ID))) + .isInstanceOf(IdTokenValidationException.class) + .hasMessageContaining("Signing key issuer"); + } + + @ParameterizedTest + @ValueSource(strings = {ENTRA_TEMPLATE, TENANT_ISSUER}) + void concreteEntraAuthorityAcceptsAMatchingSharedKey(String scope) throws Exception { + signingKeyIssuer = scope; + final String shared = publishKeySet("/common/discovery/v2.0/keys", keyId); + final IdTokenValidator entra = + new IdTokenValidator( + new McpTokenVerification( + List.of(shared), TENANT_ISSUER, expectedAudience, true, AuthProvider.AZURE)); + assertThat(entra.validateAndDecode(tenantToken(TENANT_ISSUER, TENANT_ID)).getIssuer()) + .isEqualTo(TENANT_ISSUER); + } + + @Test + void customProviderCanUseItsOwnKeyAttributes() throws Exception { + signingKeyIssuer = "provider-specific key attribute"; + final String keys = publishKeySet("/common/discovery/keys", keyId); + final IdTokenValidator custom = + new IdTokenValidator( + new McpTokenVerification( + List.of(keys), expectedIssuer, expectedAudience, true, AuthProvider.CUSTOM_OIDC)); + + assertThat( + custom + .validateAndDecode( + createValidIdToken(expectedIssuer, expectedAudience, "a@example.com")) + .getIssuer()) + .isEqualTo(expectedIssuer); + } + + private String tenantToken(String issuer, String tenant) { + return tenantToken(issuer, tenant, keyId); + } + + private String tenantToken(String issuer, String tenant, String signingKeyId) { + return JWT.create() + .withIssuer(issuer) + .withAudience(expectedAudience) + .withClaim("tid", tenant) + .withExpiresAt(new Date(System.currentTimeMillis() + 3600000)) + .withKeyId(signingKeyId) + .sign(Algorithm.RSA256(null, privateKey)); + } + @Test void testValidateAndDecode_WrongIssuer() { String wrongIssuerToken = @@ -311,10 +464,10 @@ private String createJwksResponse(RSAPublicKey publicKey, String kid) { "use": "sig", "alg": "RS256", "n": "%s", - "e": "%s" + "e": "%s"%s }] } """, - kid, n, e); + kid, n, e, signingKeyIssuer == null ? "" : ", \"issuer\": \"" + signingKeyIssuer + "\""); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthenticationCodeFlowHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthenticationCodeFlowHandler.java index 573e3edb39a8..686a21706f44 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthenticationCodeFlowHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/AuthenticationCodeFlowHandler.java @@ -14,7 +14,6 @@ import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.proc.BadJOSEException; -import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.JWTParser; import com.nimbusds.jwt.proc.BadJWTException; @@ -59,6 +58,7 @@ import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.PrivateKey; import java.time.Instant; @@ -90,6 +90,7 @@ import org.openmetadata.schema.entity.teams.Role; import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.security.client.OidcClientConfig; +import org.openmetadata.schema.services.connections.metadata.AuthProvider; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; @@ -149,7 +150,7 @@ public class AuthenticationCodeFlowHandler implements AuthServeletHandler { private static final String FORCED_LOGIN_PROMPT = "login"; private static final String FORCED_REAUTHENTICATION_MAX_AGE = "0"; - private static final String MCP_CALLBACK_PATH = "/mcp/callback"; + static final String MCP_CALLBACK_PATH = "/mcp/callback"; private static final String AUTH_CALLBACK_PATH = "/auth/callback"; private static final String CALLBACK_SERVLET_PATH = "/callback"; private static final String SIGNIN_PATH = "/signin"; @@ -168,7 +169,7 @@ public class AuthenticationCodeFlowHandler implements AuthServeletHandler { private static volatile AuthenticationCodeFlowHandler latestInstance; - private final boolean publicMcpClient; + @Getter private final boolean publicMcpClient; private OidcClient client; private List claimsOrder; private Map claimsMapping; @@ -178,6 +179,21 @@ public class AuthenticationCodeFlowHandler implements AuthServeletHandler { private String principalDomain; private String maxAge; private String promptType; + + /** Verification inputs from the same configuration that performs this provider code exchange. */ + public record McpTokenVerification( + List keySetUrls, + String issuer, + String audience, + boolean publicClient, + AuthProvider provider) { + public McpTokenVerification { + keySetUrls = List.copyOf(listOrEmpty(keySetUrls)); + CommonHelper.assertNotBlank("OIDC client ID", audience); + } + } + + @Getter private volatile McpTokenVerification mcpTokenVerification; @Getter private String providerIssuer; @Getter private URL providerKeySetUrl; private AuthenticationConfiguration authenticationConfiguration; @@ -286,7 +302,9 @@ public synchronized void updateConfiguration( private void initializeFields() { this.client = - buildOidcClient(authenticationConfiguration.getOidcConfiguration(), publicMcpClient); + buildOidcClient( + authenticationConfiguration.getOidcConfiguration(), + publicMcpClient ? authenticationConfiguration.getProvider() : null); client.setCallbackUrl(authenticationConfiguration.getOidcConfiguration().getCallbackUrl()); // Create the OIDC metadata resolver during single-threaded startup so concurrent logins never // race to lazily initialize it. pac4j 6 normally does this in client.init(), but OM does not @@ -315,6 +333,13 @@ private void initializeFields() { this.providerIssuer = providerMetadata.getIssuer() == null ? null : providerMetadata.getIssuer().getValue(); this.providerKeySetUrl = keySetUrlOf(providerMetadata); + this.mcpTokenVerification = + new McpTokenVerification( + authenticationConfiguration.getPublicKeyUrls(), + providerIssuer, + client.getConfiguration().getClientId(), + publicMcpClient, + authenticationConfiguration.getProvider()); } private static URL keySetUrlOf(OIDCProviderMetadata providerMetadata) { @@ -358,15 +383,17 @@ static String normalizePrompt(String configuredPrompt) { } static OidcClient buildOidcClient(OidcClientConfig clientConfig) { - return buildOidcClient(clientConfig, false); + return buildOidcClient(clientConfig, null); } private static OidcClient buildOidcClient( - OidcClientConfig clientConfig, boolean publicMcpClient) { + OidcClientConfig clientConfig, AuthProvider publicProvider) { + final boolean publicMcpClient = publicProvider != null; String id = clientConfig.getId(); String secret = clientConfig.getSecret(); if (CommonHelper.isNotBlank(id) && (publicMcpClient || CommonHelper.isNotBlank(secret))) { - OidcConfiguration configuration = new OidcConfiguration(); + OidcConfiguration configuration = + publicMcpClient ? new PublicOidcConfiguration(publicProvider) : new OidcConfiguration(); configuration.setClientId(id); configuration.setResponseMode("query"); @@ -601,8 +628,27 @@ private void persistMcpPendingState(HttpServletRequest req, PendingLoginContext } } - // Callback + @FunctionalInterface + public interface McpIdTokenVerifier { + JWTClaimsSet verify(String rawToken) throws GeneralSecurityException; + } + + @Override public void handleCallback(HttpServletRequest req, HttpServletResponse resp) { + if (publicMcpClient) { + throw new IllegalStateException("Public MCP sign-in requires ID token verification"); + } + completeCallback(req, resp, null); + } + + public JWTClaimsSet handleMcpCallback( + HttpServletRequest req, HttpServletResponse resp, McpIdTokenVerifier verifier) { + return completeCallback(req, resp, Objects.requireNonNull(verifier)); + } + + private JWTClaimsSet completeCallback( + HttpServletRequest req, HttpServletResponse resp, McpIdTokenVerifier mcpVerifier) { + JWTClaimsSet completedClaims = null; UserSession pendingSession = null; try { Optional maybePendingSession = sessionService.getPendingSession(req, resp); @@ -612,7 +658,7 @@ public void handleCallback(HttpServletRequest req, HttpServletResponse resp) { // already cleared the stale cookie, so route the user to interactive signin instead. LOG.warn("No pending session found for callback, redirecting to signin"); resp.sendRedirect(deploymentUrl(SIGNIN_PATH)); - return; + return null; } pendingSession = maybePendingSession.get(); @@ -632,7 +678,7 @@ public void handleCallback(HttpServletRequest req, HttpServletResponse resp) { if (SILENT_AUTH_ERRORS.contains(errorCode)) { LOG.warn("Silent auth not possible (error={}), redirecting to signin", errorCode); resp.sendRedirect(deploymentUrl(SIGNIN_PATH)); - return; + return null; } throw SignInFailure.PROVIDER_REFUSED.because( "Identity provider refused the sign-in: " @@ -641,6 +687,9 @@ public void handleCallback(HttpServletRequest req, HttpServletResponse resp) { } String redirectUri = requireRedirectUriOrDefault(pendingSession.getRedirectUri()); + if (mcpVerifier != null && !isMcpRedirectUri(redirectUri)) { + throw new IllegalArgumentException("Pending sign-in is not for MCP"); + } LOG.debug("Authentication response successful"); AuthenticationSuccessResponse successResponse = (AuthenticationSuccessResponse) response; @@ -653,13 +702,15 @@ public void handleCallback(HttpServletRequest req, HttpServletResponse resp) { requireAuthorizationCode(pendingSession, credentials); redeemAuthorizationCode(pendingSession, credentials, computedCallbackUrl); - // pac4j 6 re-parses the serialized id token on every toIdToken() call; parse once and reuse. - JWT idToken = credentials.toIdToken(); - if (idToken == null) { + if (nullOrEmpty(credentials.getIdToken())) { throw SignInFailure.TOKEN_EXCHANGE_FAILED.because( "ID token not returned by OIDC provider", null); } - JWTClaimsSet idTokenClaims = idToken.getJWTClaimsSet(); + // Verify MCP identity before these claims can provision a user or activate a session. + final JWTClaimsSet idTokenClaims = + mcpVerifier == null + ? credentials.toIdToken().getJWTClaimsSet() + : mcpVerifier.verify(credentials.getIdToken()); Date expirationTime = idTokenClaims.getExpirationTime(); if (expirationTime != null && expirationTime.before(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime())) { @@ -670,14 +721,6 @@ public void handleCallback(HttpServletRequest req, HttpServletResponse resp) { validateNonceIfRequired(pendingSession, idTokenClaims); - // The MCP callback completes its own OAuth exchange off the provider-issued id_token, which - // is only available here. Hand the validated credentials over on this request, so the MCP - // callback only ever reads tokens this callback validated; a session would outlive it. - if (isMcpRedirectUri(pendingSession.getRedirectUri())) { - req.setAttribute(OIDC_CREDENTIAL_PROFILE, credentials); - LOG.debug("Stored OIDC credentials on the request for MCP callback handoff"); - } - Map claims = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); claims.putAll(idTokenClaims.getClaims()); @@ -709,6 +752,10 @@ public void handleCallback(HttpServletRequest req, HttpServletResponse resp) { // The browser presents the provider's own ID token: its claims are the ones the principal // configuration names, and its expiry is the provider's. sendRedirectWithToken(resp, redirectUri, user, credentials.getIdToken()); + if (isMcpRedirectUri(redirectUri)) { + req.setAttribute(OIDC_CREDENTIAL_PROFILE, credentials); + completedClaims = idTokenClaims; + } } catch (SignInFailedException failure) { endFailedSignIn(req, resp, pendingSession, failure); } catch (IllegalArgumentException e) { @@ -721,6 +768,7 @@ public void handleCallback(HttpServletRequest req, HttpServletResponse resp) { } catch (Exception e) { getErrorMessage(resp, e); } + return completedClaims; } /** @@ -1599,7 +1647,7 @@ private String requireRedirectUriOrDefault(String redirectUri) { * keeps {@code serverUrl}. */ private String deploymentUrl(String path) { - String callbackBaseUrl = baseUrlOf(client.getCallbackUrl()); + String callbackBaseUrl = publicMcpClient ? serverUrl : baseUrlOf(client.getCallbackUrl()); return (callbackBaseUrl == null ? serverUrl : callbackBaseUrl) + path; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/IdentityProviderKeys.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/IdentityProviderKeys.java index ed17b81dd99d..7b3b7aa37162 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/IdentityProviderKeys.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/IdentityProviderKeys.java @@ -20,7 +20,6 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; -import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; @@ -48,6 +47,9 @@ public final class IdentityProviderKeys implements JwkProvider { "JWT Token keyID doesn't match the configured keyID. This usually happens if you didn't" + " configure proper publicKeyUrls under authentication configuration."; + /** The key-set URL matters for providers whose shared keys carry issuer restrictions. */ + public record PublishedKey(Jwk key, String keySetUrl) {} + private final KeySetFetchPolicy fetchPolicy; private final Ticker ticker; private final List configuredSources; @@ -55,9 +57,9 @@ public final class IdentityProviderKeys implements JwkProvider { private final Supplier> discoveredKeySetUrls; private final Cache discoveredSources = CacheBuilder.newBuilder().maximumSize(MAX_DISCOVERED_KEY_SETS).build(); - private final Cache> downloadedSets; + private final Cache> downloadedSets; private final Cache failedDownloads; - private final LoadingCache keysById; + private final LoadingCache keysById; /** * The keys published at {@code keySetUrls}, downloaded with the default timeouts and budget, each @@ -68,6 +70,12 @@ public static IdentityProviderKeys forUrls(List keySetUrls, Duration keyLif keySetUrls, List::of, KeySetFetchPolicy.DEFAULT, keyLifetime, Ticker.systemTicker()); } + /** Each public MCP key download applies the same connection policy as provider discovery. */ + public static IdentityProviderKeys forPublicMcp(List keySetUrls, Duration keyLifetime) { + return forUrls( + keySetUrls.stream().map(PublicOidcConfiguration::checkedKeySetUrl).toList(), keyLifetime); + } + /** * {@code discoveredKeySetUrls} adds key sets known only at lookup time, such as the {@code * jwks_uri} of the provider's discovery document, to the configured {@code keySetUrls}. @@ -97,6 +105,10 @@ public static IdentityProviderKeys forUrls(List keySetUrls, Duration keyLif @Override public Jwk get(String keyId) throws JwkException { + return getWithSource(keyId).key(); + } + + public PublishedKey getWithSource(String keyId) throws JwkException { try { return keysById.get(requireKeyId(keyId)); } catch (ExecutionException | UncheckedExecutionException e) { @@ -121,7 +133,7 @@ private static JwkException asJwkException(Throwable loadFailure) { // One load per key id at a time, so the requests that arrive with a newly rotated key share it. // A resolved key is reused only briefly: how long a key lives is decided by downloadedSets. - private LoadingCache keyLookup(Ticker ticker) { + private LoadingCache keyLookup(Ticker ticker) { return CacheBuilder.newBuilder() .maximumSize(MAX_RESOLVED_KEY_IDS) .expireAfterWrite(RESOLVED_KEY_REUSE) @@ -129,7 +141,7 @@ private LoadingCache keyLookup(Ticker ticker) { .build( new CacheLoader<>() { @Override - public @NotNull Jwk load(@NotNull String keyId) throws JwkException { + public @NotNull PublishedKey load(@NotNull String keyId) throws JwkException { return loadKey(keyId); } }); @@ -137,26 +149,26 @@ private LoadingCache keyLookup(Ticker ticker) { // Bounded by the number of keys across all sets. One segment, so a set of up to the whole bound // fits: Guava divides a weight bound between its segments. - private static Cache> downloadCache( + private static Cache> downloadCache( Duration keyLifetime, Ticker ticker) { return CacheBuilder.newBuilder() .concurrencyLevel(1) .maximumWeight(MAX_CACHED_KEYS) - .weigher((String keySetUrl, Map keys) -> Math.max(1, keys.size())) + .weigher((String keySetUrl, Map keys) -> Math.max(1, keys.size())) .expireAfterWrite(keyLifetime) .ticker(ticker) .build(); } - private Jwk loadKey(String keyId) throws SigningKeyNotFoundException { + private PublishedKey loadKey(String keyId) throws SigningKeyNotFoundException { List sources = candidateSources(); - Optional cached = cachedKey(sources, keyId); + Optional cached = cachedKey(sources, keyId); return cached.isPresent() ? cached.get() : downloadedKey(sources, keyId); } // Cached sets answer only up to the first set nothing is known about: an earlier set may publish // the id too, and it must be asked before a later set's copy wins. - private Optional cachedKey(List sources, String keyId) { + private Optional cachedKey(List sources, String keyId) { return sources.stream() .map(this::knownKeys) .takeWhile(Objects::nonNull) @@ -168,15 +180,15 @@ private Optional cachedKey(List sources, String keyId) { // A set's cached download, no keys for a set marked as failed, or null when neither is known and // the set must be asked. A failed set is asked again only on a lookup of an unknown id, or once a // key lifetime has passed: asking it here would hold the request up for its timeouts. - private Map knownKeys(KeySetSource source) { - Map cached = downloadedSets.getIfPresent(source.url()); + private Map knownKeys(KeySetSource source) { + Map cached = downloadedSets.getIfPresent(source.url()); boolean isMarkedFailed = failedDownloads.getIfPresent(source.url()) != null; return cached == null && isMarkedFailed ? Map.of() : cached; } // The sets are asked in order. One whose cached download holds the id answers without a download; // any other is downloaded, because an id it lacks may be newly rotated in. - private Jwk downloadedKey(List sources, String keyId) + private PublishedKey downloadedKey(List sources, String keyId) throws SigningKeyNotFoundException { SigningKeyNotFoundException notFound = new SigningKeyNotFoundException(KEY_NOT_FOUND, null); return sources.stream() @@ -186,8 +198,9 @@ private Jwk downloadedKey(List sources, String keyId) .orElseThrow(() -> notFound); } - private Jwk keyIn(KeySetSource source, String keyId, SigningKeyNotFoundException notFound) { - Map cached = downloadedSets.getIfPresent(source.url()); + private PublishedKey keyIn( + KeySetSource source, String keyId, SigningKeyNotFoundException notFound) { + Map cached = downloadedSets.getIfPresent(source.url()); return cached != null && cached.containsKey(keyId) ? cached.get(keyId) : download(source, notFound).get(keyId); @@ -195,10 +208,11 @@ private Jwk keyIn(KeySetSource source, String keyId, SigningKeyNotFoundException // The key is read from the download itself, never back from the bounded cache. A refused or // failed download falls back to the set's cached copy, which a concurrent download may fill. - private Map download(KeySetSource source, SigningKeyNotFoundException notFound) { - Map keys; + private Map download( + KeySetSource source, SigningKeyNotFoundException notFound) { + Map keys; try { - keys = indexById(source.fetchAll()); + keys = indexById(source.url(), source.fetchAll()); downloadedSets.put(source.url(), keys); failedDownloads.invalidate(source.url()); } catch (RateLimitReachedException refused) { @@ -220,16 +234,16 @@ private void markFailedUnlessCached(KeySetSource source) { } } - private Map cachedOrNone(KeySetSource source) { + private Map cachedOrNone(KeySetSource source) { return Objects.requireNonNullElse(downloadedSets.getIfPresent(source.url()), Map.of()); } - private static Map indexById(List keySet) { + private static Map indexById(String keySetUrl, List keySet) { return keySet.stream() .filter(key -> key.getId() != null) .collect( Collectors.toUnmodifiableMap( - Jwk::getId, Function.identity(), (first, repeated) -> first)); + Jwk::getId, key -> new PublishedKey(key, keySetUrl), (first, repeated) -> first)); } private List candidateSources() { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/ProviderTokenValidator.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/ProviderTokenValidator.java index 5c5c2ae1867a..2e4047424e1f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/ProviderTokenValidator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/ProviderTokenValidator.java @@ -15,9 +15,13 @@ import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; import com.auth0.jwt.interfaces.DecodedJWT; +import java.net.URI; import java.util.Optional; import java.util.Set; import java.util.function.Supplier; +import java.util.regex.Pattern; +import org.openmetadata.schema.services.connections.metadata.AuthProvider; +import org.openmetadata.service.security.IdentityProviderKeys.PublishedKey; /** * Checks that a token signed by the identity provider's keys was issued to this deployment. A @@ -29,7 +33,15 @@ * a multi-tenant application registration accepts sign-ins from every tenant. */ public final class ProviderTokenValidator { - private static final String TENANT_ID_PLACEHOLDER = "{tenantid}"; + static final String TENANT_ID_PLACEHOLDER = "{tenantid}"; + static final String ENCODED_TENANT_ID_PLACEHOLDER = "%7Btenantid%7D"; + private static final Pattern TENANT_GUID = + Pattern.compile( + "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"); + private static final Pattern SHARED_ENTRA_KEY_SET = + Pattern.compile( + "(?:.*/)?(?:common|organizations)/discovery/(?:v2\\.0/)?keys/?", + Pattern.CASE_INSENSITIVE); private static final String TENANT_ID_CLAIM = "tid"; private static final String GOOGLE_ISSUER = "https://accounts.google.com"; private static final String GOOGLE_SCHEMELESS_ISSUER = "accounts.google.com"; @@ -93,18 +105,40 @@ private static void requireIssuedBy(String providerIssuer, DecodedJWT token) { } } - private static boolean isIssuedBy(String providerIssuer, DecodedJWT token) { - String expectedIssuer = withTokenTenant(providerIssuer, token); - String issuer = token.getIssuer(); - return expectedIssuer.equals(issuer) || isGoogleSchemelessIssuer(expectedIssuer, issuer); + public static boolean isIssuedBy(String providerIssuer, DecodedJWT token) { + final String issuer = token.getIssuer(); + final String template = + providerIssuer.replace(ENCODED_TENANT_ID_PLACEHOLDER, TENANT_ID_PLACEHOLDER); + boolean matches; + if (template.contains(TENANT_ID_PLACEHOLDER)) { + final String tenant = token.getClaim(TENANT_ID_CLAIM).asString(); + matches = + tenant != null + && TENANT_GUID.matcher(tenant).matches() + && template.replace(TENANT_ID_PLACEHOLDER, tenant).equals(issuer); + } else { + matches = providerIssuer.equals(issuer) || isGoogleSchemelessIssuer(providerIssuer, issuer); + } + return matches; } - /** Multi-tenant Entra ID discovery names the issuer as a template filled in by each tenant. */ - private static String withTokenTenant(String providerIssuer, DecodedJWT token) { - String tenantId = token.getClaim(TENANT_ID_CLAIM).asString(); - return tenantId == null - ? providerIssuer - : providerIssuer.replace(TENANT_ID_PLACEHOLDER, tenantId); + /** A shared Entra key set may contain a signing key restricted to a single tenant. */ + public static boolean signingKeyAllowsIssuer( + AuthProvider provider, String providerIssuer, PublishedKey publishedKey, DecodedJWT token) { + final boolean templated = + providerIssuer.contains(TENANT_ID_PLACEHOLDER) + || providerIssuer.contains(ENCODED_TENANT_ID_PLACEHOLDER); + boolean allowed = true; + if (provider == AuthProvider.AZURE || templated) { + final var attributes = publishedKey.key().getAdditionalAttributes(); + if (attributes.containsKey("issuer")) { + allowed = attributes.get("issuer") instanceof String scope && isIssuedBy(scope, token); + } else { + final String keySetPath = URI.create(publishedKey.keySetUrl()).normalize().getPath(); + allowed = !templated && !SHARED_ENTRA_KEY_SET.matcher(keySetPath).matches(); + } + } + return allowed; } /** Google documents both forms as the issuer of its ID tokens. */ diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java index c9586f1a4353..8c821a36a035 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java @@ -1,6 +1,10 @@ package org.openmetadata.service.security; +import com.nimbusds.oauth2.sdk.ParseException; +import com.nimbusds.oauth2.sdk.util.JSONObjectUtils; +import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata; import java.util.Objects; +import net.minidev.json.JSONObject; import org.apache.commons.lang3.StringUtils; import org.openmetadata.schema.api.security.AuthenticationConfiguration; import org.openmetadata.schema.api.security.AuthorizerConfiguration; @@ -60,7 +64,21 @@ static OidcClientConfig publicCodeFlow(AuthenticationConfiguration authenticatio .withDiscoveryUri(discovery) .withDisablePkce(false) .withServerUrl(base) - .withCallbackUrl( - StringUtils.defaultIfBlank(authentication.getCallbackUrl(), base + "/callback")); + .withCallbackUrl(base + AuthenticationCodeFlowHandler.MCP_CALLBACK_PATH); + } + + static OIDCProviderMetadata parseDiscovery(String document, AuthProvider provider) + throws ParseException { + final JSONObject metadata = JSONObjectUtils.parse(document); + if (provider == AuthProvider.AZURE) { + // Entra's tenant-independent issuer contains braces, which Nimbus rejects in a URI. + final String issuer = JSONObjectUtils.getString(metadata, "issuer"); + metadata.put( + "issuer", + issuer.replace( + ProviderTokenValidator.TENANT_ID_PLACEHOLDER, + ProviderTokenValidator.ENCODED_TENANT_ID_PLACEHOLDER)); + } + return OIDCProviderMetadata.parse(metadata); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcConfiguration.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcConfiguration.java new file mode 100644 index 000000000000..6913aa0e4998 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcConfiguration.java @@ -0,0 +1,127 @@ +package org.openmetadata.service.security; + +import com.nimbusds.jose.util.Resource; +import com.nimbusds.oauth2.sdk.ParseException; +import com.nimbusds.oauth2.sdk.http.HTTPRequest; +import com.nimbusds.oauth2.sdk.http.HTTPResponse; +import com.nimbusds.oauth2.sdk.id.Issuer; +import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.time.Duration; +import java.util.function.LongSupplier; +import org.openmetadata.schema.services.connections.metadata.AuthProvider; +import org.openmetadata.service.util.OutboundUrlPolicy; +import org.pac4j.core.exception.TechnicalException; +import org.pac4j.oidc.config.OidcConfiguration; +import org.pac4j.oidc.metadata.IOidcOpMetadataResolver; +import org.pac4j.oidc.metadata.OidcOpMetadataResolver; + +/** The public MCP flow contacts provider endpoints learned from a public-client authority. */ +final class PublicOidcConfiguration extends OidcConfiguration { + private static final long DISCOVERY_INTERVAL_NANOS = Duration.ofMinutes(1).toNanos(); + private final AuthProvider provider; + private final LongSupplier nanoTime; + + PublicOidcConfiguration(AuthProvider provider) { + this(provider, System::nanoTime); + } + + PublicOidcConfiguration(AuthProvider provider, LongSupplier nanoTime) { + this.provider = provider; + this.nanoTime = nanoTime; + } + + @Override + public void configureHttpRequest(HTTPRequest request) { + super.configureHttpRequest(request); + OutboundUrlPolicy.getInstance().checkForConnect(request.getURI()); + request.setFollowRedirects(false); + } + + @Override + protected IOidcOpMetadataResolver createNewOpMetadataResolver() { + setResourceRetriever(url -> fetch(URI.create(url.toExternalForm()))); + final var resolver = new ProviderMetadataResolver(); + resolver.init(); + return resolver; + } + + private final class ProviderMetadataResolver extends OidcOpMetadataResolver { + private Issuer issuer; + private long lastAttempt; + private RuntimeException failure; + + ProviderMetadataResolver() { + super(PublicOidcConfiguration.this); + // Our monotonic refresh interval replaces Spring's last-modified HTTP probe. + setMinimumDelayBetweenChangeDetectionInMilliseconds(0); + } + + @Override + public boolean hasChanged() { + final boolean refreshDue = nanoTime.getAsLong() - lastAttempt >= DISCOVERY_INTERVAL_NANOS; + if (!refreshDue && failure != null) { + throw failure; + } + return refreshDue; + } + + @Override + protected OIDCProviderMetadata retrieveMetadata() { + lastAttempt = nanoTime.getAsLong(); + try { + final Resource document = fetch(URI.create(getDiscoveryURI())); + final var metadata = + PublicOidcAuthServletHandler.parseDiscovery(document.getContent(), provider); + if (issuer != null && !issuer.equals(metadata.getIssuer())) { + throw new TechnicalException("Public OIDC discovery changed the provider issuer"); + } + issuer = metadata.getIssuer(); + failure = null; + return metadata; + } catch (IOException | ParseException e) { + failure = new TechnicalException("Unable to read the public OIDC provider metadata", e); + throw failure; + } catch (RuntimeException e) { + failure = e; + throw e; + } + } + } + + private Resource fetch(URI uri) throws IOException { + final HTTPRequest request = new HTTPRequest(HTTPRequest.Method.GET, uri); + configureHttpRequest(request); + final HTTPResponse response = request.send(); + if (!response.indicatesSuccess()) { + throw new IOException("OIDC provider returned HTTP " + response.getStatusCode()); + } + return new Resource(response.getBody(), response.getHeaderValue("Content-Type")); + } + + /** Auth0 opens this URL on each cache miss, after checking the per-key-set fetch budget. */ + static URL checkedKeySetUrl(URL configured) { + final URI uri = URI.create(configured.toExternalForm()); + try { + return URL.of( + uri, + new URLStreamHandler() { + @Override + protected URLConnection openConnection(URL url) throws IOException { + OutboundUrlPolicy.getInstance().checkForConnect(uri); + final HttpURLConnection connection = (HttpURLConnection) configured.openConnection(); + connection.setInstanceFollowRedirects(false); + return connection; + } + }); + } catch (MalformedURLException e) { + throw new IllegalArgumentException("Invalid key-set URL", e); + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/ProviderTokenValidatorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/ProviderTokenValidatorTest.java index 326b7dd7a9e5..feac93663162 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/security/ProviderTokenValidatorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/ProviderTokenValidatorTest.java @@ -103,17 +103,17 @@ void resolvesEntraTenantTemplateFromTheTokensTenant() { () -> validate( entra, - token("https://login.microsoftonline.com/tenant-a/v2.0") + token("https://login.microsoftonline.com/11111111-2222-3333-4444-555555555555/v2.0") .withAudience(CLIENT_ID) - .withClaim("tid", "tenant-a"))); + .withClaim("tid", "11111111-2222-3333-4444-555555555555"))); assertThrows( AuthenticationException.class, () -> validate( entra, - token("https://login.microsoftonline.com/tenant-a/v2.0") + token("https://login.microsoftonline.com/11111111-2222-3333-4444-555555555555/v2.0") .withAudience(CLIENT_ID) - .withClaim("tid", "tenant-b"))); + .withClaim("tid", "99999999-8888-7777-6666-555555555555"))); } /** diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java index be24d351d422..aa2297b7a60e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java @@ -2,8 +2,10 @@ import static org.assertj.core.api.Assertions.assertThat; +import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; import org.openmetadata.schema.api.security.AuthenticationConfiguration; import org.openmetadata.schema.security.client.OidcClientConfig; import org.openmetadata.schema.services.connections.metadata.AuthProvider; @@ -19,7 +21,7 @@ class PublicOidcAuthServletHandlerTest { void derivesDiscoveryFromThePublicAuthority( AuthProvider provider, String authorityPath, String discoveryPath) { String authority = "https://localhost" + authorityPath; - String callback = "https://catalog.example.com/callback"; + String callback = "https://ui.example.com/auth/callback"; AuthenticationConfiguration authentication = new AuthenticationConfiguration() .withProvider(provider) @@ -30,12 +32,41 @@ void derivesDiscoveryFromThePublicAuthority( new OidcClientConfig().withId("old-client").withSecret("unused")); OidcClientConfig client = - PublicOidcAuthServletHandler.publicCodeFlow(authentication, "https://catalog.example.com"); + PublicOidcAuthServletHandler.publicCodeFlow( + authentication, "https://catalog.example.com/catalog"); assertThat(client.getDiscoveryUri()) .isEqualTo("https://localhost" + discoveryPath + "/.well-known/openid-configuration"); assertThat(client.getId()).isEqualTo("public-client"); - assertThat(client.getCallbackUrl()).isEqualTo(callback); + assertThat(client.getCallbackUrl()) + .isEqualTo("https://catalog.example.com/catalog/mcp/callback"); + assertThat(authentication.getCallbackUrl()).isEqualTo(callback); assertThat(client.getSecret()).isNull(); assertThat(client.getDisablePkce()).isFalse(); } + + @ParameterizedTest + @ValueSource(strings = {"common", "organizations"}) + void readsTenantIndependentEntraDiscovery(String tenant) throws Exception { + final String authority = "https://login.microsoftonline.com/" + tenant; + final String document = + """ + { + "issuer": "https://login.microsoftonline.com/{tenantid}/v2.0", + "authorization_endpoint": "%1$s/oauth2/v2.0/authorize", + "token_endpoint": "%1$s/oauth2/v2.0/token", + "jwks_uri": "%1$s/discovery/v2.0/keys", + "subject_types_supported": ["pairwise"], + "response_types_supported": ["code"], + "id_token_signing_alg_values_supported": ["RS256"] + } + """ + .formatted(authority); + + final OIDCProviderMetadata metadata = + PublicOidcAuthServletHandler.parseDiscovery(document, AuthProvider.AZURE); + assertThat(metadata.getIssuer().getValue()) + .isEqualTo("https://login.microsoftonline.com/%7Btenantid%7D/v2.0"); + assertThat(metadata.getTokenEndpointURI().toString()) + .isEqualTo(authority + "/oauth2/v2.0/token"); + } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcConfigurationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcConfigurationTest.java new file mode 100644 index 000000000000..45dba800d503 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcConfigurationTest.java @@ -0,0 +1,157 @@ +package org.openmetadata.service.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.auth0.jwk.JwkException; +import com.nimbusds.oauth2.sdk.AuthorizationCode; +import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; +import com.nimbusds.oauth2.sdk.TokenRequest; +import com.nimbusds.oauth2.sdk.id.ClientID; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.services.connections.metadata.AuthProvider; +import org.openmetadata.service.util.OutboundUrlBlockedException; +import org.pac4j.core.exception.TechnicalException; + +class PublicOidcConfigurationTest { + private final AtomicLong elapsedNanos = new AtomicLong(); + private final PublicOidcConfiguration configuration = + new PublicOidcConfiguration(AuthProvider.CUSTOM_OIDC, elapsedNanos::get); + private final AtomicInteger followed = new AtomicInteger(); + private HttpServer server; + private URI redirect; + + @BeforeEach + void startProvider() throws IOException { + server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + redirect = URI.create("http://localhost:" + server.getAddress().getPort() + "/redirect"); + server.createContext( + "/redirect", + exchange -> { + try (exchange) { + exchange.getResponseHeaders().set("Location", "/final"); + exchange.sendResponseHeaders(307, -1); + } + }); + server.createContext( + "/final", + exchange -> { + try (exchange) { + followed.incrementAndGet(); + exchange.sendResponseHeaders(200, -1); + } + }); + server.start(); + } + + @AfterEach + void stopProvider() { + server.stop(0); + } + + @Test + void refusesDiscoveryRedirect() { + configuration.setDiscoveryURI(redirect.toString()); + assertThatThrownBy(configuration::createNewOpMetadataResolver) + .isInstanceOf(TechnicalException.class) + .hasRootCauseMessage("OIDC provider returned HTTP 307"); + assertThat(followed).hasValue(0); + } + + @Test + void refreshesEndpointsForTheSameIssuerAndRejectsAnIssuerChange() { + final URI issuer = redirect.resolve("/"); + final var metadata = new AtomicReference<>(discovery(issuer, "/first-token")); + final var methods = new CopyOnWriteArrayList(); + server.createContext( + "/discovery", + exchange -> { + try (exchange) { + methods.add(exchange.getRequestMethod()); + final byte[] body = metadata.get().getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, body.length); + exchange.getResponseBody().write(body); + } + }); + configuration.setDiscoveryURI(redirect.resolve("/discovery").toString()); + configuration.setClientId("public-client"); + final var resolver = configuration.createNewOpMetadataResolver(); + + metadata.set(discovery(issuer, "/second-token")); + assertThat(resolver.load().getTokenEndpointURI()).isEqualTo(issuer.resolve("/first-token")); + elapsedNanos.addAndGet(Duration.ofMinutes(1).toNanos()); + assertThat(resolver.load().getTokenEndpointURI()).isEqualTo(issuer.resolve("/second-token")); + + elapsedNanos.addAndGet(Duration.ofMinutes(1).toNanos()); + metadata.set(discovery(issuer.resolve("/different-issuer"), "/third-token")); + assertThatThrownBy(resolver::load).hasMessageContaining("changed the provider issuer"); + assertThatThrownBy(resolver::load).hasMessageContaining("changed the provider issuer"); + assertThat(methods).containsExactly("GET", "GET", "GET"); + + elapsedNanos.addAndGet(Duration.ofMinutes(1).toNanos()); + metadata.set(discovery(issuer, "/third-token")); + assertThat(resolver.load().getTokenEndpointURI()).isEqualTo(issuer.resolve("/third-token")); + assertThat(methods).containsExactly("GET", "GET", "GET", "GET"); + } + + private static String discovery(URI issuer, String tokenPath) { + return """ + {"issuer":"%s","authorization_endpoint":"%s","token_endpoint":"%s","jwks_uri":"%s", + "response_types_supported":["code"],"subject_types_supported":["public"], + "id_token_signing_alg_values_supported":["RS256"]} + """ + .formatted( + issuer, + issuer.resolve("/authorize"), + issuer.resolve(tokenPath), + issuer.resolve("/jwks")); + } + + @Test + void returnsTokenRedirectWithoutResendingTheGrant() throws IOException { + var response = + AuthenticationCodeFlowHandler.executeTokenHttpRequest(configuration, grant(redirect)); + assertThat(response.getStatusCode()).isEqualTo(307); + assertThat(followed).hasValue(0); + } + + @Test + void checksTheTokenDestinationBeforeSending() { + final URI unresolved = URI.create("https://unregistered.invalid/token"); + assertThatThrownBy( + () -> + AuthenticationCodeFlowHandler.executeTokenHttpRequest( + configuration, grant(unresolved))) + .isInstanceOf(OutboundUrlBlockedException.class); + } + + @Test + void doesNotFollowAKeySetRedirect() throws Exception { + var keys = IdentityProviderKeys.forPublicMcp(List.of(redirect.toURL()), Duration.ofMinutes(5)); + assertThatThrownBy(() -> keys.get("example")).isInstanceOf(JwkException.class); + assertThat(followed).hasValue(0); + } + + private static TokenRequest grant(URI endpoint) { + return new TokenRequest( + endpoint, + new ClientID("public-client"), + new AuthorizationCodeGrant( + new AuthorizationCode("example"), URI.create("https://catalog.example/callback"))); + } +} From b99cf35f06e590f1502c77065d8be71234cdf7cd Mon Sep 17 00:00:00 2001 From: Kia Yun Date: Wed, 25 Nov 2026 22:43:59 +0800 Subject: [PATCH 3/8] Document public MCP discovery refresh and connection rules --- ...mcp-callback-needs-the-state-of-a-pending-login.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md b/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md index fef60f7c4a3b..21cb15b52d57 100644 --- a/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md +++ b/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md @@ -34,10 +34,19 @@ For a public OIDC client, MCP uses the top-level client ID and discovers the pro The public flow derives its own settings independently of the confidential `oidcConfiguration`. The MCP base URL comes from the MCP settings, falling back to the system OpenMetadata URL. +After the first successful discovery, the public MCP handler checks for endpoint changes on demand, +at most once per minute. If a refresh fails, sign-ins that need discovery receive that failure until +the next attempt. This bounds traffic during an outage. The issuer must match the initial document. +A provider can rotate endpoints while keeping that issuer. To switch issuers, reload the provider +configuration. For discovery, token exchanges and signing-key downloads, the server checks the +outbound URL before connecting and disables HTTP redirects. `PublicOidcConfigurationTest` covers +endpoint rotation, refusal of a changed issuer, recovery and redirect handling. + Register `/mcp/callback` at the identity provider for a server-side authorization-code exchange using the public client ID and S256 PKCE. Include the deployment base path, if configured. OpenMetadata sends this same URI when it requests and -redeems the code. The browser application retains its own registered redirect. MCP requires a pending login and asks for consent before issuing a grant. +redeems the code. The browser application retains its own registered redirect. MCP requires a pending +login and asks for consent before issuing a grant. A Microsoft Entra redirect registered as a single-page application requires a browser origin during redemption. Keep the browser redirect registered for the SPA and configure the MCP redirect From fcdedf85bc04b02069049c9111a7f4e51afd266c Mon Sep 17 00:00:00 2001 From: Kia Yun Date: Thu, 26 Nov 2026 09:01:03 +0800 Subject: [PATCH 4/8] Preserve legacy Azure sign-in and recover from provider discovery failures --- ...back-needs-the-state-of-a-pending-login.md | 3 +- openmetadata-mcp/README.md | 10 ++- .../auth/validators/IdTokenValidatorTest.java | 35 +++++++++- .../security/ProviderTokenValidator.java | 9 +-- .../PublicOidcAuthServletHandler.java | 35 +++++++++- .../security/PublicOidcConfiguration.java | 10 ++- .../security/IdentityProviderKeysTest.java | 27 ++++++++ .../security/ProviderTokenValidatorTest.java | 26 +++++++ .../PublicOidcAuthServletHandlerTest.java | 67 +++++++++++++++++++ 9 files changed, 209 insertions(+), 13 deletions(-) diff --git a/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md b/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md index 21cb15b52d57..f8e0e65f233f 100644 --- a/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md +++ b/docs/decisions/2026-10-30-the-mcp-callback-needs-the-state-of-a-pending-login.md @@ -34,7 +34,8 @@ For a public OIDC client, MCP uses the top-level client ID and discovers the pro The public flow derives its own settings independently of the confidential `oidcConfiguration`. The MCP base URL comes from the MCP settings, falling back to the system OpenMetadata URL. -After the first successful discovery, the public MCP handler checks for endpoint changes on demand, +If initial discovery fails, the public MCP handler waits one minute before trying again for the +same configuration. After the first success, the handler checks for endpoint changes on demand, at most once per minute. If a refresh fails, sign-ins that need discovery receive that failure until the next attempt. This bounds traffic during an outage. The issuer must match the initial document. A provider can rotate endpoints while keeping that issuer. To switch issuers, reload the provider diff --git a/openmetadata-mcp/README.md b/openmetadata-mcp/README.md index a19ffe82ab67..6f5395206d7a 100644 --- a/openmetadata-mcp/README.md +++ b/openmetadata-mcp/README.md @@ -392,6 +392,14 @@ OAuth components initialized in `McpServer`: 5. SSO callback servlet and Basic Auth login servlet registration 6. OAuthTokenCleanupJob scheduled (10-minute intervals) +### Public OIDC provider setup + +Register `/mcp/callback` at the identity provider for a +server-side authorization-code exchange with PKCE. Keep the browser application's +redirect registered separately. For an internal provider, configure its authority +and endpoints with a DNS hostname that the OpenMetadata server can resolve. +The outbound URL policy rejects private and loopback IP literals. + ### Environment Variables **SSO Provider Configuration** (varies by provider): @@ -425,4 +433,4 @@ OAuth components initialized in `McpServer`: ## License -Apache License 2.0 \ No newline at end of file +Apache License 2.0 diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/validators/IdTokenValidatorTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/validators/IdTokenValidatorTest.java index 87463b67614c..fd4c0e0ef0e5 100644 --- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/validators/IdTokenValidatorTest.java +++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/server/auth/validators/IdTokenValidatorTest.java @@ -193,7 +193,33 @@ void refusesNonGuidTenantEvenWhenTheIssuerMatchesTheClaim() { } @ParameterizedTest - @ValueSource(strings = {"/common/discovery/keys", "/organizations/discovery/v2.0/keys"}) + @ValueSource(booleans = {false, true}) + void concreteEntraAuthorityAcceptsLegacyKeysWithoutAnIssuer(boolean publicClient) + throws Exception { + final String legacyKeys = publishKeySet("/common/discovery/keys", keyId); + final IdTokenValidator entra = + new IdTokenValidator( + new McpTokenVerification( + List.of(legacyKeys), + TENANT_ISSUER, + expectedAudience, + publicClient, + AuthProvider.AZURE)); + + assertThat(entra.validateAndDecode(tenantToken(TENANT_ISSUER, TENANT_ID)).getIssuer()) + .isEqualTo(TENANT_ISSUER); + final String otherTenant = "00000000-0000-0000-0000-000000000001"; + assertThatThrownBy( + () -> + entra.validateAndDecode( + tenantToken( + "https://login.microsoftonline.com/" + otherTenant + "/v2.0", otherTenant))) + .isInstanceOf(IdTokenValidationException.class) + .hasMessageContaining("issuer mismatch"); + } + + @ParameterizedTest + @ValueSource(strings = {"/common/discovery/v2.0/keys", "/organizations/discovery/v2.0/keys"}) void concreteEntraAuthorityChecksTheSetThatSuppliedTheKey(String sharedPath) throws Exception { final String tenantKeys = publishKeySet("/" + TENANT_ID + "/discovery/v2.0/keys", "tenant-key"); final String sharedKeys = publishKeySet(sharedPath, "shared-key"); @@ -218,7 +244,12 @@ void concreteEntraAuthorityChecksTheSetThatSuppliedTheKey(String sharedPath) thr } @ParameterizedTest - @ValueSource(strings = {"/common/discovery/v2.0/keys", "/tenant/discovery/v2.0/keys"}) + @ValueSource( + strings = { + "/common/discovery/keys", + "/common/discovery/v2.0/keys", + "/tenant/discovery/v2.0/keys" + }) void concreteEntraAuthorityHonorsAnExplicitKeyScope(String keySetPath) { signingKeyIssuer = "https://login.microsoftonline.com/00000000-0000-0000-0000-000000000001/v2.0"; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/ProviderTokenValidator.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/ProviderTokenValidator.java index 2e4047424e1f..71ef3e5e05d8 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/ProviderTokenValidator.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/ProviderTokenValidator.java @@ -38,10 +38,9 @@ public final class ProviderTokenValidator { private static final Pattern TENANT_GUID = Pattern.compile( "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"); - private static final Pattern SHARED_ENTRA_KEY_SET = + private static final Pattern SHARED_ENTRA_V2_KEY_SET = Pattern.compile( - "(?:.*/)?(?:common|organizations)/discovery/(?:v2\\.0/)?keys/?", - Pattern.CASE_INSENSITIVE); + "(?:.*/)?(?:common|organizations)/discovery/v2\\.0/keys/?", Pattern.CASE_INSENSITIVE); private static final String TENANT_ID_CLAIM = "tid"; private static final String GOOGLE_ISSUER = "https://accounts.google.com"; private static final String GOOGLE_SCHEMELESS_ISSUER = "accounts.google.com"; @@ -135,7 +134,9 @@ public static boolean signingKeyAllowsIssuer( allowed = attributes.get("issuer") instanceof String scope && isIssuedBy(scope, token); } else { final String keySetPath = URI.create(publishedKey.keySetUrl()).normalize().getPath(); - allowed = !templated && !SHARED_ENTRA_KEY_SET.matcher(keySetPath).matches(); + // The legacy /common/discovery/keys omits per-key issuers. A concrete authority + // still pins the token issuer; tenant-independent v2 keys must declare their scope. + allowed = !templated && !SHARED_ENTRA_V2_KEY_SET.matcher(keySetPath).matches(); } } return allowed; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java index 8c821a36a035..f8431e692960 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java @@ -4,6 +4,7 @@ import com.nimbusds.oauth2.sdk.util.JSONObjectUtils; import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata; import java.util.Objects; +import java.util.function.LongSupplier; import net.minidev.json.JSONObject; import org.apache.commons.lang3.StringUtils; import org.openmetadata.schema.api.security.AuthenticationConfiguration; @@ -20,29 +21,57 @@ final class PublicOidcAuthServletHandler extends NoopAuthServeletHandler { private final AuthenticationConfiguration authentication; private final AuthorizerConfiguration authorizer; private final SessionService sessions; + private final LongSupplier nanoTime; private AuthenticationCodeFlowHandler handler; private String baseUrl; + private RuntimeException initializationFailure; + private long failedAt; PublicOidcAuthServletHandler( AuthenticationConfiguration authentication, AuthorizerConfiguration authorizer, SessionService sessions) { + this(authentication, authorizer, sessions, System::nanoTime); + } + + PublicOidcAuthServletHandler( + AuthenticationConfiguration authentication, + AuthorizerConfiguration authorizer, + SessionService sessions, + LongSupplier nanoTime) { this.authentication = authentication; this.authorizer = authorizer; this.sessions = sessions; + this.nanoTime = nanoTime; } synchronized AuthenticationCodeFlowHandler forMcp(String configuredBaseUrl) { final String base = StringUtils.stripEnd(configuredBaseUrl, "/"); - if (handler == null || !Objects.equals(baseUrl, base)) { + if (!Objects.equals(baseUrl, base)) { + baseUrl = base; + handler = null; + initializationFailure = null; + } + if (handler != null) { + return handler; + } + if (initializationFailure != null + && nanoTime.getAsLong() - failedAt < PublicOidcConfiguration.DISCOVERY_INTERVAL_NANOS) { + throw initializationFailure; + } + try { // Only public-client deployments that actually use MCP need backend discovery. final AuthenticationConfiguration effective = JsonUtils.deepCopy(authentication, AuthenticationConfiguration.class); effective.setOidcConfiguration(publicCodeFlow(authentication, base)); handler = new AuthenticationCodeFlowHandler(effective, authorizer, sessions, true); - baseUrl = base; + initializationFailure = null; + return handler; + } catch (RuntimeException failure) { + initializationFailure = failure; + failedAt = nanoTime.getAsLong(); + throw failure; } - return handler; } static OidcClientConfig publicCodeFlow(AuthenticationConfiguration authentication, String base) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcConfiguration.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcConfiguration.java index 6913aa0e4998..fd56d7c4aa2b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcConfiguration.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcConfiguration.java @@ -16,6 +16,7 @@ import java.time.Duration; import java.util.function.LongSupplier; import org.openmetadata.schema.services.connections.metadata.AuthProvider; +import org.openmetadata.service.util.OutboundUrlBlockedException; import org.openmetadata.service.util.OutboundUrlPolicy; import org.pac4j.core.exception.TechnicalException; import org.pac4j.oidc.config.OidcConfiguration; @@ -24,7 +25,7 @@ /** The public MCP flow contacts provider endpoints learned from a public-client authority. */ final class PublicOidcConfiguration extends OidcConfiguration { - private static final long DISCOVERY_INTERVAL_NANOS = Duration.ofMinutes(1).toNanos(); + static final long DISCOVERY_INTERVAL_NANOS = Duration.ofMinutes(1).toNanos(); private final AuthProvider provider; private final LongSupplier nanoTime; @@ -114,7 +115,12 @@ static URL checkedKeySetUrl(URL configured) { new URLStreamHandler() { @Override protected URLConnection openConnection(URL url) throws IOException { - OutboundUrlPolicy.getInstance().checkForConnect(uri); + try { + OutboundUrlPolicy.getInstance().checkForConnect(uri); + } catch (OutboundUrlBlockedException denied) { + // Auth0 reports IO failures per key set, allowing lookup to try the next source. + throw new IOException("Key-set URL was denied by the outbound policy", denied); + } final HttpURLConnection connection = (HttpURLConnection) configured.openConnection(); connection.setInstanceFollowRedirects(false); return connection; diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/IdentityProviderKeysTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/IdentityProviderKeysTest.java index 6f533dccec01..63bab98d1790 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/security/IdentityProviderKeysTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/IdentityProviderKeysTest.java @@ -4,6 +4,9 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; import com.auth0.jwk.JwkException; import com.auth0.jwk.SigningKeyNotFoundException; @@ -20,6 +23,8 @@ import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.openmetadata.service.util.OutboundUrlBlockedException; +import org.openmetadata.service.util.OutboundUrlPolicy; class IdentityProviderKeysTest { private static final Duration ONE_DAY = Duration.ofDays(1); @@ -30,6 +35,28 @@ class IdentityProviderKeysTest { private static final KeySetFetchPolicy BURST_OF_TWO = new KeySetFetchPolicy(Duration.ofSeconds(1), Duration.ofSeconds(1), 2, Duration.ofHours(1)); + @Test + void publicMcpSkipsADeniedKeySetAndReturnsTheNextSourcesKey() throws Exception { + try (KeySetServer denied = KeySetServer.publishing("provider-key"); + KeySetServer permitted = KeySetServer.publishing("provider-key"); + var policies = mockStatic(OutboundUrlPolicy.class)) { + final var policy = mock(OutboundUrlPolicy.class); + policies.when(OutboundUrlPolicy::getInstance).thenReturn(policy); + doThrow(new OutboundUrlBlockedException("Key source denied by test policy")) + .when(policy) + .checkForConnect(denied.url().toURI()); + final var keys = + IdentityProviderKeys.forPublicMcp(List.of(denied.url(), permitted.url()), ONE_DAY); + + final var found = keys.getWithSource("provider-key"); + + assertEquals("provider-key", found.key().getId()); + assertEquals(permitted.url().toExternalForm(), found.keySetUrl()); + assertEquals(0, denied.requests()); + assertEquals(1, permitted.requests()); + } + } + @Test void tokenWithoutAKeyIdNamesNoKey() { IdentityProviderKeys keys = IdentityProviderKeys.forUrls(List.of(), ONE_DAY); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/ProviderTokenValidatorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/ProviderTokenValidatorTest.java index feac93663162..fe840ba53912 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/security/ProviderTokenValidatorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/ProviderTokenValidatorTest.java @@ -13,16 +13,23 @@ package org.openmetadata.service.security; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.auth0.jwk.Jwk; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTCreator; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; +import java.util.Map; import java.util.Optional; import java.util.Set; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.openmetadata.schema.services.connections.metadata.AuthProvider; +import org.openmetadata.service.security.IdentityProviderKeys.PublishedKey; class ProviderTokenValidatorTest { private static final String CLIENT_ID = "openmetadata-client"; @@ -116,6 +123,25 @@ void resolvesEntraTenantTemplateFromTheTokensTenant() { .withClaim("tid", "99999999-8888-7777-6666-555555555555"))); } + @ParameterizedTest + @ValueSource( + strings = {ENTRA_COMMON_ISSUER, "https://login.microsoftonline.com/%7Btenantid%7D/v2.0"}) + void tenantIndependentAuthorityRequiresAKeyIssuerEvenForLegacyKeys(String providerIssuer) { + final String tenant = "11111111-2222-3333-4444-555555555555"; + final DecodedJWT token = + decode( + token("https://login.microsoftonline.com/" + tenant + "/v2.0") + .withClaim("tid", tenant)); + final PublishedKey legacyKey = + new PublishedKey( + Jwk.fromValues(Map.of("kty", "RSA", "kid", "legacy")), + "https://login.microsoftonline.com/common/discovery/keys"); + + assertFalse( + ProviderTokenValidator.signingKeyAllowsIssuer( + AuthProvider.AZURE, providerIssuer, legacyKey, token)); + } + /** * A public client has no discovery document, but a multi-tenant application registration signs * users in from every tenant. The tenant its authority names is the one tokens must come from. diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java index aa2297b7a60e..4cd148cfac94 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java @@ -1,16 +1,83 @@ package org.openmetadata.service.security; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata; +import com.sun.net.httpserver.HttpServer; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.openmetadata.schema.api.security.AuthenticationConfiguration; +import org.openmetadata.schema.api.security.AuthorizerConfiguration; import org.openmetadata.schema.security.client.OidcClientConfig; import org.openmetadata.schema.services.connections.metadata.AuthProvider; class PublicOidcAuthServletHandlerTest { + @Test + void initialDiscoveryRetriesAfterOneMinuteAndRecovers() throws Exception { + final HttpServer server = + HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + final String authority = "http://localhost:" + server.getAddress().getPort(); + final String base = "https://catalog.example.com"; + final var requests = new AtomicInteger(); + final var elapsed = new AtomicLong(); + server.createContext( + "/.well-known/openid-configuration", + exchange -> { + try (exchange) { + if (requests.incrementAndGet() == 1) { + exchange.sendResponseHeaders(503, -1); + return; + } + final byte[] document = + """ + {"issuer":"%1$s","authorization_endpoint":"%1$s/authorize","token_endpoint":"%1$s/token", + "jwks_uri":"%1$s/keys","subject_types_supported":["public"],"response_types_supported":["code"], + "id_token_signing_alg_values_supported":["RS256"]} + """ + .formatted(authority) + .getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, document.length); + exchange.getResponseBody().write(document); + } + }); + server.start(); + try { + final var handler = + new PublicOidcAuthServletHandler( + new AuthenticationConfiguration() + .withProvider(AuthProvider.CUSTOM_OIDC) + .withAuthority(authority) + .withClientId("public-client"), + new AuthorizerConfiguration(), + null, + elapsed::get); + + assertThatThrownBy(() -> handler.forMcp(base)) + .hasRootCauseMessage("OIDC provider returned HTTP 503"); + elapsed.set(Duration.ofSeconds(59).toNanos()); + assertThatThrownBy(() -> handler.forMcp(base)) + .hasRootCauseMessage("OIDC provider returned HTTP 503"); + assertThat(requests).hasValue(1); + + elapsed.set(Duration.ofMinutes(1).toNanos()); + final var recovered = handler.forMcp(base); + assertThat(handler.forMcp(base)).isSameAs(recovered); + assertThat(requests).hasValue(2); + } finally { + server.stop(0); + } + } + @ParameterizedTest @CsvSource({ "CUSTOM_OIDC, /realms/catalog/, /realms/catalog", From f3c7fa0ffd268832b8df8ace4ea49f151b8505d0 Mon Sep 17 00:00:00 2001 From: Kia Yun Date: Thu, 26 Nov 2026 09:09:12 +0800 Subject: [PATCH 5/8] Use a single return in the public MCP handler cache --- .../PublicOidcAuthServletHandler.java | 37 +++++++++---------- .../PublicOidcAuthServletHandlerTest.java | 24 ++++++------ 2 files changed, 30 insertions(+), 31 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java index f8431e692960..6bad0c2fb47e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcAuthServletHandler.java @@ -52,26 +52,25 @@ synchronized AuthenticationCodeFlowHandler forMcp(String configuredBaseUrl) { handler = null; initializationFailure = null; } - if (handler != null) { - return handler; - } - if (initializationFailure != null - && nanoTime.getAsLong() - failedAt < PublicOidcConfiguration.DISCOVERY_INTERVAL_NANOS) { - throw initializationFailure; - } - try { - // Only public-client deployments that actually use MCP need backend discovery. - final AuthenticationConfiguration effective = - JsonUtils.deepCopy(authentication, AuthenticationConfiguration.class); - effective.setOidcConfiguration(publicCodeFlow(authentication, base)); - handler = new AuthenticationCodeFlowHandler(effective, authorizer, sessions, true); - initializationFailure = null; - return handler; - } catch (RuntimeException failure) { - initializationFailure = failure; - failedAt = nanoTime.getAsLong(); - throw failure; + if (handler == null) { + if (initializationFailure != null + && nanoTime.getAsLong() - failedAt < PublicOidcConfiguration.DISCOVERY_INTERVAL_NANOS) { + throw initializationFailure; + } + try { + // Only public-client deployments that actually use MCP need backend discovery. + final AuthenticationConfiguration effective = + JsonUtils.deepCopy(authentication, AuthenticationConfiguration.class); + effective.setOidcConfiguration(publicCodeFlow(authentication, base)); + handler = new AuthenticationCodeFlowHandler(effective, authorizer, sessions, true); + initializationFailure = null; + } catch (RuntimeException failure) { + initializationFailure = failure; + failedAt = nanoTime.getAsLong(); + throw failure; + } } + return handler; } static OidcClientConfig publicCodeFlow(AuthenticationConfiguration authentication, String base) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java index 4cd148cfac94..2148a1ae81b6 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcAuthServletHandlerTest.java @@ -35,19 +35,19 @@ void initialDiscoveryRetriesAfterOneMinuteAndRecovers() throws Exception { try (exchange) { if (requests.incrementAndGet() == 1) { exchange.sendResponseHeaders(503, -1); - return; + } else { + final byte[] document = + """ + {"issuer":"%1$s","authorization_endpoint":"%1$s/authorize","token_endpoint":"%1$s/token", + "jwks_uri":"%1$s/keys","subject_types_supported":["public"],"response_types_supported":["code"], + "id_token_signing_alg_values_supported":["RS256"]} + """ + .formatted(authority) + .getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, document.length); + exchange.getResponseBody().write(document); } - final byte[] document = - """ - {"issuer":"%1$s","authorization_endpoint":"%1$s/authorize","token_endpoint":"%1$s/token", - "jwks_uri":"%1$s/keys","subject_types_supported":["public"],"response_types_supported":["code"], - "id_token_signing_alg_values_supported":["RS256"]} - """ - .formatted(authority) - .getBytes(StandardCharsets.UTF_8); - exchange.getResponseHeaders().set("Content-Type", "application/json"); - exchange.sendResponseHeaders(200, document.length); - exchange.getResponseBody().write(document); } }); server.start(); From 25904d6a5c0379d7f8c1d5b49d5f294f37fbf697 Mon Sep 17 00:00:00 2001 From: Kia Yun Date: Fri, 27 Nov 2026 12:52:53 +0800 Subject: [PATCH 6/8] Preserve public OIDC discovery failures after the pac4j upgrade --- .../security/PublicOidcConfiguration.java | 90 ++++++++++++------- .../security/PublicOidcConfigurationTest.java | 6 ++ 2 files changed, 64 insertions(+), 32 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcConfiguration.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcConfiguration.java index fd56d7c4aa2b..7fb34d970ca3 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcConfiguration.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/PublicOidcConfiguration.java @@ -2,6 +2,7 @@ import com.nimbusds.jose.util.Resource; import com.nimbusds.oauth2.sdk.ParseException; +import com.nimbusds.oauth2.sdk.auth.ClientAuthentication; import com.nimbusds.oauth2.sdk.http.HTTPRequest; import com.nimbusds.oauth2.sdk.http.HTTPResponse; import com.nimbusds.oauth2.sdk.id.Issuer; @@ -21,7 +22,8 @@ import org.pac4j.core.exception.TechnicalException; import org.pac4j.oidc.config.OidcConfiguration; import org.pac4j.oidc.metadata.IOidcOpMetadataResolver; -import org.pac4j.oidc.metadata.OidcOpMetadataResolver; +import org.pac4j.oidc.metadata.StaticOidcOpMetadataResolver; +import org.pac4j.oidc.profile.creator.TokenValidator; /** The public MCP flow contacts provider endpoints learned from a public-client authority. */ final class PublicOidcConfiguration extends OidcConfiguration { @@ -49,50 +51,74 @@ public void configureHttpRequest(HTTPRequest request) { protected IOidcOpMetadataResolver createNewOpMetadataResolver() { setResourceRetriever(url -> fetch(URI.create(url.toExternalForm()))); final var resolver = new ProviderMetadataResolver(); - resolver.init(); + resolver.load(); return resolver; } - private final class ProviderMetadataResolver extends OidcOpMetadataResolver { + private final class ProviderMetadataResolver implements IOidcOpMetadataResolver { + private StaticOidcOpMetadataResolver resolver; private Issuer issuer; private long lastAttempt; private RuntimeException failure; - ProviderMetadataResolver() { - super(PublicOidcConfiguration.this); - // Our monotonic refresh interval replaces Spring's last-modified HTTP probe. - setMinimumDelayBetweenChangeDetectionInMilliseconds(0); + private synchronized StaticOidcOpMetadataResolver current() { + final long now = nanoTime.getAsLong(); + if ((resolver == null && failure == null) || now - lastAttempt >= DISCOVERY_INTERVAL_NANOS) { + lastAttempt = now; + try { + resolver = resolveDiscovery(); + failure = null; + } catch (IOException | ParseException e) { + failure = new TechnicalException("Unable to read the public OIDC provider metadata", e); + } catch (RuntimeException e) { + failure = e; + } + } + if (failure != null) { + throw failure; + } + return resolver; } - @Override - public boolean hasChanged() { - final boolean refreshDue = nanoTime.getAsLong() - lastAttempt >= DISCOVERY_INTERVAL_NANOS; - if (!refreshDue && failure != null) { - throw failure; + private StaticOidcOpMetadataResolver resolveDiscovery() throws IOException, ParseException { + final Resource document = fetch(URI.create(getDiscoveryURI())); + final var metadata = + PublicOidcAuthServletHandler.parseDiscovery(document.getContent(), provider); + if (issuer != null && !issuer.equals(metadata.getIssuer())) { + throw new TechnicalException("Public OIDC discovery changed the provider issuer"); } - return refreshDue; + final var snapshot = + new StaticOidcOpMetadataResolver(PublicOidcConfiguration.this, metadata) { + @Override + public boolean hasChanged() { + // Only the outer resolver refreshes discovery, through the configured outbound + // policy. + return false; + } + }; + snapshot.init(); + issuer = metadata.getIssuer(); + return snapshot; } @Override - protected OIDCProviderMetadata retrieveMetadata() { - lastAttempt = nanoTime.getAsLong(); - try { - final Resource document = fetch(URI.create(getDiscoveryURI())); - final var metadata = - PublicOidcAuthServletHandler.parseDiscovery(document.getContent(), provider); - if (issuer != null && !issuer.equals(metadata.getIssuer())) { - throw new TechnicalException("Public OIDC discovery changed the provider issuer"); - } - issuer = metadata.getIssuer(); - failure = null; - return metadata; - } catch (IOException | ParseException e) { - failure = new TechnicalException("Unable to read the public OIDC provider metadata", e); - throw failure; - } catch (RuntimeException e) { - failure = e; - throw e; - } + public OIDCProviderMetadata load() { + return current().load(); + } + + @Override + public TokenValidator getTokenValidator() { + return current().getTokenValidator(); + } + + @Override + public ClientAuthentication getClientAuthenticationTokenEndpoint() { + return current().getClientAuthenticationTokenEndpoint(); + } + + @Override + public ClientAuthentication getClientAuthenticationPAREndpoint() { + return current().getClientAuthenticationPAREndpoint(); } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcConfigurationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcConfigurationTest.java index 45dba800d503..2f613eef3a36 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcConfigurationTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/PublicOidcConfigurationTest.java @@ -101,6 +101,12 @@ void refreshesEndpointsForTheSameIssuerAndRejectsAnIssuerChange() { metadata.set(discovery(issuer.resolve("/different-issuer"), "/third-token")); assertThatThrownBy(resolver::load).hasMessageContaining("changed the provider issuer"); assertThatThrownBy(resolver::load).hasMessageContaining("changed the provider issuer"); + assertThatThrownBy(resolver::getTokenValidator) + .hasMessageContaining("changed the provider issuer"); + assertThatThrownBy(resolver::getClientAuthenticationTokenEndpoint) + .hasMessageContaining("changed the provider issuer"); + assertThatThrownBy(resolver::getClientAuthenticationPAREndpoint) + .hasMessageContaining("changed the provider issuer"); assertThat(methods).containsExactly("GET", "GET", "GET"); elapsedNanos.addAndGet(Duration.ofMinutes(1).toNanos()); From e5a6aec8b483b55e80c7ef3450fce87d38df2bbe Mon Sep 17 00:00:00 2001 From: Kia Yun Date: Fri, 27 Nov 2026 14:12:47 +0800 Subject: [PATCH 7/8] Document the additional MCP callback in the SSO setup guides --- .../locales/en-US/SSO/auth0SSOClientConfig.md | 19 ++++++----------- .../en-US/SSO/awsCognitoSSOClientConfig.md | 5 +++++ .../locales/en-US/SSO/azureSSOClientConfig.md | 21 +++++++------------ .../en-US/SSO/customOidcSSOClientConfig.md | 5 +++++ .../en-US/SSO/googleSSOClientConfig.md | 20 +++++++----------- .../locales/en-US/SSO/oktaSSOClientConfig.md | 19 ++++++----------- 6 files changed, 37 insertions(+), 52 deletions(-) diff --git a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/auth0SSOClientConfig.md b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/auth0SSOClientConfig.md index 8be39c11b068..57e00bc4b470 100644 --- a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/auth0SSOClientConfig.md +++ b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/auth0SSOClientConfig.md @@ -55,6 +55,12 @@ $$section - **Note:** - Must be registered in Auth0 → Applications → Authentication → Redirect URIs - Always use HTTPS in production + - The web callback defaults to `{your-domain}/callback`. Register the exact URL shown in this field. + +**MCP sign-in** + +- Allow the authorization code grant (`code`) for this client. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). +- Add `/mcp/callback` to the Auth0 application’s allowed callback URLs. Use the external address where users reach the OpenMetadata MCP server, for example `https://catalog.example.com/mcp/callback`. $$ $$section @@ -259,19 +265,6 @@ $$section - **Note:** Common parameters include `prompt`, `domain_hint`, `login_hint` $$ -$$section -### OIDC Callback URL / Redirect URI $(id="callbackUrl") - -- **Definition:** URL where Auth0 redirects after authentication. -- **Auto-Generated:** This field is automatically populated as `{your-domain}/callback`. -- **Example:** https://openmetadata.company.com/callback -- **Why it matters:** Must be registered in your Auth0 configuration. -- **Note:** - - **This field is read-only** - it cannot be edited - - **Copy this exact URL** and add it to Auth0's allowed redirect URIs list - - Format is always: `{your-domain}/callback` -$$ - $$section ### OIDC Max Age $(id="maxAge") diff --git a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/awsCognitoSSOClientConfig.md b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/awsCognitoSSOClientConfig.md index 9afd0df5beaf..6e6b0c352939 100644 --- a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/awsCognitoSSOClientConfig.md +++ b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/awsCognitoSSOClientConfig.md @@ -54,6 +54,11 @@ $$section - **This field is read-only** - it cannot be edited - **Copy this exact URL** and add it to AWS Cognito's allowed redirect URIs list - Format is always: `{your-domain}/callback` + +**MCP sign-in** + +- Allow the authorization code grant (`code`) for this client. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). +- Add `/mcp/callback` to the Cognito app client’s allowed callback URLs. Use the external address where users reach the OpenMetadata MCP server, for example `https://catalog.example.com/mcp/callback`. $$ $$section diff --git a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/azureSSOClientConfig.md b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/azureSSOClientConfig.md index 375a88590e22..1c3cef48b22f 100644 --- a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/azureSSOClientConfig.md +++ b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/azureSSOClientConfig.md @@ -53,6 +53,13 @@ $$section - **Note:** - Must be registered in Azure AD → App registrations → Authentication → Redirect URIs - Always use HTTPS in production + - The web callback defaults to `{your-domain}/callback`. Register the exact URL shown in this field. + +**MCP sign-in** + +- Allow the authorization code grant (`code`) for this client. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). +- Add `/mcp/callback` to the redirect URIs in your Entra app registration. Use the external address where users reach the OpenMetadata MCP server, for example `https://catalog.example.com/mcp/callback`. +- In **App registrations → your application → Authentication**, choose **Mobile and desktop applications** for an OpenMetadata **Public** client (S256 PKCE, no client secret), or **Web** for a **Confidential** client. A **Single-page application** redirect requires a browser token exchange. OpenMetadata redeems the MCP code on the server. [Microsoft redirect URI setup](https://learn.microsoft.com/en-us/entra/identity-platform/how-to-add-redirect-uri) $$ $$section @@ -73,6 +80,7 @@ $$section - **Example:** ["https://login.microsoftonline.com/YOUR-TENANT-ID/discovery/v2.0/keys"] - **Why it matters:** Used to verify JWT token signatures from Azure AD. - **Note:** Usually auto-discovered from the discovery URI, rarely needs manual configuration +- **Multi-tenant MCP sign-in:** Use the `jwks_uri` from your authority’s v2.0 discovery document, for example `https://login.microsoftonline.com/common/discovery/v2.0/keys`. MCP checks the issuer on each signing key. With a tenant-independent authority, the legacy `/common/discovery/keys` endpoint supplies keys without an issuer and MCP rejects them. A fixed-tenant authority can still use those legacy keys. [Microsoft signing-key guidance](https://learn.microsoft.com/en-us/entra/identity-platform/access-tokens#validate-the-signing-key-issuer) $$ $$section @@ -268,19 +276,6 @@ $$section - **Note:** Can be tenant ID, domain name, or "common" for multi-tenant $$ -$$section -### OIDC Callback URL / Redirect URI $(id="callbackUrl") - -- **Definition:** URL where Azure AD redirects after authentication. -- **Auto-Generated:** This field is automatically populated as `{your-domain}/callback`. -- **Example:** https://openmetadata.company.com/callback -- **Why it matters:** Must be registered in your Azure AD app configuration. -- **Note:** - - **This field is read-only** - it cannot be edited - - **Copy this exact URL** and add it to Azure AD → App registrations → Authentication → Redirect URIs - - Format is always: `{your-domain}/callback` -$$ - $$section ### OIDC Max Age $(id="maxAge") diff --git a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/customOidcSSOClientConfig.md b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/customOidcSSOClientConfig.md index 335873ab90de..e082c271e632 100644 --- a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/customOidcSSOClientConfig.md +++ b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/customOidcSSOClientConfig.md @@ -41,6 +41,11 @@ $$section - **This field is read-only** - it cannot be edited - **Copy this exact URL** and add it to your OIDC provider's allowed redirect URIs list - Format is always: `{your-domain}/callback` + +**MCP sign-in** + +- Allow the authorization code grant (`code`) for this client. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). +- Add `/mcp/callback` to your provider’s allowed redirect URIs. Use the external address where users reach the OpenMetadata MCP server, for example `https://catalog.example.com/mcp/callback`. $$ $$section diff --git a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/googleSSOClientConfig.md b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/googleSSOClientConfig.md index e72e5fad5045..9859a8fa1c7b 100644 --- a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/googleSSOClientConfig.md +++ b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/googleSSOClientConfig.md @@ -63,6 +63,13 @@ $$section - **Note:** - Must be registered in Google Cloud Console → Credentials → OAuth 2.0 Client → Authorized redirect URIs - Always use HTTPS in production + - The web callback defaults to `{your-domain}/callback`. Register the exact URL shown in this field. + +**MCP sign-in** + +- Allow the authorization code grant (`code`) for this client. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). +- Add `/mcp/callback` to the Google OAuth client’s authorized redirect URIs. Use the external address where users reach the OpenMetadata MCP server, for example `https://catalog.example.com/mcp/callback`. +- For a Google client that requires a secret to redeem the code, configure **Confidential** in OpenMetadata and supply the secret on the server. $$ $$section @@ -279,19 +286,6 @@ $$section - `login_hint`: Pre-fill email address $$ -$$section -### OIDC Callback URL / Redirect URI $(id="callbackUrl") - -- **Definition:** URL where Google redirects after authentication. -- **Auto-Generated:** This field is automatically populated as `{your-domain}/callback`. -- **Example:** https://openmetadata.company.com/callback -- **Why it matters:** Must be registered in your Google Cloud Console configuration. -- **Note:** - - **This field is read-only** - it cannot be edited - - **Copy this exact URL** and add it to your Google Cloud Console → OAuth 2.0 Client → Authorized redirect URIs - - Format is always: `{your-domain}/callback` -$$ - $$section ### OIDC Max Age $(id="maxAge") diff --git a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/oktaSSOClientConfig.md b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/oktaSSOClientConfig.md index 03a36d7f885a..18d32ec7771d 100644 --- a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/oktaSSOClientConfig.md +++ b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/oktaSSOClientConfig.md @@ -53,6 +53,12 @@ $$section - **Note:** - Must be registered in Okta → Applications → Your app → General → Sign-in redirect URIs - Always use HTTPS in production + - The web callback defaults to `{your-domain}/callback`. Register the exact URL shown in this field. + +**MCP sign-in** + +- Allow the authorization code grant (`code`) for this client. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). +- Add `/mcp/callback` to the Okta app integration’s sign-in redirect URIs. Use the external address where users reach the OpenMetadata MCP server, for example `https://catalog.example.com/mcp/callback`. $$ $$section @@ -256,19 +262,6 @@ $$section - **Note:** Common parameters include `prompt`, `max_age`, `login_hint` $$ -$$section -### OIDC Callback URL / Redirect URI $(id="callbackUrl") - -- **Definition:** URL where Okta redirects after authentication. -- **Auto-Generated:** This field is automatically populated as `{your-domain}/callback`. -- **Example:** https://openmetadata.company.com/callback -- **Why it matters:** Must be registered in your Okta configuration. -- **Note:** - - **This field is read-only** - it cannot be edited - - **Copy this exact URL** and add it to Okta's allowed redirect URIs list - - Format is always: `{your-domain}/callback` -$$ - $$section ### OIDC Max Age $(id="maxAge") From 907c768f02cccd833b4abe23c383073519a60765 Mon Sep 17 00:00:00 2001 From: Kia Yun Date: Fri, 27 Nov 2026 14:47:36 +0800 Subject: [PATCH 8/8] Distinguish the MCP authorization grant from its response type --- .../ui/public/locales/en-US/SSO/auth0SSOClientConfig.md | 2 +- .../ui/public/locales/en-US/SSO/awsCognitoSSOClientConfig.md | 2 +- .../ui/public/locales/en-US/SSO/azureSSOClientConfig.md | 2 +- .../ui/public/locales/en-US/SSO/customOidcSSOClientConfig.md | 2 +- .../ui/public/locales/en-US/SSO/googleSSOClientConfig.md | 2 +- .../ui/public/locales/en-US/SSO/oktaSSOClientConfig.md | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/auth0SSOClientConfig.md b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/auth0SSOClientConfig.md index 57e00bc4b470..f21ff2c67c34 100644 --- a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/auth0SSOClientConfig.md +++ b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/auth0SSOClientConfig.md @@ -59,7 +59,7 @@ $$section **MCP sign-in** -- Allow the authorization code grant (`code`) for this client. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). +- Enable the authorization code grant for this client. MCP requests `response_type=code`. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). - Add `/mcp/callback` to the Auth0 application’s allowed callback URLs. Use the external address where users reach the OpenMetadata MCP server, for example `https://catalog.example.com/mcp/callback`. $$ diff --git a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/awsCognitoSSOClientConfig.md b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/awsCognitoSSOClientConfig.md index 6e6b0c352939..a9f066343afd 100644 --- a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/awsCognitoSSOClientConfig.md +++ b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/awsCognitoSSOClientConfig.md @@ -57,7 +57,7 @@ $$section **MCP sign-in** -- Allow the authorization code grant (`code`) for this client. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). +- Enable the authorization code grant for this client. MCP requests `response_type=code`. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). - Add `/mcp/callback` to the Cognito app client’s allowed callback URLs. Use the external address where users reach the OpenMetadata MCP server, for example `https://catalog.example.com/mcp/callback`. $$ diff --git a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/azureSSOClientConfig.md b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/azureSSOClientConfig.md index 1c3cef48b22f..3a7692d501d3 100644 --- a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/azureSSOClientConfig.md +++ b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/azureSSOClientConfig.md @@ -57,7 +57,7 @@ $$section **MCP sign-in** -- Allow the authorization code grant (`code`) for this client. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). +- Enable the authorization code grant for this client. MCP requests `response_type=code`. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). - Add `/mcp/callback` to the redirect URIs in your Entra app registration. Use the external address where users reach the OpenMetadata MCP server, for example `https://catalog.example.com/mcp/callback`. - In **App registrations → your application → Authentication**, choose **Mobile and desktop applications** for an OpenMetadata **Public** client (S256 PKCE, no client secret), or **Web** for a **Confidential** client. A **Single-page application** redirect requires a browser token exchange. OpenMetadata redeems the MCP code on the server. [Microsoft redirect URI setup](https://learn.microsoft.com/en-us/entra/identity-platform/how-to-add-redirect-uri) $$ diff --git a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/customOidcSSOClientConfig.md b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/customOidcSSOClientConfig.md index e082c271e632..a4d7f13ecfee 100644 --- a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/customOidcSSOClientConfig.md +++ b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/customOidcSSOClientConfig.md @@ -44,7 +44,7 @@ $$section **MCP sign-in** -- Allow the authorization code grant (`code`) for this client. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). +- Enable the authorization code grant for this client. MCP requests `response_type=code`. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). - Add `/mcp/callback` to your provider’s allowed redirect URIs. Use the external address where users reach the OpenMetadata MCP server, for example `https://catalog.example.com/mcp/callback`. $$ diff --git a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/googleSSOClientConfig.md b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/googleSSOClientConfig.md index 9859a8fa1c7b..55205c3b38f9 100644 --- a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/googleSSOClientConfig.md +++ b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/googleSSOClientConfig.md @@ -67,7 +67,7 @@ $$section **MCP sign-in** -- Allow the authorization code grant (`code`) for this client. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). +- Enable the authorization code grant for this client. MCP requests `response_type=code`. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). - Add `/mcp/callback` to the Google OAuth client’s authorized redirect URIs. Use the external address where users reach the OpenMetadata MCP server, for example `https://catalog.example.com/mcp/callback`. - For a Google client that requires a secret to redeem the code, configure **Confidential** in OpenMetadata and supply the secret on the server. $$ diff --git a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/oktaSSOClientConfig.md b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/oktaSSOClientConfig.md index 18d32ec7771d..22becf74d034 100644 --- a/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/oktaSSOClientConfig.md +++ b/openmetadata-ui/src/main/resources/ui/public/locales/en-US/SSO/oktaSSOClientConfig.md @@ -57,7 +57,7 @@ $$section **MCP sign-in** -- Allow the authorization code grant (`code`) for this client. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). +- Enable the authorization code grant for this client. MCP requests `response_type=code`. Keep the existing browser redirect and its response type (the public web app defaults to `id_token`). - Add `/mcp/callback` to the Okta app integration’s sign-in redirect URIs. Use the external address where users reach the OpenMetadata MCP server, for example `https://catalog.example.com/mcp/callback`. $$