8000 Clean up scheduled workflow state when a client is removed by sguilhen · Pull Request #55641 · 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 @@ -73,12 +73,14 @@ public ScheduleResult scheduleStep(Workflow workflow, WorkflowStep step, String
}

if (entity == null) {
ResourceType resourceType = workflow.getSupportedType();
entity = new WorkflowStateEntity();
entity.setResourceId(resourceId);
entity.setWorkflowId(workflow.getId());
entity.setExecutionId(executionId);
entity.setScheduledStepId(step.getId());
entity.setScheduledStepTimestamp(Instant.now().plus(duration).toEpochMilli());
entity.setResourceType(resourceType != null ? resourceType.name() : null);
em.persist(entity);
return ScheduleResult.CREATED;
} else {
Expand Down Expand Up @@ -163,7 +165,7 @@ public Stream<ScheduledStep> getScheduledStepsByResource(String resourceId, Stri
}

@Override
public void removeByResource(String resourceId, String realmId) {
public void removeByResource(String resourceId, String realmId, ResourceType resourceType) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaDelete<WorkflowStateEntity> delete = cb.createCriteriaDelete(WorkflowStateEntity.class);
Root<WorkflowStateEntity> root = delete.from(WorkflowStateEntity.class);
Expand All @@ -178,8 +180,11 @@ public void removeByResource(String resourceId, String realmId) {
cb.equal(component.get("providerType"), WorkflowProvider.class.getName()),
cb.equal(component.get("realm").get("id"), realmId)));

// also scope by resource type, so a resource of a different type with a colliding id
// (e.g. a user and a client sharing the same id) is not affected
delete.where(cb.and(
cb.equal(root.get("resourceId"), resourceId),
cb.equal(root.get("resourceType"), resourceType.name()),
Comment thread
sguilhen marked this conversation as resolved.
Resolved
root.get("workflowId").in(workflowIdsInRealm)));
int deletedCount = em.createQuery(delete).executeUpdate();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package org.keycloak.models.workflow;

import org.keycloak.Config;
import org.keycloak.models.ClientModel.ClientRemovedEvent;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.RealmModel.RealmRemovedEvent;
Expand All @@ -38,6 +39,8 @@ public void postInit(KeycloakSessionFactory factory) {
onUserRemovedEvent(event);
} if (fired instanceof RealmRemovedEvent event) {
onRealmRemovedEvent(event);
} if (fired instanceof ClientRemovedEvent event) {
onClientRemovedEvent(event);
}
});
}
Expand Down Expand Up @@ -65,6 +68,12 @@ private void onRealmRemovedEvent(RealmRemovedEvent event) {
private void onUserRemovedEvent(UserRemovedEvent event) {
KeycloakSession session = event.getKeycloakSession();
WorkflowStateProvider provider = session.getProvider(WorkflowStateProvider.class);
provider.removeByResource(event.getUser().getId(), event.getRealm().getId());
provider.removeByResource(event.getUser().getId(), event.getRealm().getId(), ResourceType.USERS);
}

private void onClientRemovedEvent(ClientRemovedEvent event) {
KeycloakSession session = event.getKeycloakSession();
WorkflowStateProvider provider = session.getProvider(WorkflowStateProvider.class);
provider.removeByResource(event.getClient().getId(), event.getClient().getRealm().getId(), ResourceType.CLIENTS);
}
}
11 changes: 11 additions & 0 deletions model/jpa/src/main/resources/META-INF/jpa-changelog-27.0.0.xml
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,15 @@
</modifySql>
</changeSet>

<!-- Backfill RESOURCE_TYPE for rows scheduled before it was populated, so that resource-type-scoped
cleanup (e.g. on user/client removal) still finds and removes them. Rows whose workflow no longer
exists are left untouched; they are already unreachable through the workflow's own realm. -->
<changeSet author="keycloak" id="27.0.0-55603-workflow-state-resource-type-backfill">
<sql>UPDATE ${database.defaultSchemaName}.WORKFLOW_STATE
SET RESOURCE_TYPE = (SELECT VALUE FROM ${database.defaultSchemaName}.COMPONENT_CONFIG
WHERE COMPONENT_CONFIG.COMPONENT_ID = WORKFLOW_STATE.WORKFLOW_ID
8000 AND COMPONENT_CONFIG.NAME = 'supports')
WHERE RESOURCE_TYPE IS NULL</sql>
</changeSet>

