8000 Re-validate stored client URIs on partial client updates by graziang · Pull Request #55232 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,11 @@ The Secure Client URIs executor resolves `+` in web origins and post-logout redi
The Secure Client URIs Pattern executor matches configured values literally, including `+`, `-`, and `*`, in the configured field order.
Include patterns for these literal values when your policy allows them. Selected attributes are checked regardless of the client's protocol.

On update, both executors check the client state that results from the request.
A URI field the request does not include keeps its stored value and is checked again, so an update fails while the client still holds a non-compliant URI.
Submit a compliant value for that field, or an empty value to remove it, to update such a client.
When a client holds no web origin of its own, the origins derived from its redirect URIs are checked, on registration as well, as those are the origins that get persisted.

The sector identifier URL stored in a pairwise protocol mapper is validated separately and is outside this catalog.

The *Allow IPv4 loopback address* and *Allow IPv6 loopback address* options of *Secure Redirect URIs Enforcer* apply only to literal IP addresses.
Expand Down
17 changes: 17 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,23 @@ General validation also preserves the legacy web origin literals `${authAdminUrl
Trusted Hosts resolves relative logo URLs against the {project_name} frontend URL and checks that host against its allowlist. The client's root URL does not determine where the browser loads a logo.
The pattern executor continues to match literal configured values, including markers and relative URLs, and respects an explicit field selection. Sector identifier URLs in pairwise protocol mappers remain subject to their separate validation.

=== Secure client URI executors validate the stored client on update
// https://github.com/keycloak/keycloak/issues/53952

The *Secure Client URIs* and *Secure Client URIs Pattern* executors now validate the client state that the update produces, instead of the submitted representation alone.
A URI field that the update payload does not carry keeps its stored value, so that value is checked again.

A partial update therefore fails when the client still holds a non-compliant URI, even when the update does not touch that field.
This situation occurs for clients registered before the policy was enabled.
Correct those URIs, or submit them with compliant values in the same update, before updating such clients.

A field submitted with an empty value is cleared and is no longer checked, so an update can remove a non-compliant URI.

Web origins follow the same fallback as persistence.
A client that holds no web origin of its own has the origins of its redirect URIs persisted, so those derived origins are now validated too, both on registration and on update.
A request that only sets redirect URIs can therefore be rejected by a policy that selects `webOrigins`.
Apart from those derived origins, client registration is unchanged, because no stored client exists to merge with.

=== Login theme moved to `keycloak.v3` and PatternFly 6
// https://github.com/keycloak/keycloak/issues/52342

Expand Down
8000
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.util.Locale;

import org.keycloak.OAuthErrorException;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.protocol.oidc.utils.RedirectUtils;
import org.keycloak.representations.idm.ClientPolicyExecutorConfigurationRepresentation;
Expand Down Expand Up @@ -77,7 +78,7 @@ public void executeOnEvent(ClientPolicyContext context) throws ClientPolicyExcep
case REGISTER:
if (context instanceof AdminClientRegisterContext || context instanceof DynamicClientRegisterContext) {
ClientRepresentation clientRep = ((ClientCRUDContext)context).getProposedClientRepresentation();
confirmSecureUris(clientRep);
confirmSecureUris(clientRep, null);

// Use rootUrl as default redirectUrl to avoid creation of redirectUris with wildcards, which is done at later stages during client creation
if (clientRep.getRootUrl() != null && (clientRep.getRedirectUris() == null || clientRep.getRedirectUris().isEmpty())) {
Expand All @@ -90,7 +91,8 @@ public void executeOnEvent(ClientPolicyContext context) throws ClientPolicyExcep
return;
case UPDATE:
if (context instanceof AdminClientUpdateContext || context instanceof DynamicClientUpdateContext) {
confirmSecureUris(((ClientCRUDContext) context).getProposedClientRepresentation());
ClientCRUDContext crudContext = (ClientCRUDContext) context;
confirmSecureUris(crudContext.getProposedClientRepresentation(), crudContext.getTargetClient());
} else {
throw new ClientPolicyException(OAuthErrorException.INVALID_REQUEST, "not allowed input format.");
}
Expand All @@ -102,14 +104,17 @@ public void executeOnEvent(ClientPolicyContext context) throws ClientPolicyExcep
}
}

private void confirmSecureUris(ClientRepresentation clientRep) throws ClientPolicyException {
ClientUriField.validate(clientRep, (field, values) -> {
private void confirmSecureUris(ClientRepresentation clientRep, ClientModel storedClient) throws ClientPolicyException {
String rootUrl = ClientUriField.ROOT_URL.getValues(clientRep, storedClient).stream().findFirst().orElse(null);
List<String> redirectUris = ClientUriField.REDIRECT_URIS.getValues(clientRep, storedClient);

ClientUriField.validate(clientRep, storedClient, (field, values) -> {
if (field == ClientUriField.WEB_ORIGINS || field == ClientUriField.POST_LOGOUT_REDIRECT_URIS) {
if (field == ClientUriField.POST_LOGOUT_REDIRECT_URIS) {
values = values.stream().filter(value -> !"-".equals(value)).toList();
}
values = List.copyOf(RedirectUtils.resolveUrlsWithRedirects(session, values, clientRep.getRootUrl(),
clientRep.getRedirectUris(), field == ClientUriField.WEB_ORIGINS));
values = List.copyOf(RedirectUtils.resolveUrlsWithRedirects(session, values, rootUrl,
redirectUris, field == ClientUriField.WEB_ORIGINS));
}
String errorName = switch (field) {
case BACKCHANNEL_LOGOUT_URL -> "logoutUrl";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.regex.PatternSyntaxException;

import org.keycloak.OAuthErrorException;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.representations.idm.ClientPolicyExecutorConfigurationRepresentation;
import org.keycloak.representations.idm.ClientRepresentation;
Expand Down Expand Up @@ -123,14 +124,15 @@ public void executeOnEvent(ClientPolicyContext context) throws ClientPolicyExcep
case REGISTER:
if (context instanceof AdminClientRegisterContext || context instanceof DynamicClientRegisterContext) {
ClientRepresentation clientRep = ((ClientCRUDContext)context).getProposedClientRepresentation();
validateClientUris(clientRep);
validateClientUris(clientRep, null);
} else {
throw new ClientPolicyException(OAuthErrorException.INVALID_REQUEST, "not allowed input format.");
}
return;
case UPDATE:
if (context instanceof AdminClientUpdateContext || context instanceof DynamicClientUpdateContext) {
validateClientUris(((ClientCRUDContext)context).getProposedClientRepresentation());
ClientCRUDContext crudContext = (ClientCRUDContext) context;
validateClientUris(crudContext.getProposedClientRepresentation(), crudContext.getTargetClient());
} else {
throw new ClientPolicyException(OAuthErrorException.INVALID_REQUEST, "not allowed input format.");
}
Expand All @@ -139,13 +141,14 @@ public void executeOnEvent(ClientPolicyContext context) throws ClientPolicyExcep
}
}

private void validateClientUris(ClientRepresentation clientRep) throws ClientPolicyException {
private void validateClientUris(ClientRepresentation clientRep, ClientModel storedClient) throws ClientPolicyException {
//skip validation if empty
if (clientUriFields == null || clientUriFields.isEmpty()) {
return;
}

ClientUriField.validate(clientRep, clientUriFields, (field, values) -> confirmSecureUris(values, field.getName()));
ClientUriField.validate(clientRep, storedClient, clientUriFields,
(field, values) -> confirmSecureUris(values, field.getName()));
}

private void confirmSecureUris(List<String> uris, String uriType) throws ClientPolicyException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.List;
import java.util.Optional;

import org.keycloak.common.util.UriUtils;
import org.keycloak.models.CibaConfig;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants;
Expand Down Expand Up @@ -241,19 +242,24 @@ public interface Validator<E extends Exception> {
}

public static <E extends Exception> void validate(ClientRepresentation client, Validator<E> validator) throws E {
validate(client, List.of(values()), validator);
validate(client, null, validator);
}

public static <E extends Exception> void validate(ClientRepresentation client, List<ClientUriField> fields,
Validator<E> validator) throws E {
for (ClientUriField field : fields) {
public static <E extends Exception> void validate(ClientModel client, Validator<E> validator) throws E {
for (ClientUriField field : values()) {
validator.validate(field, field.getValues(client));
}
}

public static <E extends Exception> void validate(ClientModel client, Validator<E> validator) throws E {
for (ClientUriField field : values()) {
validator.validate(field, field.getValues(client));
public static <E extends Exception> void validate(ClientRepresentation proposed, ClientModel stored,
Validator<E> validator) throws E {
validate(proposed, stored, List.of(values()), validator);
}

public static <E extends Exception> void validate(ClientRepresentation proposed, ClientModel stored,
List<ClientUriField> fields, Validator<E> validator) throws E {
for (ClientUriField field : fields) {
validator.validate(field, field.getValues(proposed, stored));
}
}

Expand All @@ -279,6 +285,34 @@ public List<String> getValues(ClientModel client) {
};
}

/**
* Effective values after the request, mirroring {@code RepresentationToModel.updateClientProperties}.
* A field the request does not carry keeps the value of the stored client, which is null on registration.
*/
public List<String> getValues(ClientRepresentation proposed, ClientModel stored) {
if (isSetIn(proposed)) {
return getValues(proposed);
}
List<String> values = stored == null ? List.of() : getValues(stored);
// persistence falls back to defaultWebOrigins, which derives origins from the effective redirect URIs
return this == WEB_ORIGINS && values.isEmpty() ? defaultWebOrigins(REDIRECT_URIS.getValues(proposed, stored)) : values;
}

private static List<String> defaultWebOrigins(List<String> redirectUris) {
return redirectUris.stream().filter(uri -> uri.startsWith("http")).map(UriUtils::getOrigin).distinct().toList();
}

private boolean isSetIn(ClientRepresentation client) {
return switch (source) {
case ROOT -> client.getRootUrl() != null;
case ADMIN -> client.getAdminUrl() != null;
case BASE -> client.getBaseUrl() != null;
case REDIRECTS -> client.getRedirectUris() != null;
case ORIGINS -> client.getWebOrigins() != null;
case ATTRIBUTE, MULTIVALUED -> client.getAttributes() != null && client.getAttributes().containsKey(attribute);
};
}

private List<String> attributeValues(String value) {
return source == Source.MULTIVALUED && value != null
? nonEmpty(Arrays.asList(Constants.CFG_DELIMITER_PATTERN.split(value))) : singleton(value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@
package org.keycloak.validation;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.keycloak.component.ComponentModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.Constants;
import org.keycloak.protocol.oidc.OIDCConfigAttributes;
import org.keycloak.representations.idm.ClientRepresentation;
Expand Down Expand Up @@ -337,6 +339,81 @@ public void patternDoesNotResolveOrSkipLiteralMarkers() {
}
}

@Test
public void mergeKeepsStoredValuesForFieldsTheUpdateDoesNotSet() {
ClientModel stored = storedClient();
ClientRepresentation proposed = new ClientRepresentation();
proposed.setDescription("updated description");

assertEquals(List.of("https://stored.example"), ClientUriField.ROOT_URL.getValues(proposed, stored));
assertEquals(List.of("https://stored.example/callback"), ClientUriField.REDIRECT_URIS.getValues(proposed, stored));
assertEquals(List.of("https://stored.example/jwks"), ClientUriField.JWKS_URL.getValues(proposed, stored));
}

@Test
public void mergeTakesValuesTheUpdateSets() {
ClientModel stored = storedClient();
ClientRepresentation proposed = new ClientRepresentation();
proposed.setRootUrl("https://updated.example");
proposed.setRedirectUris(List.of("https://updated.example/callback"));
proposed.setAttributes(Map.of(OIDCConfigAttributes.JWKS_URL, "https://updated.example/jwks"));

assertEquals(List.of("https://updated.example"), ClientUriField.ROOT_URL.getValues(proposed, stored));
assertEquals(List.of("https://updated.example/callback"), ClientUriField.REDIRECT_URIS.getValues(proposed, stored));
assertEquals(List.of("https://updated.example/jwks"), ClientUriField.JWKS_URL.getValues(proposed, stored));
}

@Test
public void mergeLeavesNothingToValidateWhenTheUpdateClearsAField() {
ClientModel stored = storedClient();
ClientRepresentation proposed = new ClientRepresentation();
proposed.setRedirectUris(List.of());
Map<String, String> attributes = new HashMap<>();
attributes.put(OIDCConfigAttributes.JWKS_URL, null);
proposed.setAttributes(attributes);

assertEquals(List.of(), ClientUriField.REDIRECT_URIS.getValues(proposed, stored));
assertEquals(List.of(), ClientUriField.JWKS_URL.getValues(proposed, stored));

attributes.put(OIDCConfigAttributes.JWKS_URL, "");
assertEquals(List.of(), ClientUriField.JWKS_URL.getValues(proposed, stored));
}

@Test
public void mergeDerivesWebOriginsFromTheUpdatedRedirectUrisWhenNoneAreStored() {
ClientModel stored = storedClient();
ClientRepresentation proposed = new ClientRepresentation();
proposed.setRedirectUris(List.of("http://updated.example/callback"));

assertEquals(List.of("http://updated.example"), ClientUriField.WEB_ORIGINS.getValues(proposed, stored));
}

@Test
public void mergeDerivesWebOriginsFromTheRedirectUrisOfARegistration() {
ClientRepresentation proposed = new ClientRepresentation();
proposed.setRedirectUris(List.of("http://registered.example/callback", "/relative"));

assertEquals(List.of("http://registered.example"), ClientUriField.WEB_ORIGINS.getValues(proposed, null));
}

@Test
public void mergeKeepsStoredWebOriginsInsteadOfDerivingThem() {
ClientRepresentation storedRep = new ClientRepresentation();
storedRep.setRedirectUris(List.of("http://stored.example/callback"));
storedRep.setWebOrigins(List.of("https://origin.example"));
ClientModel stored = ClientUriPolicyTest.clientModel(storedRep);

assertEquals(List.of("https://origin.example"), ClientUriField.WEB_ORIGINS.getValues(new ClientRepresentation(), stored));
}

private static ClientModel storedClient() {
ClientRepresentation stored = new ClientRepresentation();
stored.setRootUrl("https://stored.example");
stored.setRedirectUris(List.of("https://stored.example/callback"));
stored.setAttributes(Map.of(OIDCConfigAttributes.JWKS_URL, "https://stored.example/jwks"));
return ClientUriPolicyTest.clientModel(stored);
}

private static SecureClientUrisPatternExecutor literalMarkerPattern(List<String> fields) {
SecureClientUrisPatternExecutor executor = new SecureClientUrisPatternExecutor(null);
SecureClientUrisPatternExecutor.Configuration configuration = new SecureClientUrisPatternExecutor.Configuration();
Expand Down
Loading
Loading
0