From 690e0d90cfa257f60d18b5afc666876a2bedbe13 Mon Sep 17 00:00:00 2001 From: Takashi Norimatsu Date: Fri, 20 Nov 2026 14:10:46 +0900 Subject: [PATCH] Keycloak 26.8.2 CIMD backchannel_logout_uri causes POST to loopback address Closes #55378 Signed-off-by: Takashi Norimatsu --- .../topics/changes/changes-27_0_0.adoc | 18 ++ .../securing-apps/mcp-authz-server.adoc | 7 +- ...tractClientIdMetadataDocumentExecutor.java | 88 ++++++++-- ...ientIdMetadataDocumentExecutorFactory.java | 12 +- .../ClientIdMetadataDocumentExecutorTest.java | 93 +++++++++++ .../ClientIdMetadataDocumentTest.java | 156 ++++++++++++++++++ 6 files changed, 350 insertions(+), 24 deletions(-) create mode 100644 services/src/test/java/org/keycloak/protocol/oauth2/cimd/clientpolicy/executor/ClientIdMetadataDocumentExecutorTest.java diff --git a/docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc b/docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc index d389e8891197..b3edcdbdc0bd 100644 --- a/docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc +++ b/docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc @@ -763,6 +763,24 @@ As a workaround, use the default value of a property that is not defined, for ex This did not work before, as the `$` prevented the placeholder from being closed. It only works as long as the property is not defined. +=== Client ID Metadata Document executor verifies the back-channel URLs of the client metadata +// https://github.com/keycloak/keycloak/issues/55378 + +The `client-id-metadata-document` client policy executor of the experimental Client ID Metadata Document feature now verifies the `backchannel_logout_uri` and `backchannel_client_notification_endpoint` properties of a client metadata document in the same way as the other URLs that {project_name} sends a request to, such as the `jwks_uri` property. +Their host must match one of the *Trusted domains* of the executor. +Their scheme must be `https` unless *Allow http scheme* is `ON`. +Their host must not resolve to a loopback, private, link-local, unique local or multicast address unless *Allow private-use addresses* is `ON`. +If *Restrict same domain* is `ON`, they must also be under the same trusted domain as the Client ID URL and the Redirect URI. + +An authorization request of a client whose metadata does not pass these checks is rejected. +This also applies to a client that was registered before the upgrade, because the URLs that {project_name} stored for it are checked on every authorization request. +If such a client is legitimate, add the host of these URLs to *Trusted domains*. + +{project_name} does not remove the URLs that it stored for a client before the upgrade, and it keeps sending back-channel logout requests and CIBA client notifications to them. +Therefore, review the clients that were registered through a Client ID Metadata Document before the upgrade, which are the clients whose client ID is the URL of the document. +Delete a client whose back-channel logout URL or CIBA client notification endpoint is a destination that {project_name} should not send requests to. +A deleted client is registered again from its client metadata document on its next authorization request. + // ------------------------ Deprecated features ------------------------ // == Deprecated features diff --git a/docs/guides/securing-apps/mcp-authz-server.adoc b/docs/guides/securing-apps/mcp-authz-server.adoc index 5dc1939ae7d3..926ee71f76d9 100644 --- a/docs/guides/securing-apps/mcp-authz-server.adoc +++ b/docs/guides/securing-apps/mcp-authz-server.adoc @@ -207,8 +207,11 @@ To configure the executor, create a client policy profile in the {project_name} . Click *Add executor* and select `client-id-metadata-document` from the list. . Configure the executor with the following options: + -* *Allow http scheme*: If `ON`, allows `http` scheme for the URLs that {project_name} fetches itself, that is the Client ID URL and the `jwks_uri`, `sector_identifier_uri` and `request_uris` properties of the client metadata. This should only be `ON` in a development environment and must be `OFF` in a production environment. -* *Allow private-use addresses*: If `OFF`, the executor rejects the URLs that {project_name} fetches itself, that is the Client ID URL and the `jwks_uri`, `sector_identifier_uri` and `request_uris` properties, when their host resolves to a loopback, private, link-local, unique local or multicast address. They are rejected even if their host matches one of the trusted domains, which prevents Server-Side Request Forgery (SSRF) against hosts that only {project_name} can reach. This should only be `ON` in a development environment and must be `OFF` in a production environment. +* *Allow http scheme*: If `ON`, allows `http` scheme for the URLs that {project_name} sends a request to itself, that is the Client ID URL and the `jwks_uri`, `sector_identifier_uri`, `request_uris`, `backchannel_logout_uri` and `backchannel_client_notification_endpoint` properties of the client metadata. This should only be `ON` in a development environment and must be `OFF` in a production environment. +* *Allow private-use addresses*: If `OFF`, the executor rejects the URLs that {project_name} sends a request to itself, that is the Client ID URL and the `jwks_uri`, `sector_identifier_uri`, `request_uris`, `backchannel_logout_uri` and `backchannel_client_notification_endpoint` properties, when their host resolves to a loopback, private, link-local, unique local or multicast address. They are rejected even if their host matches one of the trusted domains, which prevents Server-Side Request Forgery (SSRF) against hosts that only {project_name} can reach. This should only be `ON` in a development environment and must be `OFF` in a production environment. +The scheme and the address of these URLs are checked when {project_name} fetches the client metadata. +They are not checked again when {project_name} later sends a request to one of these URLs, so a host that resolves to a different address afterwards is not detected. +Therefore, only add domains whose owners and DNS records you trust to *Trusted domains*. * *Trusted domains*: A list of domain patterns (wildcard) that the executor accepts for the Client ID URL and Client Metadata URL properties. For example, use `*.example.org` to accept any subdomain of `example.org`. If empty, all domains are denied. * *Restrict same domain*: If `ON`, the executor verifies that the Client ID URL and Redirect URI in an authorization request, as well as URL-valued properties of the client metadata, are all under the same trusted domain. * *Required properties*: A list of client metadata properties that must be present in the Client ID Metadata Document. If the fetched document does not include all the listed properties, the request is rejected. diff --git a/services/src/main/java/org/keycloak/protocol/oauth2/cimd/clientpolicy/executor/AbstractClientIdMetadataDocumentExecutor.java b/services/src/main/java/org/keycloak/protocol/oauth2/cimd/clientpolicy/executor/AbstractClientIdMetadataDocumentExecutor.java index a8b10220f5cb..e33a34b5f635 100644 --- a/services/src/main/java/org/keycloak/protocol/oauth2/cimd/clientpolicy/executor/AbstractClientIdMetadataDocumentExecutor.java +++ b/services/src/main/java/org/keycloak/protocol/oauth2/cimd/clientpolicy/executor/AbstractClientIdMetadataDocumentExecutor.java @@ -25,12 +25,14 @@ import org.keycloak.http.simple.SimpleHttp; import org.keycloak.http.simple.SimpleHttpRequest; import org.keycloak.http.simple.SimpleHttpResponse; +import org.keycloak.models.CibaConfig; import org.keycloak.models.ClientModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.ProtocolMapperModel; import org.keycloak.models.RealmModel; import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.protocol.oauth2.cimd.provider.ClientIdMetadataDocumentProvider; +import org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper; import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.protocol.oidc.mappers.AudienceProtocolMapper; import org.keycloak.protocol.oidc.resourceindicators.ResourceIndicatorConstants; @@ -42,6 +44,7 @@ import org.keycloak.services.clientpolicy.context.PreAuthorizationRequestContext; import org.keycloak.services.clientpolicy.executor.ClientPolicyExecutorProvider; import org.keycloak.util.JsonSerialization; +import org.keycloak.utils.StringUtil; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; @@ -400,8 +403,10 @@ private void process(PreAuthorizationRequestContext preAuthorizationRequestConte validateClientId(clientIdURI); if (fetchOp == FetchOperation.NO_UPDATE) { - // no update, but the resource parameter still needs to be enforced on every authorization request. - enforceResourceIndicator(preAuthorizationRequestContext, session.getContext().getRealm().getClientByClientId(clientId)); + // no update, but the persisted client metadata and the resource parameter still need to be verified on every authorization request. + ClientModel clientModel = session.getContext().getRealm().getClientByClientId(clientId); + verifyPersistedClientMetadata(redirectUriURI, clientModel); + enforceResourceIndicator(preAuthorizationRequestContext, clientModel); return; } @@ -409,7 +414,9 @@ private void process(PreAuthorizationRequestContext preAuthorizationRequestConte OIDCClientRepresentationWithCacheControl clientOIDCWithCacheControl = fetchClientMetadata(clientIdURI, fetchOp == FetchOperation.UPDATE, provider); if (clientOIDCWithCacheControl == null) { // fetched but no update - enforceResourceIndicator(preAuthorizationRequestContext, session.getContext().getRealm().getClientByClientId(clientId)); + ClientModel clientModel = session.getContext().getRealm().getClientByClientId(clientId); + verifyPersistedClientMetadata(redirectUriURI, clientModel); + enforceResourceIndicator(preAuthorizationRequestContext, clientModel); return; } @@ -428,6 +435,8 @@ private void process(PreAuthorizationRequestContext preAuthorizationRequestConte clientModel = provider.updateClientMetadata(clientOIDCWithCacheControl); } + // an update does not remove every property that the fetched client metadata no longer includes + verifyPersistedClientMetadata(redirectUriURI, clientModel); enforceResourceIndicator(preAuthorizationRequestContext, clientModel); } @@ -739,6 +748,8 @@ protected URI verifyClientMetadata(final URI clientIdURI, final URI redirectUriU // RFC 7591 (optional): logo_uri, client_uri, tos_uri, policy_uri, jwks_uri // OIDC Dynamic Client Registration (optional): sector_identifier_uri, request_uris, fetched by the // authorization server after the registration + // OIDC Back-Channel Logout (optional): backchannel_logout_uri, CIBA (optional): backchannel_client_notification_endpoint, + // which the authorization server sends a request to after the registration List trustedDomains = convertContentFilledList(getConfiguration().getTrustedDomains()); verifyUriProperty(clientOIDC.getClientId(), "client_id", trustedDomains); @@ -759,6 +770,9 @@ protected URI verifyClientMetadata(final URI clientIdURI, final URI redirectUriU verifyFetchedUriProperty(requestUri, "request_uris", trustedDomains); } + verifyRequestedUriProperty(clientOIDC.getBackchannelLogoutUri(), "backchannel_logout_uri", trustedDomains); + verifyRequestedUriProperty(clientOIDC.getBackchannelClientNotificationEndpoint(), "backchannel_client_notification_endpoint", trustedDomains); + URI clientIdURIfromMetadata; try { clientIdURIfromMetadata = new URI(clientOIDC.getClientId()); @@ -771,6 +785,46 @@ protected URI verifyClientMetadata(final URI clientIdURI, final URI redirectUriU return clientIdURIfromMetadata; } + /** + * Verifies and validates the URLs of a persisted client metadata that the authorization server sends a request to, + * in the same way as the ones of a fetched client metadata. + * It is done on every authorization request, because the persisted client metadata is used whether it was fetched + * for the request or not, and it can have been persisted before the configuration of the executor changed. + * + * @param redirectUriURI a value of {redirect_uri} parameter of an authorization request in {@link URI} + * @param clientModel a persisted client metadata + * @throws ClientPolicyException when verifying or validating a persisted client metadata fails. + */ + protected void verifyPersistedClientMetadata(final URI redirectUriURI, final ClientModel clientModel) throws ClientPolicyException { + List trustedDomains = convertContentFilledList(getConfiguration().getTrustedDomains()); + String backchannelLogoutUrl = OIDCAdvancedConfigWrapper.fromClientModel(clientModel).getBackchannelLogoutUrl(); + String backchannelClientNotificationEndpoint = clientModel.getAttribute(CibaConfig.CIBA_BACKCHANNEL_CLIENT_NOTIFICATION_ENDPOINT); + verifyRequestedUriProperty(backchannelLogoutUrl, "backchannel_logout_uri", trustedDomains); + verifyRequestedUriProperty(backchannelClientNotificationEndpoint, "backchannel_client_notification_endpoint", trustedDomains); + + if (getConfiguration().isRestrictSameDomain()) { + List l = Stream.of(backchannelLogoutUrl, backchannelClientNotificationEndpoint).filter(StringUtil::isNotBlank).toList(); + validateSameDomain(l, redirectUriURI, trustedDomains); + } + } + + // same domain policy: the URIs have to be under the same trusted domain as the redirect_uri parameter + private void validateSameDomain(List uris, URI redirectUriURI, List trustedDomains) throws ClientPolicyException { + String redirectUriHost = redirectUriURI.getHost(); + try { + for (String s : uris) { + URI u = new URI(s); + if (redirectUriHost == null || trustedDomains.stream().noneMatch(i -> checkTrustedDomain(u.getHost(), i) && checkTrustedDomain(redirectUriHost, i))) { + getLogger().warnv("not under the same domain = {0}", u.getHost()); + throw invalidClientIdMetadata(ERR_METADATA_NO_ALL_URIS_SAMEDOMAIN); + } + } + } catch (URISyntaxException e) { + getLogger().warnv("URI not resolved {0}}", e); + throw invalidClientIdMetadata(ERR_METADATA_NO_ALL_URIS_SAMEDOMAIN); + } + } + private void verifyUriProperty(String uriString, String propertyName, List trustedDomains) throws ClientPolicyException { verifyUri(uriString, trustedDomains, false, (error, logMessageTemplate) -> { getLogger().warnv(logMessageTemplate, propertyName, uriString); @@ -789,6 +843,13 @@ private void verifyFetchedUriProperty(String uriString, String propertyName, Lis }); } + // for a property whose URL the authorization server sends a request to itself, which it does not do for a blank one + private void verifyRequestedUriProperty(String uriString, String propertyName, List trustedDomains) throws ClientPolicyException { + if (StringUtil.isNotBlank(uriString)) { + verifyFetchedUriProperty(uriString, propertyName, trustedDomains); + } + } + private void verifyUriPropertyIfPresent(String uriString, String propertyName, List trustedDomains) throws ClientPolicyException { if (uriString != null) { verifyUriProperty(uriString, propertyName, trustedDomains); @@ -888,7 +949,8 @@ protected void validateClientMetadata(final URI clientIdURI, final URI redirectU // An authorization server MAY impose restrictions or relationships // between the redirect_uris and the client_id or client_uri properties - // same domain policy: client_id, redirect_uri, redirect_uris, client_uri, logo_uri, tos_uri,, policy_uri, jwks_uri + // same domain policy: client_id, redirect_uri, redirect_uris, client_uri, logo_uri, tos_uri,, policy_uri, jwks_uri, + // backchannel_logout_uri, backchannel_client_notification_endpoint List trustedDomains = convertContentFilledList(getConfiguration().getTrustedDomains()); if (getConfiguration().isRestrictSameDomain() && trustedDomains != null && !trustedDomains.isEmpty()) { // Client Metadata verification ensures that @@ -900,20 +962,10 @@ protected void validateClientMetadata(final URI clientIdURI, final URI redirectU throw invalidClientIdMetadata(ERR_METADATA_URIS_SAMEDOMAIN); } - List l = Stream.of(clientOIDC.getClientId(), clientOIDC.getClientUri(), clientOIDC.getLogoUri(), clientOIDC.getTosUri(), clientOIDC.getPolicyUri(), clientOIDC.getJwksUri()) - .filter(Objects::nonNull).toList(); - try { - for (String s : l) { - URI u = new URI(s); - if (trustedDomains.stream().filter(i->!i.isBlank()).noneMatch(i -> checkTrustedDomain(u.getHost(), i) && checkTrustedDomain(redirectUriURI.getHost(), i))) { - getLogger().warnv("not under the same domain = {0}", u.getHost()); - throw invalidClientIdMetadata(ERR_METADATA_NO_ALL_URIS_SAMEDOMAIN); - } - } - } catch (URISyntaxException e) { - getLogger().warnv("URI not resolved {0}}", e); - throw invalidClientIdMetadata(ERR_METADATA_NO_ALL_URIS_SAMEDOMAIN); - } + List l = Stream.of(clientOIDC.getClientId(), clientOIDC.getClientUri(), clientOIDC.getLogoUri(), clientOIDC.getTosUri(), clientOIDC.getPolicyUri(), clientOIDC.getJwksUri(), + clientOIDC.getBackchannelLogoutUri(), clientOIDC.getBackchannelClientNotificationEndpoint()) + .filter(StringUtil::isNotBlank).toList(); + validateSameDomain(l, redirectUriURI, trustedDomains); } // required properties policy diff --git a/services/src/main/java/org/keycloak/protocol/oauth2/cimd/clientpolicy/executor/AbstractClientIdMetadataDocumentExecutorFactory.java b/services/src/main/java/org/keycloak/protocol/oauth2/cimd/clientpolicy/executor/AbstractClientIdMetadataDocumentExecutorFactory.java index 4c701648a1c3..27bab3651323 100644 --- a/services/src/main/java/org/keycloak/protocol/oauth2/cimd/clientpolicy/executor/AbstractClientIdMetadataDocumentExecutorFactory.java +++ b/services/src/main/java/org/keycloak/protocol/oauth2/cimd/clientpolicy/executor/AbstractClientIdMetadataDocumentExecutorFactory.java @@ -84,7 +84,9 @@ static protected void addCommonConfigProperties(List con ProviderConfigProperty property = new ProviderConfigProperty( ALLOW_HTTP_SCHEME, "Allow http scheme", - "If ON, then the executor allows http scheme as a valid Client ID URL and property of Client Metadata whose value is URL: client_uri, logo_uri, tos_uri, policy_uri, jwks_uri. " + + "If ON, then the executor allows http scheme for a URL that the server sends a request to itself, namely the Client ID URL and the " + + "jwks_uri, sector_identifier_uri, request_uris, backchannel_logout_uri and backchannel_client_notification_endpoint " + + "properties of Client Metadata. " + "It can be ON only for development environment. It must be OFF in production environment. ", ProviderConfigProperty.BOOLEAN_TYPE, false); @@ -93,8 +95,9 @@ static protected void addCommonConfigProperties(List con property = new ProviderConfigProperty( ALLOW_PRIVATE_USE_ADDRESSES, "Allow private-use addresses", - "If OFF, then the executor rejects a URL that the server fetches itself, namely the Client ID URL and the " + - "jwks_uri, sector_identifier_uri and request_uris properties of Client Metadata, whose host resolves to a " + + "If OFF, then the executor rejects a URL that the server sends a request to itself, namely the Client ID URL and the " + + "jwks_uri, sector_identifier_uri, request_uris, backchannel_logout_uri and backchannel_client_notification_endpoint " + + "properties of Client Metadata, whose host resolves to a " + "loopback, private, link-local, unique local or multicast address. Such URLs are rejected even if their host " + "matches one of the trusted domains, which prevents Server-Side Request Forgery (SSRF) against hosts only " + "reachable from the server. It can be ON only for development environment. It must be OFF in production environment.", @@ -108,7 +111,8 @@ static protected void addCommonConfigProperties(List con "Trusted domains", "If some domains are filled, the executor only accepts the following URL-formatted parameters whose host part matches one of the filled domains: " + "Authorization request parameters: client_id, redirect_uri, " + - "Client metadata properties: client_id, redirect_uris, jwks_uri, logo_uri, policy_uri, tos_uri, client_uri, sector_identifier_uri, request_uris. " + + "Client metadata properties: client_id, redirect_uris, jwks_uri, logo_uri, policy_uri, tos_uri, client_uri, sector_identifier_uri, request_uris, " + + "backchannel_logout_uri, backchannel_client_notification_endpoint. " + "The domains are checked by using wildcard pattern matching (e.g. '*.example.org'). " + "If the domains not filled, the executor denies all such the parameters and properties. " + "For example, use pattern like '*.example.org' if you want to accept the parameter / property whose domain is 'example.org' or its subdomains.", diff --git a/services/src/test/java/org/keycloak/protocol/oauth2/cimd/clientpolicy/executor/ClientIdMetadataDocumentExecutorTest.java b/services/src/test/java/org/keycloak/protocol/oauth2/cimd/clientpolicy/executor/ClientIdMetadataDocumentExecutorTest.java new file mode 100644 index 000000000000..b96e55b0a139 --- /dev/null +++ b/services/src/test/java/org/keycloak/protocol/oauth2/cimd/clientpolicy/executor/ClientIdMetadataDocumentExecutorTest.java @@ -0,0 +1,93 @@ +package org.keycloak.protocol.oauth2.cimd.clientpolicy.executor; + +import java.net.URI; +import java.util.List; +import java.util.function.BiConsumer; + +import org.keycloak.common.Profile; +import org.keycloak.common.crypto.CryptoIntegration; +import org.keycloak.common.crypto.CryptoProvider; +import org.keycloak.http.HttpRequest; +import org.keycloak.models.KeycloakSession; +import org.keycloak.representations.oidc.OIDCClientRepresentation; +import org.keycloak.services.clientpolicy.ClientPolicyException; +import org.keycloak.services.resteasy.HttpRequestImpl; +import org.keycloak.services.resteasy.ResteasyKeycloakSession; +import org.keycloak.services.resteasy.ResteasyKeycloakSessionFactory; + +import org.jboss.resteasy.mock.MockHttpRequest; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +public class ClientIdMetadataDocumentExecutorTest { + + private static final URI CLIENT_ID = URI.create("https://client.example.com/metadata"); + private static final URI REDIRECT_URI = URI.create("https://client.example.com/callback"); + + private static KeycloakSession session; + + private ClientIdMetadataDocumentExecutor executor; + private ClientIdMetadataDocumentExecutor.Configuration configuration; + private OIDCClientRepresentation clientMetadata; + + @BeforeClass + public static void beforeClass() throws Exception { + HttpRequest httpRequest = new HttpRequestImpl(MockHttpRequest.create("GET", URI.create("https://keycloak.org/"), URI.create("https://keycloak.org"))); + Profile.defaults(); + CryptoIntegration.init(CryptoProvider.class.getClassLoader()); + ResteasyKeycloakSessionFactory sessionFactory = new ResteasyKeycloakSessionFactory(); + sessionFactory.init(); + session = new ResteasyKeycloakSession(sessionFactory); + session.getContext().setHttpRequest(httpRequest); + } + + @Before + public void before() { + // neither the http scheme nor a private-use address is allowed by default + configuration = new ClientIdMetadataDocumentExecutor.Configuration(); + configuration.setTrustedDomains(List.of("client.example.com", "localhost", "127.0.0.1")); + executor = new ClientIdMetadataDocumentExecutor(session, null); + executor.setupConfiguration(configuration); + + clientMetadata = new OIDCClientRepresentation(); + clientMetadata.setClientId(CLIENT_ID.toString()); + clientMetadata.setRedirectUris(List.of(REDIRECT_URI.toString())); + } + + @Test + public void backchannelLogoutUriIsVerifiedAsServerRequestedUrl() throws Exception { + assertVerifiedAsServerRequestedUrl(OIDCClientRepresentation::setBackchannelLogoutUri); + } + + @Test + public void backchannelClientNotificationEndpointIsVerifiedAsServerRequestedUrl() throws Exception { + assertVerifiedAsServerRequestedUrl(OIDCClientRepresentation::setBackchannelClientNotificationEndpoint); + } + + private void assertVerifiedAsServerRequestedUrl(BiConsumer property) throws Exception { + property.accept(clientMetadata, "http://127.0.0.1:19080/capture"); + assertRejected(AbstractClientIdMetadataDocumentExecutor.ERR_INVALID_SCHEME); + + property.accept(clientMetadata, "https://127.0.0.1:19080/capture"); + assertRejected(AbstractClientIdMetadataDocumentExecutor.ERR_NOTALLOWED_ADDRESS); + + // a trusted host that resolves to a loopback address + property.accept(clientMetadata, "https://localhost/capture"); + assertRejected(AbstractClientIdMetadataDocumentExecutor.ERR_NOTALLOWED_ADDRESS); + + configuration.setAllowHttpScheme(true); + configuration.setAllowPrivateUseAddresses(true); + property.accept(clientMetadata, "http://127.0.0.1:19080/capture"); + executor.verifyClientMetadata(CLIENT_ID, REDIRECT_URI, clientMetadata); + } + + private void assertRejected(String errorDetail) { + ClientPolicyException e = assertThrows(ClientPolicyException.class, + () -> executor.verifyClientMetadata(CLIENT_ID, REDIRECT_URI, clientMetadata)); + assertEquals(errorDetail, e.getErrorDetail()); + } +} diff --git a/tests/base/src/test/java/org/keycloak/tests/client/policies/ClientIdMetadataDocumentTest.java b/tests/base/src/test/java/org/keycloak/tests/client/policies/ClientIdMetadataDocumentTest.java index ed1a25a4c845..e8c93ff7c9ae 100644 --- a/tests/base/src/test/java/org/keycloak/tests/client/policies/ClientIdMetadataDocumentTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/client/policies/ClientIdMetadataDocumentTest.java @@ -1197,6 +1197,148 @@ public void testClientIdMetadataDocumentExecutorVerifyClientMetadata() throws Ex cimd.getRepresentation().setRequestUris(null); } + @Test + public void testClientIdMetadataDocumentExecutorVerifyBackchannelUris() throws Exception { + // register profiles: the trusted domains are *.example.com and localhost + updatePolicy(createDefaultConditionConfig(), createDefaultExecutorConfig()); + + oauth.redirectUri(REDIRECT_URI); + setCimdPublicClient(); + String untrustedUri = "http://127.0.0.1:19080/capture"; + String invalidSchemeUri = "ftp://localhost:8500/backchannel"; + String trustedLogoutUri = "http://localhost:8500/backchannel-logout"; + String trustedNotificationEndpoint = "http://localhost:8500/ciba-notification"; + + try { + // backchannel_logout_uri : not allowed domain + cimd.getRepresentation().setBackchannelLogoutUri(untrustedUri); + assertLoginAndError(AbstractClientIdMetadataDocumentExecutor.ERR_NOTALLOWED_DOMAIN); + + // backchannel_logout_uri : not allowed scheme + cimd.getRepresentation().setBackchannelLogoutUri(invalidSchemeUri); + assertLoginAndError(AbstractClientIdMetadataDocumentExecutor.ERR_INVALID_SCHEME); + + // backchannel_client_notification_endpoint : not allowed domain + cimd.getRepresentation().setBackchannelLogoutUri(null); + cimd.getRepresentation().setBackchannelClientNotificationEndpoint(untrustedUri); + assertLoginAndError(AbstractClientIdMetadataDocumentExecutor.ERR_NOTALLOWED_DOMAIN); + + // backchannel_client_notification_endpoint : not allowed scheme + cimd.getRepresentation().setBackchannelClientNotificationEndpoint(invalidSchemeUri); + assertLoginAndError(AbstractClientIdMetadataDocumentExecutor.ERR_INVALID_SCHEME); + + // no client metadata was persisted + Assertions.assertTrue(realm.admin().clients().findByClientId(CLIENT_ID).isEmpty()); + + // a blank value is handled in the same way as an absent one + cimd.getRepresentation().setBackchannelLogoutUri(""); + cimd.getRepresentation().setBackchannelClientNotificationEndpoint(""); + String code = loginUserAndGetCode(true); + AccessTokenResponse tokenResponse = oauth.client(CLIENT_ID).accessTokenRequest(code).send(); + Assertions.assertEquals(200, tokenResponse.getStatusCode()); + logout(tokenResponse.getIdToken()); + + // both under a trusted domain + cimd.getRepresentation().setBackchannelLogoutUri(trustedLogoutUri); + cimd.getRepresentation().setBackchannelClientNotificationEndpoint(trustedNotificationEndpoint); + timeOffSet.set(CIMD_EXECUTOR_MIN_CACHE_TIME_SEC + 3); + code = loginUserAndGetCode(false); + tokenResponse = oauth.client(CLIENT_ID).accessTokenRequest(code).send(); + Assertions.assertEquals(200, tokenResponse.getStatusCode()); + + Map attrs = findByClientIdByAdmin().getAttributes(); + Assertions.assertEquals(trustedLogoutUri, attrs.get(OIDCConfigAttributes.BACKCHANNEL_LOGOUT_URL)); + Assertions.assertEquals(trustedNotificationEndpoint, attrs.get(CibaConfig.CIBA_BACKCHANNEL_CLIENT_NOTIFICATION_ENDPOINT)); + + logout(tokenResponse.getIdToken()); + + // the re-fetched client metadata is verified as well, and the persisted one remains the same + cimd.getRepresentation().setBackchannelLogoutUri(untrustedUri); + timeOffSet.set(2 * (CIMD_EXECUTOR_MIN_CACHE_TIME_SEC + 3)); + assertLoginAndError(AbstractClientIdMetadataDocumentExecutor.ERR_NOTALLOWED_DOMAIN); + Assertions.assertEquals(trustedLogoutUri, findByClientIdByAdmin().getAttributes().get(OIDCConfigAttributes.BACKCHANNEL_LOGOUT_URL)); + } finally { + realm.admin().clients().findByClientId(CLIENT_ID).forEach(client -> deleteClientByAdmin(client.getId())); + } + } + + @Test + public void testClientIdMetadataDocumentExecutorVerifyPersistedBackchannelUris() throws Exception { + // register profiles: the trusted domains are *.example.com and localhost + updatePolicy(createDefaultConditionConfig(), createDefaultExecutorConfig()); + + oauth.redirectUri(REDIRECT_URI); + setCimdPublicClient(); + String untrustedUri = "http://127.0.0.1:19080/capture"; + + try { + String code = loginUserAndGetCode(true); + AccessTokenResponse tokenResponse = oauth.client(CLIENT_ID).accessTokenRequest(code).send(); + Assertions.assertEquals(200, tokenResponse.getStatusCode()); + logout(tokenResponse.getIdToken()); + + // the persisted client metadata holds a URL that was not verified when it was registered + ClientRepresentation clientRepresentation = findByClientIdByAdmin(); + clientRepresentation.getAttributes().put(OIDCConfigAttributes.BACKCHANNEL_LOGOUT_URL, untrustedUri); + realm.admin().clients().get(clientRepresentation.getId()).update(clientRepresentation); + + // the persisted client metadata is still effective, so it is not fetched but verified + assertLoginAndError(AbstractClientIdMetadataDocumentExecutor.ERR_NOTALLOWED_DOMAIN); + + // the re-fetched client metadata is not modified, so the persisted one stays in use and is verified + cimd.setStatus(Response.Status.NOT_MODIFIED); + timeOffSet.set(CIMD_EXECUTOR_MIN_CACHE_TIME_SEC + 3); + assertLoginAndError(AbstractClientIdMetadataDocumentExecutor.ERR_NOTALLOWED_DOMAIN); + + // the re-fetched client metadata no longer includes the properties, but the update keeps the persisted endpoint + clientRepresentation.getAttributes().put(OIDCConfigAttributes.BACKCHANNEL_LOGOUT_URL, "http://localhost:8500/backchannel-logout"); + clientRepresentation.getAttributes().put(CibaConfig.CIBA_BACKCHANNEL_CLIENT_NOTIFICATION_ENDPOINT, untrustedUri); + realm.admin().clients().get(clientRepresentation.getId()).update(clientRepresentation); + cimd.setStatus(Response.Status.OK); + assertLoginAndError(AbstractClientIdMetadataDocumentExecutor.ERR_NOTALLOWED_DOMAIN); + } finally { + realm.admin().clients().findByClientId(CLIENT_ID).forEach(client -> deleteClientByAdmin(client.getId())); + } + } + + @Test + public void testClientIdMetadataDocumentExecutorValidatePersistedBackchannelUrisRestrictSameDomain() throws Exception { + // register profiles: the trusted domains are *.example.com and localhost, and the same domain is not required + ClientIdUriSchemeCondition.Configuration conditionConfig = createDefaultConditionConfig(); + ClientIdMetadataDocumentExecutor.Configuration executorConfig = createDefaultExecutorConfig(); + updatePolicy(conditionConfig, executorConfig); + + oauth.redirectUri(REDIRECT_URI); + setCimdPublicClient(); + cimd.getRepresentation().setBackchannelClientNotificationEndpoint("https://www.example.com/ciba-notification"); + + try { + String code = loginUserAndGetCode(true); + AccessTokenResponse tokenResponse = oauth.client(CLIENT_ID).accessTokenRequest(code).send(); + Assertions.assertEquals(200, tokenResponse.getStatusCode()); + logout(tokenResponse.getIdToken()); + + // the same domain is required after the client metadata was persisted + executorConfig.setRestrictSameDomain(true); + updatePolicy(conditionConfig, executorConfig); + + // the persisted client metadata is still effective, so it is not fetched but validated + assertLoginAndError(AbstractClientIdMetadataDocumentExecutor.ERR_METADATA_NO_ALL_URIS_SAMEDOMAIN); + + // the re-fetched client metadata is not modified, so the persisted one stays in use and is validated + cimd.setStatus(Response.Status.NOT_MODIFIED); + timeOffSet.set(CIMD_EXECUTOR_MIN_CACHE_TIME_SEC + 3); + assertLoginAndError(AbstractClientIdMetadataDocumentExecutor.ERR_METADATA_NO_ALL_URIS_SAMEDOMAIN); + + // the re-fetched client metadata no longer includes the property, but the update keeps the persisted endpoint + cimd.getRepresentation().setBackchannelClientNotificationEndpoint(null); + cimd.setStatus(Response.Status.OK); + assertLoginAndError(AbstractClientIdMetadataDocumentExecutor.ERR_METADATA_NO_ALL_URIS_SAMEDOMAIN); + } finally { + realm.admin().clients().findByClientId(CLIENT_ID).forEach(client -> deleteClientByAdmin(client.getId())); + } + } + @Test public void testClientIdMetadataDocumentExecutorTrustedSectorIdentifierUri() throws Exception { // register profiles @@ -1427,6 +1569,20 @@ public void testClientIdMetadataDocumentExecutorValidateClientMetadataRestrictSa cimd.getRepresentation().setTosUri("https://www.example.co.jp/mcp"); cimd.getRepresentation().setPolicyUri("https://localhost/mcp"); assertLoginAndError(ClientIdMetadataDocumentExecutor.ERR_METADATA_NO_ALL_URIS_SAMEDOMAIN); + + // backchannel_logout_uri and backchannel_client_notification_endpoint are under the same domain as well + cimd.getRepresentation().setClientUri("http://localhost:8500"); + cimd.getRepresentation().setTosUri("https://localhost:8500/tos"); + try { + cimd.getRepresentation().setBackchannelLogoutUri("https://www.example.com/backchannel-logout"); + assertLoginAndError(ClientIdMetadataDocumentExecutor.ERR_METADATA_NO_ALL_URIS_SAMEDOMAIN); + + cimd.getRepresentation().setBackchannelLogoutUri(null); + cimd.getRepresentation().setBackchannelClientNotificationEndpoint("https://www.example.com/ciba-notification"); + assertLoginAndError(ClientIdMetadataDocumentExecutor.ERR_METADATA_NO_ALL_URIS_SAMEDOMAIN); + } finally { + realm.admin().clients().findByClientId(CLIENT_ID).forEach(client -> deleteClientByAdmin(client.getId())); + } } @Test