8000 Fix #51594: Add has-client-attribute condition and align client-created workflow event timing by tusharjamunkar · Pull Request #52189 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
7FFF
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 @@ -41,3 +41,15 @@ The conditions are also based on the realm resource associated with the event.
| `has-identity-provider-link` | If the user is linked to an identity provider. | The alias of the identity provider.
| `is-member-of` | If the user is member of a specific group. | The name or path of the group.
|===

[[_workflow_client_functions_]]
== Client functions

[cols="3*", options="header"]
|===
|Condition
|Description
|Parameters
| `has-client-attribute` | If the client has an attribute set. | The attribute name and optionally the single attribute value using a properties format (e.g. `key=value` or `key:value`). If the value is omitted, only the presence of the attribute is checked.
|===

Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright 2026 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.keycloak.models.workflow.conditions;

import org.keycloak.models.KeycloakSession;
import org.keycloak.models.workflow.WorkflowConditionProviderFactory;

public class ClientAttributeWorkflowConditionFactory implements WorkflowConditionProviderFactory<ClientAttributeWorkflowConditionProvider> {

public static final String ID = "has-client-attribute";

@Override
public ClientAttributeWorkflowConditionProvider create(KeycloakSession session, String keyValuePair) {
return new ClientAttributeWorkflowConditionProvider(session, keyValuePair);
}

@Override
public String getId() {
return ID;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/*
* Copyright 2026 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.keycloak.models.workflow.conditions;

import java.util.Map;

import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import jakarta.persistence.criteria.Subquery;

import org.hibernate.Session;
import org.keycloak.connections.jpa.JpaConnectionProvider;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.jpa.entities.ClientAttributeEntity;
import org.keycloak.models.workflow.ResourceType;
import org.keycloak.models.workflow.WorkflowConditionProvider;
import org.keycloak.models.workflow.WorkflowExecutionContext;
import org.keycloak.models.workflow.WorkflowInvalidStateException;

public class ClientAttributeWorkflowConditionProvider implements WorkflowConditionProvider {

private final String expectedAttribute;
private final KeycloakSession session;

public ClientAttributeWorkflowConditionProvider(KeycloakSession session, String expectedAttribute) {
this.session = session;
this.expectedAttribute = expectedAttribute;
}

@Override
public ResourceType getSupportedResourceType() {
return ResourceType.CLIENTS;
}

@Override
public boolean evaluate(WorkflowExecutionContext context) {
validate();

RealmModel realm = session.getContext().getRealm();
ClientModel client = session.clients().getClientById(realm, context.getResourceId());

if (client == null) {
return false;
}

String[] parsedKeyValuePair = UserAttributeWorkflowConditionProvider.parseKeyValuePair(expectedAttribute);
String key = parsedKeyValuePair[0];
String valuePart = parsedKeyValuePair[1];

Map<String, String> attributes = client.getAttributes();
if (attributes == null) {
return false;
}

String actualValue = attributes.get(key);
if (actualValue == null) {
return false;
}

if (valuePart == null || valuePart.isEmpty()) {
return true;
}

return valuePart.equals(actualValue);
}

@Override
public Predicate toPredicate(CriteriaBuilder cb, CriteriaQuery<String> query, Root<?> path) {
validate();

String[] parsedKeyValuePair = UserAttributeWorkflowConditionProvider.parseKeyValuePair(expectedAttribute);
String attributeName = parsedKeyValuePair[0];
String valuePart = parsedKeyValuePair[1];

if (valuePart == null || valuePart.isEmpty()) {
return cb.greaterThan(createTotalCountSubquery(cb, query, path, attributeName), 0L);
}

EntityManager em = session.getProvider(JpaConnectionProvider.class).getEntityManager();
String dbProductName = em.unwrap(Session.class).doReturningWork(connection -> connection.getMetaData().getDatabaseProductName());
Comment on lines +99 to +100

Subquery<Long> matchingCountSubquery = query.subquery(Long.class);
Root<ClientAttributeEntity> attrRoot = matchingCountSubquery.from(ClientAttributeEntity.class);
matchingCountSubquery.select(cb.count(attrRoot));

Predicate valuePredicate;
if ("Oracle".equals(dbProductName)) {
valuePredicate = cb.equal(cb.function("DBMS_LOB.COMPARE", Integer.class, attrRoot.get("value"), cb.literal(valuePart)), 0);
} else if ("PostgreSQL".equals(dbProductName)) {
Predicate attrValuePredicate1 = cb.equal(
cb.function("substr", String.class, attrRoot.get("value"), cb.literal(1), cb.literal(255)),
cb.function("substr", String.class, cb.literal(valuePart), cb.literal(1), cb.literal(255)));
Predicate attrValuePredicate2 = cb.equal(attrRoot.get("value"), valuePart);
valuePredicate = cb.and(attrValuePredicate1, attrValuePredicate2);
} else {
valuePredicate = cb.equal(attrRoot.get("value"), valuePart);
}

matchingCountSubquery.where(
cb.and(
cb.equal(attrRoot.get("client").get("id"), path.get("id")),
cb.equal(attrRoot.get("name"), attributeName),
valuePredicate
)
);

return cb.greaterThan(matchingCountSubquery, 0L);
}

private Subquery<Long> createTotalCountSubquery(CriteriaBuilder cb, CriteriaQuery<String> query, Root<?> path, String attributeName) {
Subquery<Long> totalCountSubquery = query.subquery(Long.class);
Root<ClientAttributeEntity> attrRoot = totalCountSubquery.from(ClientAttributeEntity.class);
totalCountSubquery.select(cb.count(attrRoot));
totalCountSubquery.where(
cb.and(
cb.equal(attrRoot.get("client").get("id"), path.get("id")),
cb.equal(attrRoot.get("name"), attributeName)
)
);
return totalCountSubquery;
}

@Override
public void validate() {
if (expectedAttribute == null || expectedAttri 10BC8 bute.trim().isEmpty()) {
throw new WorkflowInvalidStateException("workflowConditionAttributeNotSet");
}
}

@Override
public void close() {
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package org.keycloak.models.workflow.events;

import org.keycloak.models.ClientModel;
import org.keycloak.events.Event;
import org.keycloak.events.EventType;
import org.keycloak.events.admin.AdminEvent;
import org.keycloak.events.admin.OperationType;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.workflow.AbstractWorkflowEventProvider;
import org.keycloak.models.workflow.ResourceType;
import org.keycloak.provider.ProviderEvent;

public class ClientCreatedWorkflowEventProvider extends AbstractWorkflowEventProvider {

Expand All @@ -18,15 +20,13 @@ public ResourceType getSupportedResourceType() {
}

@Override
public boolean supports(ProviderEvent providerEvent) {
return providerEvent instanceof ClientModel.ClientCreationEvent;
public boolean supports(Event event) {
return EventType.CLIENT_REGISTER.equals(event.getType());
Comment on lines +23 to +24
Comment on lines +23 to +24
}

@Override
protected String resolveResourceId(ProviderEvent providerEvent) {
if (providerEvent instanceof ClientModel.ClientCreationEvent cce) {
return cce.getCreatedClient().getId();
}
return null;
public boolean supports(AdminEvent adminEvent) {
return org.keycloak.events.admin.ResourceType.CLIENT.equals(adminEvent.getResourceType())
&& OperationType.CREATE.equals(adminEvent.getOperationType());
Comment on lines +28 to +30
10BC8 Comment on lines +29 to +30
Comment on lines +23 to +30
}
Comment on lines +23 to 31
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Checked this against ResourceType.CLIENTS.resolveResourceId in server-spi-private: it already resolves the public clientId to the internal UUID generically via findClientResourceId, the same way USERS resolves through event.getUserId(). ClientCreatedWorkflowEventProvider doesn't need its own resolution logic. Closing this one out.

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@
org.keycloak.models.workflow.conditions.GroupMembershipWorkflowConditionFactory
org.keycloak.models.workflow.conditions.IdentityProviderWorkflowConditionFactory
org.keycloak.models.workflow.conditions.UserAttributeWorkflowConditionFactory
org.keycloak.models.workflow.conditions.ClientAttributeWorkflowConditionFactory
org.keycloak.models.workflow.conditions.RoleWorkflowConditionFactory
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,13 @@ && isBlank(oidcClient.getAuth().getSecret())) {
* @param representation the v2 representation of the client
*/
protected void fireAdminEvent(OperationType operationType, BaseClientRepresentation representation) {
if (Boolean.parseBoolean(System.getProperty("kc.admin-v2.client-service.events.enabled", "false"))) {
if (OperationType.CREATE.equals(operationType)) {
adminEventBuilder
.operation(operationType)
.resourcePath(session.getContext().getUri(), representation.getUuid())
.representation(representation)
.success();
} else if (Boolean.parseBoolean(System.getProperty("kc.admin-v2.client-service.events.enabled", "false"))) {
Comment on lines +421 to +427
adminEventBuilder
.operation(operationType)
.resourcePath(session.getContext().getUri())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ public void createClientFiresV2Event() throws Exception {

assertThat("V2 event should be present with apiVersion=v2 detail", v2Event, notNullValue());
assertThat("V2 event should have CREATE operation", v2Event.getOperationType(), is(OperationType.CREATE.toString()));
assertThat("V2 event should have resource path relative to API v2", v2Event.getResourcePath(), is("clients/v2"));
String createdClientUuid = testRealm.admin().clients().findByClientId(TEST_CLIENT_ID).get(0).getId();
assertThat("V2 event should have resource path relative to API v2", v2Event.getResourcePath(), is("clients/v2/" + createdClientUuid));
} finally {
deleteTestClient();
}
Expand Down Expand Up @@ -244,7 +245,8 @@ public void v2EventContainsV2Representation() throws Exception {
.orElse(null);

assertThat("V2 event should be present", v2Event, notNullValue());
assertThat("V2 event should have resource path relative to API v2", v2Event.getResourcePath(), is("clients/v2"));
String createdClientUuid = testRealm.admin().clients().findByClientId(TEST_CLIENT_ID).get(0).getId();
assertThat("V2 event should have resource path relative to API v2", v2Event.getResourcePath(), is("clients/v2/" + createdClientUuid));
var representation = v2Event.getRepresentation();
assertThat("V2 event should have representation", representation, notNullValue());
assertThat("V2 event should have masked secret in representation", representation, containsString("\"secret\":\"**********\""));
Expand Down Expand Up @@ -293,7 +295,8 @@ public void stripSamlSigningCertificateFromRepresentation() throws Exception {
.orElse(null);

assertThat("V2 event should be present", v2Event, notNullValue());
assertThat("V2 event should have resource path relative to API v2", v2Event.getResourcePath(), is("clients/v2"));
String samlClientUuid = testRealm.admin().clients().findByClientId(SAML_CLIENT_ID).get(0).getId();
assertThat("V2 event should have resource path relative to API v2", v2Event.getResourcePath(), is("clients/v2/" + samlClientUuid));
var representation = v2Event.getRepresentation();
assertThat("V2 event should have representation", representation, notNullValue());
assertThat("V2 event should have masked signing certificate in representation", representation, containsString("\"signingCertificate\":\"**********\""));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,14 +184,14 @@ public ClientModel createClientMetadata(AbstractClientIdMetadataDocumentExecutor
clientRep.setDefaultRoles(defaultRolesNames.toArray(String[]::new));
}

event.client(clientRep.getClientId()).success();

clientModel = realm.getClientByClientId(clientRep.getClientId());
updatePairwiseSubMappers(clientModel, SubjectType.parse(clientOIDC.getSubjectType()), clientOIDC.getSectorIdentifierUri());
updateClientRepWithProtocolMappers(clientModel, clientRep);

validateClient(clientModel, clientOIDC, true);

event.client(clientRep.getClientId()).success();

return clientModel;
} catch (ModelDuplicateException e) {
getLogger().warnv("ModelDuplicateException: {0}", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public Response createSaml(String descriptor) {
EntityDescriptorClientRegistrationContext context = new EntityDescriptorClientRegistrationContext(session, client, this);
client = create(context);
validateClient(client, true);
event.client(client.getClientId()).success();
URI uri = session.getContext().getUri().getAbsolutePathBuilder().path(client.getClientId()).build();
return Response.created(uri).entity(client).build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ public ClientRepresentation create(ClientRegistrationContext context) {
client.setDefaultRoles(defaultRolesNames.toArray(String[]::new));
}

event.client(client.getClientId()).success();
return client;
} catch (ModelDuplicateException e) {
throw new ErrorResponseException(ErrorCodes.INVALID_CLIENT_METADATA, "Client Identifier in use", Response.Status.BAD_REQUEST);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public Response createDefault(ClientRepresentation client) {
DefaultClientRegistrationContext context = new DefaultClientRegistrationContext(session, client, this);
client = create(context);
validateClient(client, true);
event.client(client.getClientId()).success();
URI uri = session.getContext().getUri().getAbsolutePathBuilder().path(client.getClientId()).build();
return Response.created(uri).entity(client).build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ public Response createOIDC(OIDCClientRepresentation clientOIDC) {

validateClient(clientModel, clientOIDC, true);

event.client(client.getClientId()).success();

URI uri = getRegistrationClientUri(clientModel);
clientOIDC = DescriptionConverter.toExternalResponse(session, client, uri);
clientOIDC.setClientIdIssuedAt(Time.currentTime());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,8 +221,6 @@ public ClientModel createClientModel(final ClientRepresentation rep) {
new ClientManager(new RealmManager(session)).enableServiceAccount(clientModel);
}

adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), clientModel.getId()).representation(rep).success();

if (Profile.isFeatureEnabled(Profile.Feature.AUTHORIZATION) && TRUE.equals(rep.getAuthorizationServicesEnabled())) {
if (Profile.isFeatureEnabled(Profile.Feature.CLIENT_TYPES) && clientModel.getType() != null) {
ClientType clientType = session.getProvider(ClientTypeManager.class).getClientType(realm, clientModel.getType());
Expand Down Expand Up @@ -254,6 +252,8 @@ public ClientModel createClientModel(final ClientRepresentation rep) {
session.getContext().setClient(clientModel);
session.clientPolicy().triggerOnEvent(new AdminClientRegisteredContext(clientModel, auth.adminAuth()));

adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), clientModel.getId()).representation(rep).success();
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This relocation changes behavior for every EventListenerProvider, not just workflows: a creation rejected by validation or client policy no longer emits the CREATE event (previously it did), and all listeners see the new ordering. The PR description should state that. Also, other producers of CLIENT+CREATE admin events (e.g. partial import) will now activate on: client-created workflows — intended?


return clientModel;
} catch (ModelDuplicateException e) {
throw ErrorResponse.exists("Client " + rep.getClientId() + " already exists");
Expand Down
Loading
0