8000 feat: event-hook system by paulwer · Pull Request #48168 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content

feat: event-hook system - #48168

Open
paulwer wants to merge 17 commits into
keycloak:mainfrom
paulwer:feat-event-hooks
Open

paulwer wants to merge 17 commits into
keycloak:mainfrom
paulwer:feat-event-hooks

Conversation

@paulwer
@paulwer paulwer commented Apr 16, 2026 •
Copy link
Copy Markdown
Contributor

closes #41065

Summary

This PR introduces an event-hook system for Keycloak with an extensible provider model, persistent delivery state, admin REST support, admin UI integration, import/export support, documentation, and test coverage.

The goal is to make realm events available through configurable hook targets while keeping the design open for additional target types beyond the built-in implementations.

If this PR is to big, I would also be up for introducing only webhook support for now and adding the other providers with seperate PRs. Keeping the db schema able to grow.

What I Implemented

  • added the event-hook domain model and representations for targets, messages, logs, providers, and test results
  • introduced EventHookTargetSpi and EventHookStoreSpi so hook targets and storage are extensible
  • added JPA entities and changelog entries for storing hook targets, queued messages, and delivery logs
  • implemented the event-hook listener/delivery flow in services, including payload building and delivery related task handling (batch handling, retry backoff, automatic disablement)
  • added built-in providers for:
    • HTTP delivery (timeout, hmac, headers)
    • pull-based delivery (additional http consume endpoint)
    • SQL delivery (prepared statements using jdbc)
    • email (using a custom email template, leveraging freemarker for templating data)
  • added admin endpoints and admin client bindings for CRUD of targets, messages and logs, test specific events and target configs and manual retry of failed messages
  • temp auto disable target handling f.ex. when recieving 429 http status to avoid getting instance blocked
  • integrated the feature into the admin UI with target management, dialogs, and log views
  • partial import/export support for event-hook targets
  • documentation
  • initial backend/UI tests

Notes / ToDo

  • Export, Import & SQL-target was not tested fully in the UI yet.
  • I will explore if a better data structure for default delivery would be an improvement
  • i will check on custom body mapping (http/pull)
  • Improve Docs
  • Check Table Naming Overlaps with existing plugins/extensions (already did roughly, but will verify again)
  • custom events for auto disable and failed deliveries (+ avoid loops)
  • Delete Conditions f.ex. with same lifetime as in events should be explored to remove events automaticly. Maybe a custom lifetime should be able to set.

Feedback Requested

first of all: this is a first draft and I know thats a huge one. you may explain the way forward your team wants to take. I am open for any code changes, a smaller initial PR for better review capabilities with roadmap of future changes or to hand over the initial draft so your team can align it to the repository styles I might not fully know. Feel free to explain what works best for yall and thanks for the time put in for reviewing/considdering it. :)

I would appreciate feedback especially on these points:

  • Is the current SPI/provider setup ready for extensions and future provider types?
  • Does the store/delivery approach look scalable enough in clustered environments? could it block something or lead to exessive resource usage? maybe some more guardrails have ti be enforced? do we have to think about something specific here?
  • Are there obvious gaps in the retry / batch / logging / target management model from your POV?
  • If you see places where the design should be tightened, please suggest improvements. Any nameing changes?
  • Should we realy allow public pull endpoints? (currently there is a security warning in the ui and secret can be set optionaly)
  • Do you see any issues with jdbc on runtime connecting to several database types, which are not necessary the same as the keycloak db itself. => are all drivers still available after running optimize? I did used h2 als db and connected to postgres without problems localy.
  • Do you see a security risk for using the sql target (just want to be sure)
  • I do see an option to omit the logs table if you dont want to support and handle an additional table. Opinion?
  • should this system/ui be behind a feature flag?
  • Any additional target-types wanted?
  • i touched some shared admin ui components to implement some functionalities. please verify for breaking changes!
  • Is freemarker the right choice for body (f.ex. json/XML) generation here? (as an alternative to the default)

Screenshots

Targets

image

Create/Update Target

No Target Type Selected

image

HTTP (no bulk, no retry)

image

HTTP (with bulk, with retry)

image

PULL (without secret)

image

PULL (with secret)

image

SQL(UI was reworked since this foto)

image

Logs

Filter

image

Normal and Batched Logs

image image (not completed yet)

