From bd472ae282395838cc7a282343e844fa651c983c Mon Sep 17 00:00:00 2001 From: Antonio Casagrande Date: Wed, 14 Oct 2026 15:49:33 -0300 Subject: [PATCH 1/3] Schedule workflow steps against Time so scheduling and due checks use the same clock JpaWorkflowStateProvider.scheduleStep stamped scheduledStepTimestamp with Instant.now() while getDueScheduledSteps compares it against Time.currentTimeMillis(). Production behavior is unchanged (Time delegates to the system clock), but a step scheduled while a time offset is set, such as a workflow restarted by an event, was scheduled against the real clock and fell due early. Signed-off-by: Antonio Casagrande --- .../keycloak/models/workflow/JpaWorkflowStateProvider.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/model/jpa/src/main/java/org/keycloak/models/workflow/JpaWorkflowStateProvider.java b/model/jpa/src/main/java/org/keycloak/models/workflow/JpaWorkflowStateProvider.java index 83ae874e074..2f81df6a0c5 100644 --- a/model/jpa/src/main/java/org/keycloak/models/workflow/JpaWorkflowStateProvider.java +++ b/model/jpa/src/main/java/org/keycloak/models/workflow/JpaWorkflowStateProvider.java @@ -18,7 +18,6 @@ package org.keycloak.models.workflow; import java.time.Duration; -import java.time.Instant; import java.util.stream.Stream; import jakarta.persistence.EntityManager; @@ -78,12 +77,12 @@ public ScheduleResult scheduleStep(Workflow workflow, WorkflowStep step, String entity.setWorkflowId(workflow.getId()); entity.setExecutionId(executionId); entity.setScheduledStepId(step.getId()); - entity.setScheduledStepTimestamp(Instant.now().plus(duration).toEpochMilli()); + entity.setScheduledStepTimestamp(Time.currentTimeMillis() + duration.toMillis()); em.persist(entity); return ScheduleResult.CREATED; } else { entity.setScheduledStepId(step.getId()); - entity.setScheduledStepTimestamp(Instant.now().plus(duration).toEpochMilli()); + entity.setScheduledStepTimestamp(Time.currentTimeMillis() + duration.toMillis()); return ScheduleResult.UPDATED; } } From a4099acc0ad270c64efc12bb66a4a57eb8298a79 Mon Sep 17 00:00:00 2001 From: Antonio Casagrande Date: Tue, 22 Sep 2026 13:59:40 -0300 Subject: [PATCH 2/3] Add a client-activity workflow event provider Workflows can already react to a client authenticating, but that event is EventType.CLIENT_LOGIN, which only the client_credentials grant emits. A public authorization-code client - what dynamic client registration produces - never raises it, so a workflow that means "disable this client if it has been idle for N days" silently degrades to "N days after it was created" for exactly the population most likely to accumulate. Add client-activity over LOGIN, CODE_TO_TOKEN and REFRESH_TOKEN, so any use of the client resets the timer. The *_ERROR variants are deliberately excluded: they carry the client id too, so counting them would let failed authentication against a dormant client keep it alive indefinitely. Signed-off-by: Antonio Casagrande --- .../ClientActivityWorkflowEventFactory.java | 20 +++ .../ClientActivityWorkflowEventProvider.java | 31 ++++ ...dels.workflow.WorkflowEventProviderFactory | 1 + .../ClientActivityWorkflowTest.java | 138 ++++++++++++++++++ 4 files changed, 190 insertions(+) create mode 100644 model/jpa/src/main/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventFactory.java create mode 100644 model/jpa/src/main/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventProvider.java create mode 100644 tests/base/src/test/java/org/keycloak/tests/workflow/activation/ClientActivityWorkflowTest.java diff --git a/model/jpa/src/main/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventFactory.java b/model/jpa/src/main/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventFactory.java new file mode 100644 index 00000000000..7703ff2537c --- /dev/null +++ b/model/jpa/src/main/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventFactory.java @@ -0,0 +1,20 @@ +package org.keycloak.models.workflow.events; + +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.workflow.WorkflowEventProvider; +import org.keycloak.models.workflow.WorkflowEventProviderFactory; + +public class ClientActivityWorkflowEventFactory implements WorkflowEventProviderFactory { + + public static final String ID = "client-activity"; + + @Override + public WorkflowEventProvider create(KeycloakSession session, String configParameter) { + return new ClientActivityWorkflowEventProvider(session, configParameter, this.getId()); + } + + @Override + public String getId() { + return ID; + } +} diff --git a/model/jpa/src/main/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventProvider.java b/model/jpa/src/main/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventProvider.java new file mode 100644 index 00000000000..604754aef3c --- /dev/null +++ b/model/jpa/src/main/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventProvider.java @@ -0,0 +1,31 @@ +package org.keycloak.models.workflow.events; + +import java.util.EnumSet; +import java.util.Set; + +import org.keycloak.events.Event; +import org.keycloak.events.EventType; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.workflow.AbstractWorkflowEventProvider; +import org.keycloak.models.workflow.ResourceType; + +public class ClientActivityWorkflowEventProvider extends AbstractWorkflowEventProvider { + + // User events that indicate a client is actively being used on behalf of a user. Unlike CLIENT_LOGIN, + // these events are also sent for public clients, which cannot authenticate on their own. + private static final Set ACTIVITY_EVENT_TYPES = EnumSet.of(EventType.LOGIN, EventType.CODE_TO_TOKEN, EventType.REFRESH_TOKEN); + + public ClientActivityWorkflowEventProvider(final KeycloakSession session, final String configParameter, final String providerId) { + super(session, configParameter, providerId); + } + + @Override + public ResourceType getSupportedResourceType() { + return ResourceType.CLIENTS; + } + + @Override + public boolean supports(Event event) { + return ACTIVITY_EVENT_TYPES.contains(event.getType()); + } +} diff --git a/model/jpa/src/main/resources/META-INF/services/org.keycloak.models.workflow.WorkflowEventProviderFactory b/model/jpa/src/main/resources/META-INF/services/org.keycloak.models.workflow.WorkflowEventProviderFactory index 0e3e70bead9..750db465ab7 100644 --- a/model/jpa/src/main/resources/META-INF/services/org.keycloak.models.workflow.WorkflowEventProviderFactory +++ b/model/jpa/src/main/resources/META-INF/services/org.keycloak.models.workflow.WorkflowEventProviderFactory @@ -9,5 +9,6 @@ org.keycloak.models.workflow.events.UserRoleGrantedWorkflowEventFactory org.keycloak.models.workflow.events.UserRoleRevokedWorkflowEventFactory # client event providers +org.keycloak.models.workflow.events.ClientActivityWorkflowEventFactory org.keycloak.models.workflow.events.ClientAuthenticatedWorkflowEventFactory org.keycloak.models.workflow.events.ClientCreatedWorkflowEventFactory \ No newline at end of file diff --git a/tests/base/src/test/java/org/keycloak/tests/workflow/activation/ClientActivityWorkflowTest.java b/tests/base/src/test/java/org/keycloak/tests/workflow/activation/ClientActivityWorkflowTest.java new file mode 100644 index 00000000000..5f24251b396 --- /dev/null +++ b/tests/base/src/test/java/org/keycloak/tests/workflow/activation/ClientActivityWorkflowTest.java @@ -0,0 +1,138 @@ +package org.keycloak.tests.workflow.activation; + +import java.time.Duration; + +import org.keycloak.models.ClientModel; +import org.keycloak.models.RealmModel; +import org.keycloak.models.workflow.WorkflowProvider; +import org.keycloak.models.workflow.WorkflowStateProvider; +import org.keycloak.models.workflow.client.DisableClientStepProviderFactory; +import org.keycloak.models.workflow.events.ClientActivityWorkflowEventFactory; +import org.keycloak.representations.workflows.WorkflowRepresentation; +import org.keycloak.representations.workflows.WorkflowStepRepresentation; +import org.keycloak.testframework.annotations.InjectUser; +import org.keycloak.testframework.annotations.KeycloakIntegrationTest; +import org.keycloak.testframework.injection.LifeCycle; +import org.keycloak.testframework.realm.ManagedUser; +import org.keycloak.testframework.realm.UserBuilder; +import org.keycloak.testframework.realm.UserConfig; +import org.keycloak.testframework.remote.timeoffset.InjectTimeOffSet; +import org.keycloak.testframework.remote.timeoffset.TimeOffSet; +import org.keycloak.tests.workflow.AbstractWorkflowTest; +import org.keycloak.tests.workflow.config.WorkflowsBlockingServerConfig; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.empty; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests activation of client workflows based on user-driven activity (login) events. + */ +@KeycloakIntegrationTest(config = WorkflowsBlockingServerConfig.class) +public class ClientActivityWorkflowTest extends AbstractWorkflowTest { + + @InjectUser(ref = "alice", config = DefaultUserConfig.class, lifecycle = LifeCycle.METHOD, realmRef = DEFAULT_REALM_NAME) + private ManagedUser userAlice; + + @InjectTimeOffSet + TimeOffSet timeOffSet; + + @Test + public void testActivateWorkflowOnClientActivity() { + createWorkflow(); + + // login with alice - the login event carries the client, so this attaches the workflow to the + // client used for the login and schedules the first step + login(); + + // running the scheduled tasks now shouldn't pick up any step as none are due to run yet + runScheduledSteps(Duration.ZERO); + + assertClientEnabled(true, "phase1: nothing due yet"); + + // move the clock 4 days ahead and login again - the activity resets the workflow, so the + // disable step is now due 9 days after the first login + timeOffSet.set(Duration.ofDays(4)); + try { + login(); + } finally { + timeOffSet.set(0); + } + + // without the reset the disable step would be due now + runScheduledSteps(Duration.ofDays(6)); + + assertClientEnabled(true, "phase2: reset moved the step past day 6"); + + // setting the offset past the reset schedule should disable the client + runScheduledSteps(Duration.ofDays(10)); + + assertClientEnabled(false, "phase3: step due after day 9"); + } + + @Test + public void testFailedLoginDoesNotActivateWorkflow() { + createWorkflow(); + + // a failed attempt carries the client on the error event but must not activate the workflow - + // otherwise spamming bad credentials against a dormant client would keep its idle clock alive + oauth.openLoginForm(); + loginPage.fillLogin(userAlice.getUsername(), "wrong-password"); + loginPage.submit(); + + runOnServer.run((session -> { + WorkflowProvider provider = session.getProvider(WorkflowProvider.class); + WorkflowStateProvider stateProvider = session.getProvider(WorkflowStateProvider.class); + provider.getWorkflows().forEach(workflow -> + assertThat(stateProvider.getScheduledStepsByWorkflow(workflow.getId()).toList(), empty())); + })); + } + + private void createWorkflow() { + managedRealm.admin().workflows().create(WorkflowRepresentation.withName("myworkflow") + .onEvent(ClientActivityWorkflowEventFactory.ID) + .concurrency().restartInProgress("true") // this setting enables restarting the workflow + .withSteps( + WorkflowStepRepresentation.create().of(DisableClientStepProviderFactory.ID) + .after(Duration.ofDays(5)) + .build() + ).build()).close(); + } + + private void login() { + oauth.openLoginForm(); + loginPage.fillLogin(userAlice.getUsername(), userAlice.getPassword()); + loginPage.submit(); + Assertions.assertTrue(oauth.parseLoginResponse().isSuccess()); + } + + private void assertClientEnabled(boolean expectedEnabled, String phase) { + String clientId = oauth.getClientId(); + + runOnServer.run((session -> { + RealmModel realm = session.getContext().getRealm(); + ClientModel client = session.clients().getClientByClientId(realm, clientId); + if (expectedEnabled) { + assertTrue(client.isEnabled(), phase); + } else { + assertFalse(client.isEnabled(), phase); + } + })); + } + + private static class DefaultUserConfig implements UserConfig { + + @Override + public UserBuilder configure(UserBuilder user) { + user.username("alice"); + user.password("alice"); + user.name("alice", "alice"); + user.email("alice@example.org"); + return user; + } + } +} From 1b121dd9de61c6e1a44aa7ab9b0271de2806b278 Mon Sep 17 00:00:00 2001 From: Antonio Casagrande Date: Wed, 14 Oct 2026 15:08:09 -0300 Subject: [PATCH 3/3] Document client-activity and cover each event it counts Add the event to the event-functions table. Pin the counted and ignored event types in a unit test, since an authorization code is only issued at the end of a login and an integration test cannot exercise CODE_TO_TOKEN apart from LOGIN. Add an integration case where a token refresh is the only activity and still resets the workflow. Signed-off-by: Antonio Casagrande --- .../workflows/listening-workflow-events.adoc | 1 + ...ientActivityWorkflowEventProviderTest.java | 64 +++++++++++++++++++ .../ClientActivityWorkflowTest.java | 36 ++++++++++- 3 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 model/jpa/src/test/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventProviderTest.java diff --git a/docs/documentation/server_admin/topics/workflows/listening-workflow-events.adoc b/docs/documentation/server_admin/topics/workflows/listening-workflow-events.adoc index 9da2eb44576..b421f0d9529 100644 --- a/docs/documentation/server_admin/topics/workflows/listening-workflow-events.adoc +++ b/docs/documentation/server_admin/topics/workflows/listening-workflow-events.adoc @@ -54,4 +54,5 @@ At the moment, workflows support event functions for the following realm resourc | `user-group-membership-removed` | User is removed from a group. | The group name or path | `client-created` | Client is added to the realm. | None | `client-authenticated` | Client authenticates to the realm. | None +| `client-activity` | A user signs in through the client, or the client exchanges an authorization code or refreshes a token for a user. Failed attempts are not counted. | None |=== diff --git a/model/jpa/src/test/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventProviderTest.java b/model/jpa/src/test/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventProviderTest.java new file mode 100644 index 00000000000..7d1ed1192e2 --- /dev/null +++ b/model/jpa/src/test/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventProviderTest.java @@ -0,0 +1,64 @@ +/* + * 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.events; + +import org.keycloak.events.Event; +import org.keycloak.events.EventType; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * Pins the event types that count as client activity. An authorization code is only issued at the end of a + * login, so an integration test cannot exercise {@code CODE_TO_TOKEN} apart from {@code LOGIN}; this covers + * each type on its own. + */ +public class ClientActivityWorkflowEventProviderTest { + + private final ClientActivityWorkflowEventProvider provider = + new ClientActivityWorkflowEventProvider(null, null, ClientActivityWorkflowEventFactory.ID); + + private static Event eventOf(EventType type) { + Event event = new Event(); + event.setType(type); + event.setClientId("some-client"); + return event; + } + + @Test + public void countsSuccessfulUseOfTheClient() { + assertTrue(provider.supports(eventOf(EventType.LOGIN))); + assertTrue(provider.supports(eventOf(EventType.CODE_TO_TOKEN))); + assertTrue(provider.supports(eventOf(EventType.REFRESH_TOKEN))); + } + + @Test + public void ignoresFailedAttempts() { + // Error events carry the client too; counting them would let failed attempts keep a dormant client alive + assertFalse(provider.supports(eventOf(EventType.LOGIN_ERROR))); + assertFalse(provider.supports(eventOf(EventType.CODE_TO_TOKEN_ERROR))); + assertFalse(provider.supports(eventOf(EventType.REFRESH_TOKEN_ERROR))); + } + + @Test + public void leavesClientCredentialsToClientAuthenticated() { + assertFalse(provider.supports(eventOf(EventType.CLIENT_LOGIN))); + } +} diff --git a/tests/base/src/test/java/org/keycloak/tests/workflow/activation/ClientActivityWorkflowTest.java b/tests/base/src/test/java/org/keycloak/tests/workflow/activation/ClientActivityWorkflowTest.java index 5f24251b396..3362ecb8583 100644 --- a/tests/base/src/test/java/org/keycloak/tests/workflow/activation/ClientActivityWorkflowTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/workflow/activation/ClientActivityWorkflowTest.java @@ -2,6 +2,7 @@ import java.time.Duration; +import org.keycloak.OAuth2Constants; import org.keycloak.models.ClientModel; import org.keycloak.models.RealmModel; import org.keycloak.models.workflow.WorkflowProvider; @@ -20,6 +21,7 @@ import org.keycloak.testframework.remote.timeoffset.TimeOffSet; import org.keycloak.tests.workflow.AbstractWorkflowTest; import org.keycloak.tests.workflow.config.WorkflowsBlockingServerConfig; +import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -30,7 +32,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** - * Tests activation of client workflows based on user-driven activity (login) events. + * Tests activation of client workflows based on user-driven activity (login, code exchange, token refresh) events. */ @KeycloakIntegrationTest(config = WorkflowsBlockingServerConfig.class) public class ClientActivityWorkflowTest extends AbstractWorkflowTest { @@ -74,6 +76,38 @@ public void testActivateWorkflowOnClientActivity() { assertClientEnabled(false, "phase3: step due after day 9"); } + @Test + public void testTokenRefreshAloneResetsWorkflow() { + createWorkflow(); + + // an offline session survives the clock moving days ahead, so a refresh can be the only activity + oauth.scope(OAuth2Constants.OFFLINE_ACCESS); + AccessTokenResponse tokens; + try { + login(); + tokens = oauth.doAccessTokenRequest(oauth.parseLoginResponse().getCode()); + } finally { + oauth.scope(null); + } + assertTrue(tokens.isSuccess(), "code to token"); + + // 4 days later the client only refreshes - no login, no code exchange + timeOffSet.set(Duration.ofDays(4)); + try { + assertTrue(oauth.doRefreshTokenRequest(tokens.getRefreshToken()).isSuccess(), "refresh"); + } finally { + timeOffSet.set(0); + } + + runScheduledSteps(Duration.ofDays(6)); + + assertClientEnabled(true, "phase1: the refresh moved the step past day 6"); + + runScheduledSteps(Duration.ofDays(10)); + + assertClientEnabled(false, "phase2: step due after day 9"); + } + @Test public void testFailedLoginDoesNotActivateWorkflow() { createWorkflow();