Repository navigation
feat: event-hook system - #48168
feat: event-hook system#48168paulwer wants to merge 17 commits into
Conversation
|
Hi team, 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. 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! |
|
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. |
@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. |
# 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
…-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
There was a problem hiding this comment.
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.
| ExecutorService executor = session.getProvider(ExecutorsProvider.class).getExecutor(EXECUTOR_NAME); | ||
| groupByTarget(reservedMessages).forEach(batch -> executor.submit(() -> processBatch(batch))); |
| EventHookDeliveryResult result; | ||
| try { | ||
| result = batchExecution | ||
| ? provider.deliverBatch(target, batch) | ||
| : provider.deliver(target, batch.get(0)); |
| 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>
There was a problem hiding this comment.
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
maxPollBatchSizeconcurrent deliveries to the same target. Besides creating a request/connection burst, these transactions race onconsecutive429Count, 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, butcreateMessagequeries the store through the listener's originalsession, whose transaction has already completed because this listener is enlisted after completion. PasstargetSession/storeintocreateMessageso 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 importnormalizeConfigremoves that sentinel and validation then rejects the target becausejdbcUrlis 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.
| 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; |
| @Column(name = "REALM_ID", length = 36, nullable = false) | ||
| private String realmId; |
There was a problem hiding this comment.
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
pullSecretis 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
redactSecretsis 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 (
createMessagesfollowed bycreateTestExecution), 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 isexecution-timeout-millis; the documentedclaim-timeout-millisoption 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); |
| 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"); | ||
| } |
| public void create(RealmModel realm, KeycloakSession session, EventHookTargetRepresentation resourceRep) { | ||
| session.getProvider(EventHookStoreProvider.class).createTarget( | ||
| EventHookTargetRepresentationUtil.toModel(session, realm, resourceRep, null, currentTimeMillis(), true, true)); |
|
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.
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: 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. |
|
@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. |
…eateConfiguration() for consistency
There was a problem hiding this comment.
🔵 Needs a closer look
When a target provider is unavailable, secret redaction returns raw settings, exposing stored credentials through admin responses and partial exports.
9 open issues
Imports always normalize withexisting == null, including after anOVERWRITEremoved the old… This counts every?, including characters in quoted literals/comments and PostgreSQL JSON… Realm event expiration can be shorter than a hook retry or pull-consumption window, so this removes… This realm-owned table has neither a JPA relationship nor a schema foreign key/cascade toREALM,… When an extension provider is unavailable, this skips redaction and exports its settings verbatim,… Clearing the user-event audit store now also deletes event-hook outbox rows, includingPENDINGor… These workers are submitted while the scheduler's reservation transaction is still open;… When no secret is configured, this public realm endpoint returns and consumes user/admin event… Provider delivery performs HTTP/JDBC/email I/O insiderunJobInTransaction, holding a database…
Review effort: Balanced


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
EventHookTargetSpiandEventHookStoreSpiso hook targets and storage are extensibleNotes / ToDo
SQL-targetwas not tested fully in the UI yet.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:
Screenshots
Targets
Create/Update Target
No Target Type Selected
HTTP (no bulk, no retry)
HTTP (with bulk, with retry)
PULL (without secret)
PULL (with secret)
SQL(UI was reworked since this foto)
Logs
Filter
Normal and Batched Logs
Webhook Recieved (no batch)
Webhook Recieved (batch)
Pull (no batch)
Pull (batch)
SQL