Webhook Recieved (no batch)

image

Webhook Recieved (batch)

image

Pull (no batch)

image

Pull (batch)

image

SQL

image

@vramik
vramik requested review from pedroigor, sguilhen and vramik April 16, 2026 16:59
@paulwer
paulwer commented Apr 18, 2026 •
Copy link
Copy Markdown
Contributor Author

Hi team,
I wanted to share an idea/motivation about improving workflows regarding user communication (f.ex. email step). (all outside scope of this PR but worth for a quick lookahead now while designing the system)

At the moment, the workflow system is not able to trigger an event. I envision adding a third event type next to user and admin events —custom events— which can be triggered by the workflow system with the entity + custom data.
By combining custom events with the event hook system, we can keep workflows flexible and decoupled from specific actions and could allow customizing currently very static and native keycloak functionality f.ex. when user is registered/custom actions are requested etc.
This will also enable diverse integrations, such as for email, http, sql, pull or other external future systems. Workflows would be more predictable and might not need complex logging, because event hook already has.
As a result, I believe the current email step might no longer be necessary.

It could also be worth considdering migrating existing emails to the event-hook system as well. this would allow better monitoring, customization (content and usage of email to be send for specify action or not). (2 main problems: event-hook system is async, current events are often sync and give response back in rest api + compatibility of existing template system)

I’d love to hear your feedback on those ideas, and if you have any concerns, please let me know or have a discussion.

Thanks!

@vramik
vramik commented Apr 27, 2026
Copy link
Copy Markdown
Contributor

Thanks for the contribution! JJust a heads up. Unfortunately, we don't have the capacity to review this right now, but we do intend to get back to it. We'll follow up when we're able to pick it up.

@paulwer
paulwer commented Apr 27, 2026
Copy link
Copy Markdown
Contributor Author

first of all: this is a first draft and I know thats a huge one. you may explain the way forward your team wants to take. I am open for any code changes, a smaller initial PR for better review capabilities with roadmap of future changes or to hand over the initial draft so your team can align it to the repository styles I might not fully know. Feel free to explain what works best for yall and thanks for the time put in for reviewing/considdering it. :)

@vramik thanks for your response. would it be possible do a rought review of the included features and report back if they could be part of keycloak.
I would considder this the next step instead of a deep dive into the programmcode and would like this to be done before I continue invest more time to refine the PR and make it ready to be merged from my POV.
I think this would reduce amount of effort for reviewing for your team as well.
I can provide a more complete and detailed list of all currently included features, if the above messages are not whats necessary to provide feedback.

# Conflicts:
#	docs/documentation/release_notes/topics/26_7_0.adoc
#	docs/documentation/upgrading/topics/changes/changes-26_7_0.adoc
#	js/libs/ui-shared/src/controls/table/KeycloakDataTable.tsx
#	model/jpa/src/main/resources/META-INF/jpa-changelog-26.7.0.xml
@paulwer
paulwer commented Jun 22, 2026
Copy link
Copy Markdown
Contributor Author

@vramik @stianst sorry to bother your work :)
Do you have a timeline/guess, when do you expect to be able to revisit this topic?

I really hope to be able to merge it this year if thats possible 🙈

paulwer added 4 commits July 10, 2026 20:28
…-event-hooks

# Conflicts:
#	docs/documentation/release_notes/topics/26_7_0.adoc
#	docs/documentation/upgrading/topics/changes/changes-26_7_0.adoc
#	model/jpa/src/main/java/org/keycloak/events/jpa/JpaEventStoreProvider.java
#	model/jpa/src/main/resources/META-INF/jpa-changelog-26.7.0.xml
@paulwer
paulwer marked this pull request as ready for review August 14, 2026 07:53
@paulwer
paulwer requested a review from a team as a code owner August 14, 2026 07:53
Copilot AI balanced review requested due to automatic review settings August 14, 2026 07:53
@paulwer
8000 paulwer requested a review from a team as a code owner August 14, 2026 07:53
Copilot AI left a comment
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.

Pull request overview

Introduces an extensible event-hook system spanning persistence, delivery providers, administration APIs, UI, import/export, documentation, and tests.

Changes:

  • Adds HTTP, pull, SQL, and email delivery providers with batching, retries, logging, and retention.
  • Adds JPA storage, SPIs, REST/admin-client APIs, and import/export support.
  • Adds Admin UI management, filtering, testing, documentation, and automated tests.

