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 @@ -28,6 +28,7 @@
import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.json.KeycloakJsonMapperFactory;
import org.keycloak.json.RawJsonValue;
import org.keycloak.representations.workflows.WorkflowRepresentation;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
Expand Down Expand Up @@ -202,6 +203,7 @@ public class RealmRepresentation {
private List<IdentityProviderMapperRepresentation> identityProviderMappers;
private List<ProtocolMapperRepresentation> protocolMappers;
private MultivaluedHashMap<String, ComponentExportRepresentation> components;
private List<WorkflowRepresentation> workflows;
protected Boolean internationalizationEnabled;
protected Set<String> supportedLocales;
protected String defaultLocale;
Expand Down Expand Up @@ -1482,6 +1484,14 @@ public void setComponents(MultivaluedHashMap<String, ComponentExportRepresentati
this.components = components;
}

public List<WorkflowRepresentation> getWorkflows() {
return workflows;
}

public void setWorkflows(List<WorkflowRepresentation> workflows) {
this.workflows = workflows;
}

@JsonIgnore
public boolean isIdentityFederationEnabled() {
return identityProviders != null && !identityProviders.isEmpty();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,27 @@ Workflows can be managed through the Admin Console or the Admin REST API.
Only realm administrators with the appropriate permissions can manage workflows as they are considered sensitive operations.
For more details, see <<_understanding_different_types_realm_admins_,Understanding different types of Realm Admins>>.

== Exporting and importing workflow definitions

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This section is good, but I think the change also needs an entry in docs/documentation/upgrading, because it is visible to anyone with existing tooling:

  • realm exports gain a top-level workflows array;
  • org.keycloak.models.workflow.WorkflowProvider no longer appears under components;
  • realm JSON that previously imported can now be rejected (see my comment on WorkflowExportImportUtils.fromComponent).


Realm exports include workflow definitions in the `workflows` array.
Realm imports restore these definitions through the workflow provider, using the same validation as workflow creation.
For an Admin Console or Admin REST API realm export, workflow definitions are included only for realm administrators who can access the Workflows API.
Secret properties declared by workflow step providers are masked in administrative exports; command-line exports retain them.

Exported definitions include workflow settings and step configuration, but not in-progress workflow executions.
Step identifiers are regenerated on import.
Workflows are restored after the other realm resources, so restoring users does not activate the imported workflows.
The workflows feature must be enabled to import workflow definitions.
When the feature is disabled, command-line exports preserve stored workflow definitions in the legacy component format; administrative exports omit them.
Restoring retained definitions requires enabling the workflows feature again.

Complete workflow component definitions from older realm exports are also accepted.
Configuration already omitted by an older administrative export cannot be recovered.
Legacy workflow components with no configuration are skipped with a warning so the rest of the realm can be imported.
Do not combine complete legacy workflow components and the `workflows` array in the same import.
Importing workflows into an existing realm through the partial-import endpoint (`POST /admin/realms/\{realm}/partialImport`) or the realm-update endpoint (`PUT /admin/realms/\{realm}`) is not supported; both endpoints ignore the `workflows` field.
Use the Workflows Admin API to manage definitions in an existing realm.

== Managing workflows through the Admin Console

To manage workflows through the Admin Console, you can follow these steps:
Expand Down Expand Up @@ -61,5 +82,3 @@ will not be processed further, and they would need to be re-associated with a ne





19 changes: 19 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,25 @@ Use the Admin REST API to manage realm default roles and full scope when the pol
This migration installs a new client registration policy provider that earlier nodes do not know.
A rolling upgrade is therefore not supported for this change; shut down the cluster and upgrade all nodes together (or use a recreate update) so that older nodes never process Dynamic Client Registration requests against the new policy components.

=== Workflow definitions in realm exports
// https://github.com/keycloak/keycloak/issues/50972

With the workflows feature enabled, realm exports now include workflow definitions in a top-level `workflows` array instead of under `components` with the type `org.keycloak.models.workflow.WorkflowProvider`.
The field is omitted when no workflows are exported.
Update tools that read workflow definitions from realm JSON to use the new field.
Administrative exports require the same realm-administrator permissions as the Workflows Admin API and mask declared workflow step secrets; command-line exports retain those secrets.

Full realm imports restore definitions through the workflow provider and apply workflow creation validation.
Complete legacy workflow components are still accepted, but must not be combined with definitions in the new `workflows` field.
Legacy workflow components with missing or empty configuration, as produced by affected administrative exports, are skipped with a warning identifying the component.
The lost configuration cannot be recovered.
Other invalid workflow definitions cause the realm import to fail.

The workflows feature must be enabled to restore workflow definitions.
When it is disabled, command-line exports retain stored definitions as legacy components, while administrative exports omit them.
Imports restore definitions only, not in-progress executions, and regenerate step identifiers.
The partial-import and realm-update endpoints ignore the `workflows` field; use the Workflows Admin API to manage workflows in an existing realm.

=== PAR metadata omitted when PAR is disabled

When the `par` feature is disabled, OpenID Connect discovery now omits `pushed_authorization_request_endpoint` from both the top-level metadata and `mtls_endpoint_aliases`, and omits `require_pushed_authorization_requests`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import org.keycloak.common.util.Time;
import org.keycloak.component.ComponentFactory;
import org.keycloak.component.ComponentModel;
import org.keycloak.models.AbstractKeycloakTransaction;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.ModelValidationException;
Expand Down Expand Up @@ -107,8 +108,7 @@ public void updateWorkflow(Workflow workflow, WorkflowRepresentation representat
// finally, update the workflow's config along with the steps' configs
workflow.updateConfig(representation.getConfig(), newSteps);

cancelScheduledWorkflow(workflow);
scheduleWorkflow(workflow);
rescheduleWorkflow(workflow);
notifyScheduleChange(workflow, false);
}
}
Expand Down Expand Up @@ -487,16 +487,34 @@ private Workflow addWorkflow(Workflow workflow) {

private void scheduleWorkflow(Workflow workflow) {
String scheduled = workflow.getConfig().getFirst(WorkflowConstants.CONFIG_SCHEDULE_AFTER);

if (workflow.isEnabled() && scheduled != null) {
initLastScheduleRun(workflow);
int intervalSecs = (int) DurationConverter.parseDuration(scheduled).toSeconds();
int initialDelaySecs = ScheduledWorkflowRunner.computeInitialDelay(workflow, intervalSecs);
TimerProvider timer = session.getProvider(TimerProvider.class);
ScheduledWorkflowRunner runner = new ScheduledWorkflowRunner(workflow.getId(), realm.getId(), intervalSecs);
timer.scheduleTask(runner, initialDelaySecs * 1000L, intervalSecs * 1000L);
scheduleLog.debugf("Scheduled workflow '%s' with interval %d s, initial delay %d s", workflow.getName(), intervalSecs, initialDelaySecs);
if (!workflow.isEnabled() || scheduled == null) {
return;
}
int intervalSecs = (int) DurationConverter.parseDuration(scheduled).toSeconds();
initLastScheduleRun(workflow);
int lastScheduleRun = ScheduledWorkflowRunner.getLastScheduleRun(workflow);
TimerProvider timer = session.getProvider(TimerProvider.class);
ScheduledWorkflowRunner runner = new ScheduledWorkflowRunner(workflow.getId(), realm.getId(), intervalSecs);
String workflowName = workflow.getName();
runAfterCommit(() -> {
long initialDelaySecs = ScheduledWorkflowRunner.computeInitialDelay(lastScheduleRun, intervalSecs);
timer.scheduleTask(runner, initialDelaySecs * 1000L, intervalSecs * 1000L);
scheduleLog.debugf("Scheduled workflow '%s' with interval %d s, initial delay %d s", workflowName, intervalSecs, initialDelaySecs);
});
}

private void runAfterCommit(Runnable task) {
// A later operation can still roll back this transaction; leave the existing timer untouched.
session.getTransactionManager().enlistAfterCompletion(new AbstractKeycloakTransaction() {
@Override
protected void commitImpl() {
task.run();
}

@Override
protected void rollbackImpl() {
}
});
}

private void initLastScheduleRun(Workflow workflow) {
Expand All @@ -508,7 +526,9 @@ private void initLastScheduleRun(Workflow workflow) {
}

void cancelScheduledWorkflow(Workflow workflow) {
session.getProvider(TimerProvider.class).cancelTask(ScheduledWorkflowRunner.taskName(workflow.getId()));
TimerProvider timer = session.getProvider(TimerProvider.class);
String taskName = ScheduledWorkflowRunner.taskName(workflow.getId());
runAfterCommit(() -> timer.cancelTask(taskName));
}

void rescheduleWorkflow(Workflow workflow) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,17 +147,17 @@ static int getLastScheduleRun(Workflow workflow) {
return val == null ? 0 : Integer.parseInt(val);
}

static int computeInitialDelay(Workflow workflow, int intervalSecs) {
static long computeInitialDelay(Workflow workflow, int intervalSecs) {
return computeInitialDelay(getLastScheduleRun(workflow), intervalSecs);
}

static int computeInitialDelay(int lastRunSecs, int intervalSecs) {
static long computeInitialDelay(int lastRunSecs, int intervalSecs) {
if (lastRunSecs <= 0) {
return intervalSecs;
}

int nextFireTime = lastRunSecs + intervalSecs;
int delay = nextFireTime - Time.currentTime();
return Math.max(0, delay);
long nextFireTime = (long) lastRunSecs + intervalSecs;
long delay = nextFireTime - Time.currentTime();
return Math.max(0L, delay);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ private void rescheduleWorkflow(KeycloakSession session, WorkflowScheduleCluster

int intervalSecs = workflowEvent.getIntervalSecs();
int lastScheduleRun = workflowEvent.getLastScheduleRun();
int initialDelaySecs = ScheduledWorkflowRunner.computeInitialDelay(lastScheduleRun, intervalSecs);
long initialDelaySecs = ScheduledWorkflowRunner.computeInitialDelay(lastScheduleRun, intervalSecs);
String realmId = session.getContext().getRealm().getId();
ScheduledWorkflowRunner runner = new ScheduledWorkflowRunner(workflowId, realmId, intervalSecs);
timer.scheduleTask(runner, initialDelaySecs * 1000L, intervalSecs * 1000L);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Copyright 2026 the original author or authors.
*
* 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;

import org.keycloak.common.util.Time;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class ScheduledWorkflowRunnerTest {

@Test
public void testWithoutPreviousRun() {
assertEquals(Integer.MAX_VALUE, ScheduledWorkflowRunner.computeInitialDelay(0, Integer.MAX_VALUE));
}

@Test
public void testMaximumInterval() {
assertDelay(Time.currentTime(), Integer.MAX_VALUE);
}

@Test
public void testPreviousRunAheadOfLocalClock() {
assertDelay(Time.currentTime() + 60, Integer.MAX_VALUE);
}

@Test
public void testOverdueRun() {
assertDelay(Time.currentTime() - 120, 60);
}

@Test
public void testOrdinaryInterval() {
assertDelay(Time.currentTime() - 10, 60);
}

private static void assertDelay(int lastRun, int interval) {
int before = Time.currentTime();
long delay = ScheduledWorkflowRunner.computeInitialDelay(lastRun, interval);
int after = Time.currentTime();
long nextRun = (long) lastRun + interval;
assertTrue("Delay must not be shortened by overflow", delay >= Math.max(0L, nextRun - after));
assertTrue("Delay must not exceed the remaining interval", delay <= Math.max(0L, nextRun - before));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.models.workflow.WorkflowProvider;
import org.keycloak.organization.OrganizationProvider;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.ComponentExportRepresentation;
Expand Down Expand Up @@ -254,8 +255,20 @@ public static RealmRepresentation exportRealm(KeycloakSession session, RealmMode

// components
MultivaluedHashMap<String, ComponentExportRepresentation> components = exportComponents(realm, realm.getId());
boolean keepLegacyComponents = !Profile.isFeatureEnabled(Feature.WORKFLOWS)
&& !options.isPartial() && options.isWorkflowsIncluded();
if (!keepLegacyComponents) {
components.remove(WorkflowProvider.class.getName());
}
rep.setComponents(components);

if (options.isWorkflowsIncluded() && Profile.isFeatureEnabled(Feature.WORKFLOWS)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor. This sets the field unconditionally, and the mapper uses NON_NULL rather than NON_EMPTY, so every realm export now gains a "workflows": [] entry even when the realm has no workflows at all.

Neighbouring collections guard on emptiness (if (!users.isEmpty()) rep.setUsers(users), and the same for client scope mappings). Worth matching so existing export fixtures do not pick up the noise.

var workflows = WorkflowExportImportUtils.exportWorkflows(session, realm);
if (!workflows.isEmpty()) {
rep.setWorkflows(workflows);
}
}

// Message Bundle
rep.setLocalizationTexts(realm.getRealmLocalizationTexts());

Expand Down
Loading