8000 Add a client-activity workflow event provider by antoniocasagrande-airia · Pull Request #53082 · 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 @@ -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
|===
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
}
Expand Down
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";
Comment thread
antoniocasagrande-airia marked this conversation as resolved.
Resolved

@Override
public WorkflowEventProvider create(KeycloakSession session, String configParameter) {
return new ClientActivityWorkflowEventProvider(session, configParameter, this.getId());
}

@Override
public String getId() {
return ID;
}
}
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());
}
}
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -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
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)));
}
}
10BC8
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() {
Comment thread
antoniocasagrande-airia marked this conversation as resolved.
Resolved
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 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;
}
}
}
0