Repository navigation
Emit RISC account-purged SSF events on user deletion - #51870
Conversation
7475587 to
d4bb957
Compare
|
Also see graphical design document: |
There was a problem hiding this comment.
Pull request overview
Adds RISC account-purged SSF events for admin and self-service user deletions.
Changes:
- Introduces and registers the
account-purgedevent. - Captures deleted-user snapshots for subject resolution and filtering.
- Adds documentation, unit tests, and integration coverage.
Reviewed changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
docs/guides/securing-apps/ssf-support.adoc |
Documents purge events and known gaps. |
ssf/core/src/main/java/org/keycloak/ssf/event/DefaultSsfEventProviderFactory.java |
Registers the event type. |
ssf/core/src/main/java/org/keycloak/ssf/event/risc/RiscAccountPurged.java |
Defines the event payload. |
ssf/core/src/test/java/org/keycloak/ssf/event/risc/RiscAccountEventsTest.java |
Tests serialization. |
ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/event/SecurityEventTokenMapper.java |
Maps deletion events to purge SETs. |
ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/event/SsfTransmitterEventListener.java |
Resolves deleted users from snapshots. |
ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/event/SsfTransmitterEventListenerFactory.java |
Registers snapshot capture. |
ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/subject/PurgedUserSnapshot.java |
Implements request-scoped user snapshots. |
ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/subject/SubjectSubscriptionFilter.java |
Applies snapshots during subscription checks. |
ssf/transmitter/src/test/java/org/keycloak/ssf/transmitter/event/SecurityEventTokenMapperTest.java |
Tests mapper gates and payloads. |
ssf/tests/base/src/test/java/org/keycloak/tests/ssf/transmitter/SsfTransmitterAccountPurgedEventTests.java |
Adds end-to-end purge coverage. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
Keycloak deletes the user row before firing the admin or user event that drives SSF emission, so by the time the transmitter runs every lookup of the deleted user returns null. That affected the whole pipeline, not just the subject: the admin path bailed out before building a token at all, the email and +tenant subject formats had nothing to resolve, and the dispatch-time subject gate saw an unresolvable user and dropped the event under the default default_subjects=NONE. Capture a read-only snapshot of the user on UserModel.UserPreRemovedEvent, the last hook that runs while the user still exists, and stash it on the session for the rest of the request. The snapshot is itself a UserModel, so the subject filter, the inclusion resolver and the email lookup work against it unchanged; only organization membership needs explicit handling, since getByMember is an id-keyed query rather than an attribute read and a detached user cannot answer it. Nothing downstream needs the snapshot: narrowing, signing and encoding all happen inline on the request thread, and the outbox replays stored bytes. So it never has to outlive the request or be persisted. Emission stays on the admin/user event path rather than on the provider events, because those fire for deletions that are not purges. A partial import under the OVERWRITE policy deletes and immediately recreates the user, and removing a client deletes its service-account user; both are kept out by the operation type and resource type, and both are pinned by tests so a future widening of the path matching cannot start emitting spurious data-retention signals. Fixes keycloak#48899 Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
…state Review follow-up to the account-purged support. The snapshot copied each organization's ssf.* attributes and answered the subject gate's org questions itself. That hardcoded the default attribute semantics and bypassed SsfSubjectInclusionResolver, a documented extension point -- so a deployment overriding it got one verdict for every event type and a different one for purges. Organizations outlive the user, which buildTenantSubjectFromSnapshot already depends on. So capture only the aliases and re-resolve live OrganizationModels at filter time. All three org branches now run the same code for purged and live users, and the resolver stays authoritative for both. getByMember is left as the single thing being substituted, which is what the class javadoc already claimed the exception was. Also bound snapshot retention. The workflow delete step removes every due user on one session and fires no admin or user event, so those snapshots are never read; without a cap a retention run purging tens of thousands of accounts would hold every one of them for the life of the session. Smaller fixes from the same review: verify the realm on snapshot lookup rather than trusting the user id alone; normalize the email index key with KeycloakModelUtils.toLowerCaseSafe so it matches how the adapter stores the address; document the workflow-delete gap on RiscAccountPurged and in the guide, since a data-retention deletion is exactly what a receiver would expect account-purged to cover; and refresh the canConvert(AdminEvent) javadoc, which still listed three admin paths. Adds an integration test for the org-excluded branch, and a wire-format test pinning that account-purged carries no reason claim. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
The snapshot cap added in the previous commit bounded memory, but it would have become a silent correctness bug: once workflow-driven deletions do emit purge events -- the gap documented on RiscAccountPurged -- a cap would stop capturing partway through a bulk run, so purges past that point would stop being emitted with no error and no log at default level. That is the same silent-failure mode this feature otherwise works hard to avoid, and the constant had no principled basis besides being large. Gate on an active HTTP request instead. A snapshot exists solely to serve the admin or user event fired later in the same request, so a deletion with no request behind it can never produce one and capturing only retains data that nothing will read. That is exactly the bulk case that motivated the cap: DefaultWorkflowProvider.runScheduledSteps drives every due step for every enabled workflow on one session, deleting a user per iteration. The gate stays correct when those paths gain purge support, because emission for them cannot use the request-bound listener path anyway -- so unlike a cap, it will not have to be removed or become a hazard. QuarkusKeycloakContext returns an empty Optional when no RESTEasy request context is active, which DefaultKeycloakContext turns into ContextNotActiveException, so absence has to be detected by catching rather than null-checking. Any failure is read as "no request": the cost is a purge event not emitted on a path that has none to emit, which is strictly better than unbounded retention. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
The request-context gate excludes deletions with no request behind them, but bulk deletion also happens inside a request: a partial import under the OVERWRITE policy replaces many users in one call, and deleting an organization removes each of its managed members. Neither emits a purge event, so those snapshots are never read, and nothing released them until the request ended. Recognising bulk paths is not a reliable option. A partial import leaves no marker at all, and the organization context flag is also set for ordinary single-member removals, so keying off it would skip capture for a deletion that should emit. "Bulk" is also open-ended -- any future path would have to be added to the list. Invert it instead: the listener discards each snapshot once it has emitted for that deletion. A request that deletes users and emits for them now returns to zero retained snapshots after each one, so it can delete any number without accumulating; only snapshots that are never consumed build up, which is exactly the bulk case where the snapshot was dead weight from the moment it was taken. A per-request cap remains as a backstop for anything neither mechanism anticipates. It logs at WARN rather than DEBUG: dropping a snapshot can only ever cost an event, and that must not happen quietly. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
UserStorageManager.removeUser published UserPreRemovedEvent after calling getFederatedStorage().preRemove, which deletes the user's federated attributes, group memberships, credentials and broker links. A listener therefore observed a user that had already lost part of its state, which the "pre removed" name does not lead anyone to expect. For SSF this silently broke federated users: the account-purged snapshot read ssf.notify.* and the removal-grace tombstones after they had been deleted, so a subscribed federated user's purge was dropped under the default default_subjects=NONE. It also appears to affect the only other consumer of the event. InfinispanOrganizationProviderFactory calls getByMember(event.getUser()) to register organization member invalidations, and organization membership is group membership -- which deleteFederatedUserGroupMembershipsByUser has already removed by that point. For a federated user that lookup returns nothing, so the invalidation is skipped. Publishing first restores it. Non-federated users are unaffected either way: their attributes live in USER_ATTRIBUTE, which that pre-removal does not touch. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
d2fb76c to
ae7816b
Compare
SsfSubjectInclusionResolver documents group-attribute lookups and role-based opt-ins as supported extension points, with a worked isInNotifyGroup example. The snapshot never populated either, so AbstractInMemoryUserAdapter reported an empty membership set for a purged user and a resolver doing either would reach a different verdict than it does for a live user -- suppressing purges for subscribed accounts. This is the same defect the organization handling was already fixed for, so it takes the same shape rather than a parallel mechanism: the adapter stores only group and role ids and resolves them back through the realm on read, so nothing about the groups or roles themselves is copied and they outlive the user. The membership rows are deleted by JpaUserProvider.removeUser, which runs after this hook, so they are still readable at capture time. Reported by Copilot in PR review. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
The dispatcher's subject gate resolved the token's subject live-first, falling back to the snapshot only when nothing was found. For an account-purged SET that is the wrong precedence: in a realm that allows duplicate emails, getUserByEmail returns the first surviving match, so an `email` subject could resolve to a *different* account that happens to share the address. The gate then evaluated that user's notification state instead of the purged user's and silently dropped the purge under the default default_subjects=NONE. Make the precedence event-aware rather than reordering outright: a token carrying RiscAccountPurged prefers the snapshot, since its subject names a user that was deleted in this same request and cannot legitimately resolve to anyone else. Every other event keeps the live-first order, which matters -- a blanket snapshot-first would wrongly resolve a live user's event to the snapshot of a deleted user sharing their email. Adds a regression test: two users share an address, only the purged one is subscribed, default_subjects=NONE. Before the fix the gate resolved the survivor and suppressed the event. Reported by Copilot in PR review. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
Snapshots were keyed on user id alone, with a realm comparison afterwards that returned true whenever either realm was unavailable. User ids are realm-unique in practice, but the external-id component of a federated id is not guaranteed to be, and a cross-realm hit would gate one realm's event on another realm's subject. Put the realm id in the key instead, for both the primary and the email index. Scoping is free and strictly stronger than comparing after the fact, so the permissive matchesRealm helper is deleted rather than tightened: a snapshot can now only be found from the realm it was captured in. Lookup and discard require a realm accordingly. Reported by Copilot in PR review. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
The snapshot discard runs in a finally, by which point the event has already been emitted -- but it resolved the realm as an argument, outside any guard. session.getContext().getRealm() can throw on its own (an inactive context, a realm that no longer resolves), and that would have failed the whole listener invocation after the work it protects had already succeeded. Resolve the realm lazily inside the guarded call and swallow any runtime failure, logging at debug. The cost of a failed discard is one snapshot retained until the session ends, which is strictly better than discarding successful event delivery. Reported by Copilot in PR review. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
There was a problem hiding this comment.
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Pull request overview
Copilot reviewed 16 out of 16 changed files in this pull request and generated 3 comments.
The account-purged generator looked its snapshot up under the context realm while SsfTransmitterEventListener resolves the realm from the admin event's own realm id. They agree today -- the admin API sets the context realm to the realm being administered, and AdminEventBuilder stamps that same realm onto the event -- but having two resolutions on one path is a trap: a snapshot looked up under a realm other than the one it was captured under misses silently, and a missed lookup is exactly what disables the READ_ONLY / UNSYNCED suppression the generator added. No test would have caught that either, since a missed lookup and a genuinely local user both fall through to emitting. Resolve it once, preferring the admin event's realm and falling back to the context for the self-service path, which has no admin event. Also returns the memoized organization list unmodifiable. It is handed out to callers and reused for every later subject-gate question in the request, so a caller mutating it would change verdicts downstream; the live-user branch already returned an immutable list. Reported by Copilot in PR review. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
There was a problem hiding this comment.
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Pull request overview
Copilot reviewed 16 out of 16 changed files in this pull request and generated 4 comments.
The subject gate only ever asks "is any of the user's organizations ...", so pass the predicate in rather than returning the collection. A live user's membership stream then short-circuits again -- anyMatch stops at the first hit instead of loading every membership, three times per receiving stream -- while a snapshot still answers from its memoized list. This is what an earlier round dismissed. That reply was right that a lazily returned stream cannot escape runWithoutAuthorization, since it would run its query after the scope closed and be filtered after all, but wrong to conclude nothing could restore the short-circuit: passing the predicate in consumes the stream inside the scope, which sidesteps the problem entirely. Also renames the capture-time helper to resolveLocalRemovalOnly. It differed from the public accessor only in arity, enough that the javadoc had to disambiguate by signature. And drops the second snapshot lookup on the purge path. When preferSnapshot is set and the first lookup misses, the fallback at the end repeated the identical call; nothing between them captures a snapshot, so the answer could not have changed. Reported by Copilot in PR review. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
There was a problem hiding this comment.
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Pull request overview
Copilot reviewed 16 out of 16 changed files in this pull request and generated 4 comments.
CI's Build job runs spotless:check across the reactor, and two violations from earlier commits on this branch failed it before a single test ran. The AdminPermissionsSchema import was inserted after org.keycloak.events.Details rather than before it, and Mockito.when went unused in PurgedUserSnapshotTest once times and verify were added alongside it. Applied with spotless:apply rather than by hand, so the result matches what the check enforces. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
PurgedUserSnapshots.put replaced an id without dropping the superseded snapshot's email entry, so re-capturing the same user under a different -- or newly absent -- address left the old key pointing at a stale snapshot. Discard clears only the current snapshot's key, so nothing could ever reach the orphan. Keeping the two indexes in step is the reason this class exists, so put should not be a way for them to diverge. purgeRealm returned null when an admin event's realm id no longer resolved, instead of falling back to the context realm. Null guarantees the snapshot lookup misses, and a missed lookup silently skips the local-removal suppression -- the same failure mode the previous commit set out to close, left open one branch further down. Three tests pin the index invariant: a replace under a new address, a replace by a snapshot with no address at all, and an unrelated entry surviving both. Reported by Copilot in PR review. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
There was a problem hiding this comment.
🔵 Needs a closer look
Missing snapshots can bypass federated-account suppression and emit an incorrect purge event.
Review details
Suppressed comments (1)
ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/event/SecurityEventTokenMapper.java:445
- If snapshot capture fails, this null falls through, so the self-service
DELETE_ACCOUNTpath can still build aniss_subtoken and deliver it underdefault_subjects=ALL. That bypasseslocalRemovalOnlyand can emit a destructive purge for a READ_ONLY/UNSYNCED federated account that still exists; require a snapshot before generating the purge (and update the session-less mapper tests accordingly).
PurgedUserSnapshot snapshot = PurgedUserSnapshot.lookup(session, purgeRealm(adminEvent), userId);
if (snapshot != null && snapshot.isLocalRemovalOnly()) {
- Files reviewed: 16/16 changed files
- Comments generated: 0 new
- Review effort level: Balanced
The snapshot is the only evidence a deletion was a real purge, and the localRemovalOnly check silently did nothing when it was missing -- so a federated READ_ONLY / UNSYNCED account could be reported as purged while it still exists. Nothing downstream catches that. With no snapshot the user is unresolvable, the listener's subject gate skips a null user entirely rather than failing closed, and the dispatcher delivers an unresolvable subject under default_subjects=ALL on the benefit of the doubt. The admin path bails on a null user; the self-service DELETE_ACCOUNT path does not, which is where it leaks. Nor is the miss unlikely for the population at risk. Capture is best-effort and swallows its own failures, and for a federated user it reads attributes, groups, roles and memberships -- remote I/O against the very directory whose deletion semantics are in question. A capture failure is correlated with exactly the accounts that must be suppressed, not independent of them. So treat a missing snapshot the way an absent edit mode is already treated: unknown does not mean purged. Emitting nothing costs a receiver one signal; emitting wrongly costs it data it cannot recover. Capture failure now logs at WARN rather than DEBUG, and its comment no longer claims the only cost is an undelivered SET -- that stopped being true when the federated suppression landed, and the comment had been asserting the opposite of what the code does since. Reported by Copilot in PR review. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
There was a problem hiding this comment.
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Pull request overview
Copilot reviewed 16 out of 16 changed files in this pull request and generated 3 comments.
There was a problem hiding this comment.
Thanks @ssilvert for your work! Very cool feature.
The code looks good to me - as discussed I think we can optimize the Snapshot mechanism but it should be fine for now.
I just had one nitpick about the name of the "purgeRealm" method to resolve the realm from an AdminEvent. I'd suggest changing it but I leave that decision to you.
Once this is merged, we can apply the SSF event refactoring PR that I sent a while ago (needs a rebase then...).
| * The realm a purge snapshot was captured under: the admin event's realm when there | ||
| * is one, otherwise the context realm that the self-service path runs in. | ||
| */ | ||
| protected RealmModel purgeRealm(AdminEvent adminEvent) { |
There was a problem hiding this comment.
I'd change the method name to something like resolveRealm(AdminEvent adminEvent), at first glance purgeRealm sounds like a method to delete a realm :)
There was a problem hiding this comment.
Good point :) Renamed to resolveRealm in 51b3a12. Thanks for the review!
The method resolves which realm a purge snapshot was captured under. It does not purge a realm, but the old name read as though it did. Reported by thomasdarimont in PR review. Signed-off-by: Stan Silvert <ssilvert@redhat.com> Assisted-by: Claude Opus 5
There was a problem hiding this comment.
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Pull request overview
Copilot reviewed 16 out of 16 changed files in this pull request and generated 3 comments.
Adds the RISC
account-purgedevent, so SSF receivers learn when a Keycloak account is deleted and can run their own data-retention cleanup.Closes #48899
The problem
Keycloak deletes the user row before firing the admin or user event that drives SSF emission, so by the time the transmitter runs every lookup of that user returns
null. That affected the whole pipeline, not just the subject:SsfTransmitterEventListenerbefore building a token at all;emailand+tenantsubject formats had nothing to resolve and threw;default_subjects=NONE.That last one is the nastiest, because its failure mode is a silent drop rather than an error.
The approach
Capture a read-only snapshot of the user on
UserModel.UserPreRemovedEvent— the last hook that runs while the user still exists — and stash it on the session for the rest of the request. No new SPI was needed; that provider event already exists and is already published fromUserStorageManager.removeUser.The snapshot is a
UserModel(extendingAbstractInMemoryUserAdapter) rather than a bag of fields. Everything downstream that needs the user does attribute reads — the subject filter and inclusion resolver readssf.notify.<clientId>, and the mapper's email format readsgetEmail()— so copying the attribute map makes those call sites work unmodified.Organization membership is the one exception:
getByMemberis an id-keyed query, not an attribute read. The snapshot captures only the organization aliases; since organizations outlive the user, callers re-resolve liveOrganizationModels viagetByAliasand then run exactly the same logic as for a live user. That keeps the pluggableSsfSubjectInclusionResolverauthoritative for purged users too.The snapshot never has to outlive the request: narrowing, signing and encoding all happen inline on the request thread, and the outbox replays already-signed bytes. Capture is skipped entirely when a deletion is not bound to an HTTP request, since nothing could consume the snapshot, and retention within a request is bounded — together those stop bulk deletion paths accumulating snapshots that will never be read.
Deletions that are not purges
Emission stays on the admin/user event path rather than on the provider events, because those fire for deletions where the account does not cease to exist:
OVERWRITEpolicy deletes and immediately recreates the user — it reportsOperationType.UPDATEonusers/{id}, one enum value away from the purge gate;ResourceType.CLIENTatclients/{id}.Both are safe by construction rather than by an explicit guard, so both are pinned by tests to stop a future widening of the path matching from emitting spurious data-retention signals.
Known gap
account-purgedis emitted only for deletions through the admin API or the account console. The workflow delete step (DeleteUserStepProvider) fires no Keycloak events at all, so scheduled data-retention deletions are currently silent — arguably the case receivers would most expect to hear about. Deleting an organization that owns managed members is silent for the same reason, as it bypassesUserManager.Both are documented on
RiscAccountPurgedand in the guide, and are worth follow-up issues rather than growing this PR.Testing
SsfTransmitterAccountPurgedEventTests: both subject formats, bothdefault_subjectsmodes with a negative control, the org-notified and org-excluded legs, and both near-miss paths above.canConvertgates, the emitted token shape, and the wire format (including thataccount-purgedcarries noreasonclaim, which RISC does not define for it).DELETE_ACCOUNTpath is covered by unit tests and verified by hand; an end-to-end test would need a newDeleteAccountPagepage object, which felt disproportionate for asserting one field. Happy to add it if reviewers disagree.Notes for review
The second commit is a design correction from an internal review, not a fixup — it explains why organizations are re-resolved live rather than snapshotted, so it may be worth keeping separate. Squash if you prefer.
USER_DELETED_BY_ADMIN_PATH_PATTERNis deliberately a separate constant fromUSER_UPDATED_BY_ADMIN_PATH_PATTERNdespite being an identical regex — the two gates differ by operation type, and naming them separately keeps each readable on its own. Happy to collapse them into one shared constant if preferred.