</databaseChangeLog>
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,17 @@
public interface WorkflowStateProvider extends Provider {

/**
* Deletes all state records associated with the given resource ID, scoped to the given realm.
* Deletes all state records associated with the given resource ID, scoped to the given realm and resource type.
* </p>
* This method removes workflow state information for the specified resource that belongs to
* workflows of the given realm. State records for other realms are left untouched, even when
* they reference a resource with the same ID.
* workflows of the given realm. State records for other realms, or for a resource of a different
* type that happens to share the same ID (e.g. a user and a client with colliding IDs), are left untouched.
*
* @param resourceId the ID of the resource whose state records should be deleted
* @param realmId the ID of the realm the resource belongs to
* @param resourceType the type of the resource whose state records should be deleted
*/
void removeByResource(String resourceId, String realmId);
void removeByResource(String resourceId, String realmId, ResourceType resourceType);

/**
* Deletes the state record associated with a specific workflow and resource combination.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,80 @@ public void testGetScheduledStepsByResourceIsScopedToRealm() {
}
}

/**
* Sets up a user workflow for alice and a client workflow for a client whose id is forced to collide
* with alice's user id, both in the managed realm. Used to exercise resource-type isolation of
* workflow state cleanup when a user and a client share the same id within the same realm.
*/
private record SameRealmCollisionFixture(String workflowIdUsers, String workflowIdClients, String collidingClientId) implements Serializable {}

private SameRealmCollisionFixture createSameRealmCollisionFixture() {
WorkflowsResource workflows = managedRealm.admin().workflows();

String workflowIdUsers;
try (Response response = workflows.create(WorkflowRepresentation.withName("same-realm-user-workflow")
.withSteps(
WorkflowStepRepresentation.create().of(DisableUserStepProviderFactory.ID)
.after(Duration.ofDays(5))
.build())
.build())) {
workflowIdUsers = ApiUtil.getCreatedId(response);
}
workflows.workflow(workflowIdUsers).activate(ResourceType.USERS.name(), userAlice.getId());

ClientRepresentation collidingClient = new ClientRepresentation();
collidingClient.setId(userAlice.getId());
collidingClient.setClientId("same-realm-colliding-client");
collidingClient.setEnabled(true);
managedRealm.admin().clients().create(collidingClient).close();

String workflowIdClients;
try (Response response = workflows.create(WorkflowRepresentation.withName("same-realm-client-workflow")
.withSteps(
WorkflowStepRepresentation.create().of(DisableClientStepProviderFactory.ID)
.after(Duration.ofDays(5))
.build())
.build())) {
workflowIdClients = ApiUtil.getCreatedId(response);
}
workflows.workflow(workflowIdClients).activate(ResourceType.CLIENTS.name(), userAlice.getId());

return new SameRealmCollisionFixture(workflowIdUsers, workflowIdClients, userAlice.getId());
}

@Test
@DatabaseTest
public void testClientRemovalOnlyDeletesOwnResourceTypeWorkflowState() {
SameRealmCollisionFixture fixture = createSameRealmCollisionFixture();

// verify state exists for both the user and the colliding client before the removal
runOnServer.run((RunOnServer) session -> {
WorkflowStateProvider stateProvider = session.getKeycloakSessionFactory()
.getProviderFactory(WorkflowStateProvider.class).create(session);
assertThat(stateProvider.getScheduledStepsByWorkflow(fixture.workflowIdUsers()).toList(), hasSize(1));
assertThat(stateProvider.getScheduledStepsByWorkflow(fixture.workflowIdClients()).toList(), hasSize(1));
});

// delete the client; its id collides with alice's user id in the same realm
managedRealm.admin().clients().delete(fixture.collidingClientId()).close();

// the client's own workflow state must be removed
runOnServer.run((RunOnServer) session -> {
WorkflowStateProvider stateProvider = session.getKeycloakSessionFactory()
.getProviderFactory(WorkflowStateProvider.class).create(session);
assertThat("the removed client's workflow state should be removed",
stateProvider.getScheduledStepsByWorkflow(fixture.workflowIdClients()).toList(), hasSize(0));
});

// alice's own workflow state, of a different resource type, must remain intact
runOnServer.run((RunOnServer) session -> {
WorkflowStateProvider stateProvider = session.getKeycloakSessionFactory()
.getProviderFactory(WorkflowStateProvider.class).create(session);
assertThat("client removal must not remove the colliding user's workflow state",
stateProvider.getScheduledStepsByWorkflow(fixture.workflowIdUsers()).toList(), hasSize(1));
});
}

@Test
public void testAdminEventsForWorkflowOperations() {
WorkflowsResource workflows = managedRealm.admin().workflows();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package org.keycloak.tests.workflow.step;

import java.time.Duration;
import java.util.List;

import jakarta.ws.rs.core.Response;

import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.workflow.RestartWorkflowStepProviderFactory;
import org.keycloak.models.workflow.WorkflowStateProvider;
import org.keycloak.models.workflow.client.DeleteClientStepProviderFactory;
import org.keycloak.models.workflow.client.DisableClientStepProviderFactory;
import org.keycloak.models.workflow.events.ClientAuthenticatedWorkflowEventFactory;
Expand All @@ -18,11 +20,14 @@
import org.keycloak.testframework.oauth.OAuthClient;
import org.keycloak.testframework.oauth.annotations.InjectOAuthClient;
import org.keycloak.testframework.util.ApiUtil;
import org.keycloak.tests.suites.DatabaseTest;
import org.keycloak.tests.workflow.AbstractWorkflowTest;
import org.keycloak.tests.workflow.config.WorkflowsBlockingServerConfig;

import org.junit.jupiter.api.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
Expand Down Expand Up @@ -129,6 +134,42 @@ public void testDisabledClientAfterInactivityPeriod() {
managedRealm.admin().clients().delete(cid).close();
}

@Test
@DatabaseTest
public void testClientRemovalCleansUpScheduledSteps() {
try (Response response = managedRealm.admin().workflows().create(WorkflowRepresentation.withName("myworkflow")
.onEvent(ClientCreatedWorkflowEventFactory.ID)
.withSteps(
WorkflowStepRepresentation.create()
.of(DisableClientStepProviderFactory.ID)
.after(Duration.ofDays(5))
.build()
).build())) {
assertEquals(201, response.getStatus());
}

// create a client, scheduling the disable-client step
String cid = createClient();

runOnServer.run(session -> {
RealmModel realm = session.getContext().getRealm();
WorkflowStateProvider stateProvider = session.getKeycloakSessionFactory().getProviderFactory(WorkflowStateProvider.class).create(session);
List<WorkflowStateProvider.ScheduledStep> steps = stateProvider.getScheduledStepsByResource(cid, realm.getId()).toList();
assertThat(steps, hasSize(1));
});

// remove the client before the scheduled step runs
managedRealm.admin().clients().delete(cid).close();

// the scheduled step for the removed client should have been cleaned up
runOnServer.run(session -> {
RealmModel realm = session.getContext().getRealm();
WorkflowStateProvider stateProvider = session.getKeycloakSessionFactory().getProviderFactory(WorkflowStateProvider.class).create(session);
List<WorkflowStateProvider.ScheduledStep> steps = stateProvider.getScheduledStepsByResource(cid, realm.getId()).toList();
assertThat(steps, hasSize(0));
});
}

private String createClient() {
ClientRepresentation rep = new ClientRepresentation();
rep.setName(CLIENT_ID);
Expand Down
Loading
0