Reviewed changes

Copilot reviewed 141 out of 141 changed files in this pull request and generated 12 comments.

Show a summary per file
File(s) Description
themes/.../event-hook-notification.ftl (HTML/text), messages_en.properties Email-hook templates and subject
services/src/test/.../events/hooks/*Test.java Provider, filtering, payload, and validation tests
services/src/main/resources/META-INF/services/* Registers hook providers, listener, and resource
services/.../RealmAdminResource.java Admin endpoint and partial export
services/.../partialimport/* Partial-import support
services/.../events/hooks/* Delivery providers, listener, scheduling, payloads, pull API, and retry handling
services/.../EventHooksResource.java Event-hook Admin REST API
services/pom.xml Test dependency
server-spi-private/.../events/hooks/* Hook SPIs, models, contracts, filters, and representations
server-spi-private/.../models/utils/* Export secret redaction
server-spi-private/.../ExportOptions.java Hook export option
server-spi-private/.../ResourceType.java Partial-import resource type
server-spi-private/.../META-INF/services/org.keycloak.provider.Spi Registers hook SPIs
model/storage-private/.../DefaultExportImportManager.java Realm import support
model/storage-private/.../ExportUtils.java Conditional hook export
model/jpa/.../events/hooks/jpa/* JPA entities and store implementation
model/jpa/.../JpaEventStoreProvider.java Event-store cleanup integration
model/jpa/.../JpaEventStoreProviderTest.java Cleanup tests
model/jpa/.../default-persistence.xml Registers hook entities
model/jpa/.../jpa-changelog-26.7.0.xml Hook database schema
js/libs/keycloak-admin-client/src/resources/* Event-hook and export client APIs
js/libs/keycloak-admin-client/src/defs/*Representation.ts TypeScript API representations
js/libs/keycloak-admin-client/src/client.ts Exposes event-hook client
js/libs/ui-shared/src/select/SingleSelect.tsx Placeholder support
js/apps/admin-ui/src/events/hooks/* Target management, testing, logs, icons, and routing
js/apps/admin-ui/src/events/* Hook tabs and links from existing events
js/apps/admin-ui/src/realm-settings/PartialImport.tsx Hook partial import UI
js/apps/admin-ui/src/realm-settings/PartialExport.tsx Hook partial export UI
js/apps/admin-ui/src/components/* Dynamic input option support
js/apps/admin-ui/src/Banners.tsx Hook event warning banner
js/apps/admin-ui/test/events/hooks.spec.ts End-to-end hook tests
js/apps/*/messages/messages_en.properties UI translations
integration/admin-client-core/.../RealmResource.java Java admin-client export binding
docs/documentation/server_admin/topics/events.adoc Includes hook documentation
docs/documentation/server_admin/topics/events/hooks.adoc Event-hook administrator guide
docs/documentation/release_notes/topics/26_8_0.adoc Release notes
core/.../RealmRepresentation.java Realm hook serialization
core/.../PartialImportRepresentation.java Partial-import hook payload
core/.../EventHook*Representation.java REST representation classes
Suppressed comments (1)

server-spi-private/src/main/java/org/keycloak/events/hooks/EventHookTargetEventFilter.java:53

  • A target can have null settings, and this dereference then throws instead of applying the documented wildcard default. Treat null settings the same as a missing filter.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +59 to +60
