Repository navigation
Fix #51594: Add has-client-attribute condition and align client-created workflow event timing - #52189
tusharjamunkar wants to merge 2 commits into
Conversation
There was a problem hiding this comment.
Pull request overview
Updates client-created workflow activation to use admin and dynamic registration events after client population.
Changes:
- Replaces low-level client creation event handling.
- Adds an integration test for workflow execution after client creation.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
ClientCreatedWorkflowEventProvider.java |
Handles admin and dynamic client registration events. |
ClientCreationWorkflowTest.java |
Tests client-created workflow activation. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| public boolean supports(Event event) { | ||
| return EventType.CLIENT_REGISTER.equals(event.getType()); |
| public boolean supports(AdminEvent adminEvent) { | ||
| return org.keycloak.events.admin.ResourceType.CLIENT.equals(adminEvent.getResourceType()) | ||
| && OperationType.CREATE.equals(adminEvent.getOperationType()); |
| WorkflowRepresentation workflow = WorkflowRepresentation.withName("client-created-workflow") | ||
| .onEvent(ClientCreatedWorkflowEventFactory.ID) |
|
Updated with latest review hardening:
|
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 4 changed files in this pull request and generated no new comments.
Suppressed comments (2)
model/jpa/src/main/java/org/keycloak/models/workflow/events/ClientCreatedWorkflowEventProvider.java:24
CLIENT_REGISTERis still published too early for the standard dynamic-registration paths:AbstractClientRegistrationProvider.create()callssuccess()beforeOIDCClientRegistrationProvideradds pairwise sub-mappers and performs final validation (lines 99–105), and beforeDefaultClientRegistrationProviderperforms final validation (lines 53–54). Consequently, this new listener can evaluate conditions and run steps against an incompletely configured client; move the success notification after each registration path's post-processing, as this PR does for CIMD.
public boolean supports(Event event) {
return EventType.CLIENT_REGISTER.equals(event.getType());
tests/base/src/test/java/org/keycloak/tests/workflow/activation/ClientCreationWorkflowTest.java:34
- This regression test adds an attribute but never adds a workflow condition that reads it, so it only verifies step timing and can still pass if an event is emitted after
enabledis copied but before attributes are available. Add a client-scoped test condition and attach it withonCondition(...)so the behavior reported in #51594 is exercised directly.
WorkflowRepresentation workflow = WorkflowRepresentation.withName("client-created-workflow")
.onEvent(ClientCreatedWorkflowEventFactory.ID)
|
Further hardened dynamic client registration (DCR) event emission timing:
|
| public boolean supports(Event event) { | ||
| return EventType.CLIENT_REGISTER.equals(event.getType()); |
|
Added Dynamic Client Registration test case:
|
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.
Suppressed comments (1)
tests/base/src/test/java/org/keycloak/tests/workflow/activation/ClientCreationWorkflowTest.java:71
- The dynamic-registration case also activates an unconditional workflow, so it does not verify that
CLIENT_REGISTERis emitted only after client attributes are visible to conditions. Make this workflow depend on a client-scoped condition matchingcustom-attr=dcr-valso this path directly guards the issue being fixed.
.onEvent(ClientCreatedWorkflowEventFactory.ID)
| public void testActivateWorkflowOnAdminClientCreation() { | ||
| // create the workflow that triggers on client creation | ||
| WorkflowRepresentation workflow = WorkflowRepresentation.withName("admin-client-created-workflow") | ||
| .onEvent(ClientCreatedWorkflowEventFactory.ID) |
|
Added
|
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 11 out of 11 changed files in this pull request and generated 2 comments.
Suppressed comments (1)
model/jpa/src/main/java/org/keycloak/models/workflow/conditions/ClientAttributeWorkflowConditionProvider.java:79
- This rejects the
key=valueproperties syntax used by the analogoushas-user-attributecondition and documented for workflow attributes, even thoughProperties.loadbelow supports it. Keep only the null/blank validation so both standard properties separators remain valid.
if (!expectedAttribute.contains(":")) {
throw new WorkflowInvalidStateException("workflowConditionAttributeInvalid", expectedAttribute);
}
| public Predicate toPredicate(CriteriaBuilder cb, CriteriaQuery<String> query, Root<?> path) { | ||
| return null; |
| @@ -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 | |||
|
Completed final enhancements for
|
| } | ||
|
|
||
| @Override | ||
| public Predicate toPredicate(CriteriaBuilder cb, CriteriaQuery<String> query, Root<?> path) { |
|
Added scheduled workflow criteria predicate test coverage:
|
| Subquery<Long> matchingCountSubquery = query.subquery(Long.class); | ||
| Root<ClientAttributeEntity> attrRoot = matchingCountSubquery.from(ClientAttributeEntity.class); | ||
| matchingCountSubquery.select(cb.count(attrRoot)); | ||
| matchingCountSubquery.where( | ||
| cb.and( | ||
| cb.equal(attrRoot.get("client").get("id"), path.get("id")), | ||
| cb.equal(attrRoot.get("name"), attributeName), | ||
| cb.equal(attrRoot.get("value"), valuePart) | ||
| ) | ||
| ); | ||
|
|
||
| return cb.greaterThan(matchingCountSubquery, 0L); |
| // 4. Trigger scheduled steps execution (evaluates toPredicate) | ||
| runScheduledSteps(Duration.ZERO); | ||
|
|
||
| // 5. Assert matching client is selected by criteria predicate and disabled | ||
| ClientResource matchingResource = managedRealm.admin().clients().get(matchingId); | ||
| assertThat(matchingResource.toRepresentation().isEnabled(), is(false)); | ||
|
|
||
| // 6. Assert non-matching client is not selected and remains enabled | ||
| ClientResource nonMatchingResource = managedRealm.admin().clients().get(nonMatchingId); | ||
| assertThat(nonMatchingResource.toRepresentation().isEnabled(), is(true)); |
| @@ -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 | |||
There was a problem hiding this comment.
Nit: the new files are missing the Apache license header and trailing newlines.
| @@ -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(); | |||
There was a problem hiding this comment.
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?
| public void close() { | ||
| } | ||
|
|
||
| public static String[] parseKeyValuePair(String keyValuePair) { |
There was a problem hiding this comment.
Byte-identical to UserAttributeWorkflowConditionProvider.parseKeyValuePair (also public static) — reuse that instead of a second copy. One divergence to settle: that condition splits the value on commas for multi-value matching, this one compares literally, so key:v1,v2 behaves differently between the two. Either support the list form or state single-value in the doc row.
c48fcbc to
7a5f32f
Compare
|
Refined Admin API v2 resource path and OIDC DCR client lookup:
|
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 15 out of 15 changed files in this pull request and generated 1 comment.
Suppressed comments (1)
rest/admin-v2/services/src/main/java/org/keycloak/services/client/DefaultClientService.java:433
- The former feature flag guarded all Admin API v2 events, but this
elsenow emits UPDATE and DELETE events unconditionally. That reintroduces the duplicate admin events the method comment says the flag avoids; keep CREATE unconditional for workflow activation while retaining the flag for non-CREATE operations.
} else {
adminEventBuilder
.operation(operationType)
.resourcePath(session.getContext().getUri())
.representation(representation)
.success();
}
| if (OperationType.CREATE.equals(operationType)) { | ||
| adminEventBuilder | ||
| .operation(operationType) | ||
| .resourcePath(session.getContext().getUri(), representation.getUuid()) |
…before client is populated - Align ClientCreatedWorkflowEventProvider with AdminEvent (ResourceType.CLIENT + OperationType.CREATE) and Event (EventType.CLIENT_REGISTER) rather than premature ProviderEvent, ensuring client attributes and representations are fully populated before condition evaluation. - Move event.success() after final validation across ClientsResource, DefaultClientRegistrationProvider, OIDCClientRegistrationProvider, EntityDescriptorClientRegistrationProvider, and AbstractPersistentClientIdMetadataDocumentProvider. This ensures rejected creations do not emit invalid CREATE events to EventListenerProviders. - Enable post-population client CREATE admin event emission in Admin API v2 DefaultClientService while retaining property flag for non-CREATE operations. - Map PartialImportResult resource types to corresponding AdminEvent ResourceTypes in RealmAdminResource so partial-import client creations emit CLIENT+CREATE admin events, and update PartialImportUserTest assertions accordingly. - Implement ClientAttributeWorkflowConditionProvider & ClientAttributeWorkflowConditionFactory (has-client-attribute) supporting single-value properties format and database-specific criteria predicates (including Oracle DBMS_LOB.COMPARE and PostgreSQL expression index optimizations). - Add Client functions documentation for has-client-attribute in defining-conditions.adoc. - Add comprehensive automated integration tests in ClientCreationWorkflowTest for Admin REST API, Dynamic Client Registration (DCR & OIDC), Partial Import, and scheduled workflow scans with DatabaseTest annotation and Awaitility synchronization. Signed-off-by: tusharjamunkar <tusharjamunkar@users.noreply.github.com>
7a5f32f to
28d2327
Compare
|
Updated Admin API v2 event flag scoping and test path assertion:
|
|
Hi @tusharjamunkar , thanks for working on this! I went through the PR and the review history. Most of Copilot findings from earlier rounds look addressed in the current squashed commit (event-timing relocation across
The |
There was a problem hiding this comment.
See my last comment for a list of suggestions.
…ighten event path assertion
|
Hi @sguilhen, Thank you for the detailed and constructive review! I have addressed all points from your feedback:
The updated commits are pushed and ready for your re-review! |
There was a problem hiding this comment.
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Pull request overview
Copilot reviewed 16 out of 16 changed files in this pull request and generated 5 comments.
| public boolean supports(Event event) { | ||
| return EventType.CLIENT_REGISTER.equals(event.getType()); | ||
| } | ||
|
|
||
| @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()); | ||
| } |
There was a problem hiding this comment.
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.
| return false; | ||
| } | ||
|
|
||
| String[] parsedKeyValuePair = UserAttributeWorkflowConditionProvider.parseKeyValuePair(expectedAttribute); |
| public Predicate toPredicate(CriteriaBuilder cb, CriteriaQuery<String> query, Root<?> path) { | ||
| validate(); | ||
|
|
||
| String[] parsedKeyValuePair = UserAttributeWorkflowConditionProvider.parseKeyValuePair(expectedAttribute); |
| EntityManager em = session.getProvider(JpaConnectionProvider.class).getEntityManager(); | ||
| String dbProductName = em.unwrap(Session.class).doReturningWork(connection -> connection.getMetaData().getDatabaseProductName()); |
| 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"))) { |
|
One path that I think is still uncovered: |
|
Summarizing where this stands, since the thread has drifted across #51594/#51595/#51629. Delivered here: the Two things need action before this is ready:
Minor, non-blocking: Out of scope for this PR, tracked on #51595: the |
Closes #51594
Follow-up issue: #52958
Description
Event-based workflow activation for
on: client-createdpreviously evaluated conditions against a client that was not yet populated becauseClientCreatedWorkflowEventProviderlistened on the low-levelProviderEvent(ClientModel.ClientCreationEvent) fired inJpaRealmProvider.addClient()before attributes and representations were applied.This pull request resolves this timing issue by:
ClientCreatedWorkflowEventProviderwithUserCreatedWorkflowEventProviderby listening onAdminEvent(ResourceType.CLIENT+OperationType.CREATE) andEvent(EventType.CLIENT_REGISTER).has-client-attributecondition provider for workflows to allow evaluating client-scoped attributes.Key Changes
ClientCreatedWorkflowEventProvidernow listens toAdminEvent(ResourceType.CLIENT+OperationType.CREATE) andEvent(EventType.CLIENT_REGISTER), ensuring client attributes and representations are fully populated before condition evaluation.has-client-attribute:ClientAttributeWorkflowConditionProvider&ClientAttributeWorkflowConditionFactory.has-client-attribute(attribute-name:expected-value)orhas-client-attribute(attribute-name:)to check existence).toPredicatefor scheduled workflow scans with database-specific criteria queries (including OracleDBMS_LOB.COMPAREand PostgreSQLsubstr(VALUE, 1, 255)index optimization onIDX_CLIENT_ATT_BY_NAME_VALUE).defining-conditions.adoc.adminEvent.operation(OperationType.CREATE)...success()inClientsResourceto after client policy execution (AdminClientRegisteredContext) and validation. This guarantees that rejected creations (e.g. blocked by client policies) do not emit spuriousCREATEevents to anyEventListenerProvider.CREATEadmin event emission inDefaultClientService.fireAdminEventwith exact resource path (clients/v2/{uuid}), ensuring Admin API v2 creations triggeron: client-createdworkflows. Thekc.admin-v2.client-service.events.enabledflag is retained for non-CREATE operations to prevent duplicate events.PartialImportResultresource types to correspondingAdminEventResourceTypes inRealmAdminResource, enablingon: client-createdworkflows during partial import.event.client(...).success()acrossDefaultClientRegistrationProvider,OIDCClientRegistrationProvider,EntityDescriptorClientRegistrationProvider, andAbstractPersistentClientIdMetadataDocumentProviderto after pairwise protocol mapper setup and final validation.ClientCreationWorkflowTest: Covers Admin REST API v1, Admin API v2, Dynamic Client Registration (Default & OIDC), Partial Import, and scheduled workflow scans with@DatabaseTestcriteria evaluation and Awaitility synchronization.AdminEventV2Test: Assertions verify exact resource paths (clients/v2/{uuid}) for created clients.Release Notes / Changelog
has-client-attribute: Workflows now provide a built-inhas-client-attributecondition provider that evaluates whether a client contains a specified attribute and value (or simply checks for attribute presence). This condition is supported for both real-time event triggers and scheduled batch scans.ClientsResource): In Admin REST API v1, theCLIENTCREATEadmin event is now emitted only after client policies have executed and final validation has succeeded. As a result, client creations rejected by client policies will no longer produce spuriousCREATEadmin events.CREATEadmin event upon client creation, allowing event listeners and workflows (on: client-created) to react to clients created via the v2 API.Related Issues
on: client-createdconditions are evaluated before the client is populated, so they can never match #51594