Repository navigation
Add a client-activity workflow event provider #53082
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
antoniocasagrande-airia
wants to merge
3
commits into
keycloak:main
Choose a base branch
from
antoniocasagrande-airia:workflow-client-activity-event
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
bd472ae
Schedule workflow steps against Time so scheduling and due checks use…
antoniocasagrande-airia a4099ac
Add a client-activity workflow event provider
antoniocasagrande-airia 1b121dd
Document client-activity and cover each event it counts
antoniocasagrande-airia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
20 changes: 20 additions & 0 deletions
20
...src/main/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventFactory.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<WorkflowEventProvider> { | ||
|
|
||
| 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; | ||
| } | ||
| } | ||
31 changes: 31 additions & 0 deletions
31
...rc/main/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventProvider.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<EventType> 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()); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletions
64
...est/java/org/keycloak/models/workflow/events/ClientActivityWorkflowEventProviderTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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))); | ||
| } | ||
| } |
172 changes: 172 additions & 0 deletions
172
...base/src/test/java/org/keycloak/tests/workflow/activation/ClientActivityWorkflowTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| package org.keycloak.tests.workflow.activation; | ||
|
|
||
| import java.time.Duration; | ||
|
|
||
| import org.keycloak.OAuth2Constants; | ||
| import org.keycloak.models.ClientModel; | ||
| import org.keycloak.models.RealmModel; | ||
| import org.keycloak.models.workflow.WorkflowProvider; | ||
| import org.keycloak.models.workflow.W 6878 orkflowStateProvider; | ||
| 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.keycloak.testsuite.util.oauth.AccessTokenResponse; | ||
|
|
||
| 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, code exchange, token refresh) 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() { | ||
|
antoniocasagrande-airia marked this conversation as resolved.
Resolved
|
||
| createWorkflow(); | ||
|
|
||
| 10BC8 | // 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 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(); | ||
|
|
||
| // 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; | ||
| } | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.