ExecutorService executor = session.getProvider(ExecutorsProvider.class).getExecutor(EXECUTOR_NAME);
groupByTarget(reservedMessages).forEach(batch -> executor.submit(() -> processBatch(batch)));
Comment on lines +133 to +137
EventHookDeliveryResult result;
try {
result = batchExecution
? provider.deliverBatch(target, batch)
: provider.deliver(target, batch.get(0));
Comment on lines 76 to 78
public void clear() {
deleteEventHookMessagesForAllUserEvents();
em.createQuery("delete from EventEntity").executeUpdate();
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Paul Werner <52678724+paulwer@users.noreply.github.com>
Copilot AI review requested due to automatic review settings August 14, 2026 11:31
Copilot AI left a comment
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.

Pull request overview

Copilot reviewed 141 out of 141 changed files in this pull request and generated 2 comments.

Suppressed comments (6)

integration/admin-client-core/src/main/java/org/keycloak/admin/client/resource/RealmResource.java:321

  • Changing this client method from two parameters to three breaks every existing caller; the repository still has multiple partialExport(false, false) calls that will no longer compile. Preserve the two-argument overload and add the new overload separately.
    RealmRepresentation partialExport(@QueryParam("exportGroupsAndRoles") Boolean exportGroupsAndRoles,
                                      @QueryParam("exportClients") Boolean exportClients,
                                      @QueryParam("exportEventHookTargets") Boolean exportEventHookTargets);

services/src/main/java/org/keycloak/events/hooks/EventHookDeliveryTask.java:60

  • Flattening target groups and submitting every split batch separately allows up to maxPollBatchSize concurrent deliveries to the same target. Besides creating a request/connection burst, these transactions race on consecutive429Count, so lost updates can prevent automatic disablement; submit one task per target and process that target's batches sequentially.
    services/src/main/java/org/keycloak/events/hooks/EventHookEventListenerProvider.java:81
  • This callback opens targetSession, but createMessage queries the store through the listener's original session, whose transaction has already completed because this listener is enlisted after completion. Pass targetSession/store into createMessage so aggregation queries run in the new transaction and work with non-JPA store implementations too.
    model/jpa/src/main/java/org/keycloak/events/hooks/jpa/JpaEventHookStoreProvider.java:347
  • This query loads and sorts every retained log for the realm, then discards all but one status per target in Java. On an active realm this makes each Targets-page request grow with the entire 30-day log volume; select only the latest log per target in the database.
    services/src/main/java/org/keycloak/events/hooks/SqlEventHookTargetProviderFactory.java:50
  • Realm exports replace this required value with ********; during import normalizeConfig removes that sentinel and validation then rejects the target because jdbcUrl is missing. Consequently, a realm containing a SQL hook cannot round-trip through full or partial export/import; define import semantics for redacted required SQL settings (for example, import the target disabled pending credential reconfiguration).
    services/src/main/java/org/keycloak/events/hooks/EventHookEventListenerProviderFactory.java:76
  • The listener is globally invoked for every user and admin event, and each callback opens a new transaction and queries the target table even when no realm has configured hooks. This adds a database transaction to every login/admin operation on otherwise unused installations; gate the listener behind the advertised preview feature or maintain a cheap realm-level enabled-target signal.

Comment on lines +58 to +63
public static EventHookTargetRepresentation redactRepresentation(KeycloakSession session, EventHookTargetRepresentation representation) {
EventHookTargetProviderFactory provid 10BC8 erFactory = findProviderFactory(session, representation.getType());
if (providerFactory != null) {
representation.setSettings(providerFactory.redactConfig(representation.getSettings()));
}
return representation;
Comment on lines +34 to +35
@Column(name = "REALM_ID", length = 36, nullable = false)
private String realmId;
Copilot AI review requested due to automatic review settings August 14, 2026 12:29
Copilot AI left a comment
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.

Pull request overview

Copilot reviewed 141 out of 141 changed files in this pull request and generated 3 comments.

Suppressed comments (8)

services/src/main/java/org/keycloak/events/hooks/PullEventHookTargetEndpointResource.java:132

  • When pullSecret is absent, this public realm endpoint returns queued event payloads without any authentication. Require a secret (or another authenticated mechanism) at target validation and consumption time; the existing endpoint test already expects an unauthenticated secretless target to be rejected.
    server-spi-private/src/main/java/org/keycloak/events/hooks/EventHookTargetRepresentationUtil.java:53
  • If an extension provider is removed or fails to load, this fallback returns all stored settings unchanged even when redactSecrets is true. Admin REST responses and realm exports can therefore disclose that provider's credentials; use a fail-closed fallback that omits or redacts unknown settings.
    model/jpa/src/main/java/org/keycloak/events/jpa/JpaEventStoreProvider.java:277
  • Admin-event expiration also deletes hook messages regardless of delivery status, which can silently cancel pending retries or unconsumed pull events. Keep hook retention independent, or delete only terminal hook messages here.
    services/src/main/java/org/keycloak/events/hooks/EventHookDeliveryTask.java:137
  • Provider delivery performs HTTP, SMTP, or external JDBC I/O inside runJobInTransaction, holding a Keycloak transaction and database connection for the full external timeout. Under concurrent deliveries this can exhaust the pool; claim in a short transaction, perform I/O after it closes, then persist the result in a new transaction guarded by the claim.
    model/jpa/src/main/java/org/keycloak/events/hooks/jpa/JpaEventHookStoreProvider.java:348
  • This loads every non-test delivery log for the realm and discards all but one per target in Java. With 30 days of high-volume hook history, merely listing targets can materialize millions of rows; select only the latest log per target in the database.
    docs/documentation/server_admin/topics/events/hooks.adoc:176
  • Target tests do write test outbox messages and a delivery log (createMessages followed by createTestExecution), so this API description is incorrect.
* Test a target without writing regular outbox messages or delivery logs.

docs/documentation/server_admin/topics/events/hooks.adoc:180

  • The implemented retry resource is execution-based at /executions/{executionId}/retry; this documented message-based URL does not exist.
* Retry failed, exhausted, or dead messages through `POST /admin/realms/{realm}/event-hooks/messages/{messageId}/retry`.

docs/documentation/server_admin/topics/events/hooks.adoc:197

  • The listener reads the setting executionTimeoutMillis, so the generated CLI option is execution-timeout-millis; the documented claim-timeout-millis option has no effect.
* `spi-events-listener--event-hooks--claim-timeout-millis`

String realmId = (String) row[0];
long expiration = (Long) row[1];
long eventTime = currentTimeMillis - (expiration * 1000);
deleteExpiredEventHookMessages(List.of(realmId), eventTime, EventHookSourceType.USER);
Comment on lines +127 to +130
SqlPreparedStatementTemplate preparedStatement = SqlPreparedStatementTemplate.from(sqlStatement, settings.get("sqlParameters"));
if (placeholderCount(preparedStatement.statement()) != preparedStatement.parameterMappings().size()) {
throw new IllegalArgumentException("Prepared statement placeholder count must match configured SQL parameters");
}
Comment on lines +74 to +76
public void create(RealmModel realm, KeycloakSession session, EventHookTargetRepresentation resourceRep) {
session.getProvider(EventHookStoreProvider.class).createTarget(
EventHookTargetRepresentationUtil.toModel(session, realm, resourceRep, null, currentTimeMillis(), true, true));
@paulwer
paulwer commented Nov 4, 2026 •
Copy link
Copy Markdown
Contributor Author

@vramik @sguilhen sorry to bother you again :)
Is there a rough timeline, when you expect to revisit this PR or anything I can optimise for you to improve review readiness?

@rojan-rijal
Copy link
Copy Markdown

Hi @paulwer, thanks for this PR. I’m not affiliated with the Keycloak project; I came across this while reviewing the branch (at b30e47d). I think one issue should be fixed before merge.

EventHookBodyMappingSupport.templateConfiguration() (line 161) creates a new Configuration(VERSION_2_3_32) without setting a class resolver for the ?new built-in. In FreeMarker 2.3.32 the default is TemplateClassResolver.UNRESTRICTED_RESOLVER (Configurable.java:477). A template can therefore use ?new to instantiate freemarker.template.utility.Execute and run OS commands as the Keycloak process user.

Keycloak’s own DefaultFreeMarkerProvider (line 67) sets ALLOWS_NOTHING_RESOLVER to prevent exactly this. The new code doesn’t. The custom ObjectWrapper only restricts the data model and has no effect on ?new.

Suggested fix:

configuration.setNewBuiltinClassResolver(TemplateClassResolver.ALLOWS_NOTHING_RESOLVER);
configuration.setAPIBuiltinEnabled(false); // already the default, but worth making explicit

Better still would be to derive this configuration from Keycloak’s existing FreeMarkerProvider settings, so the two can’t drift apart. I’d also suggest a regression test that a template using ?new fails at render time, not just at validation, covering both the body-mapping path and the email path.

@sguilhen
Copy link
Copy Markdown
Contributor

@pedroigor @stianst how much of a priority would this be for us? I've seen requests for Webhook support a few times already and we have this contribution. Its quite large, so if there's interest we will need to put some time into it.

Copilot AI balanced review requested due to automatic review settings November 23, 2026 12:10
Copilot AI left a comment
Copy link
Copy Markdown
Contributor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Built-in Webhook Support for Keycloak Events

6 participants

0