From 0aaad87be07e45bf53bdf72f3a095597a6e36e17 Mon Sep 17 00:00:00 2001 From: Nuno Faria Date: Wed, 15 Jul 2026 12:14:36 +0100 Subject: [PATCH 1/2] Emit credential_id on UPDATE_CREDENTIAL events from built-in required actions UpdatePassword, UpdateTotp and WebAuthnRegister now set Details.CREDENTIAL_ID on the generic UPDATE_CREDENTIAL event, matching REMOVE_CREDENTIAL which already carries the credential id. This lets event consumers identify which credential row was created or updated when a user has multiple credentials of the same type. The OTP credential id is surfaced by hydrating it in OTPCredentialProvider.createCredential; the WebAuthn id is read from the createCredential return value. A password update, however, may be handled entirely by a federated CredentialInputUpdater (e.g. LDAP in WRITABLE edit mode), in which case nothing is written to the Keycloak credential store and there is no id to report. SubjectCredentialManager therefore gains updateCredentialAndGet, which returns the credential written to the Keycloak credential store, or an empty Optional when a user-storage provider handled the write. UpdatePassword emits the detail only when a credential comes back. CredentialInputUpdater gains a default updateCredentialAndGet returning a CredentialUpdate: whether the updater handled the input, and the credential it wrote to the Keycloak credential store, if any. The default delegates to updateCredential and reports no credential, so an updater writing to its own store, or one without data about what it wrote, leaves the event without an id. PasswordCredentialProvider overrides it and hands over the model produced by the write itself: nothing is read back afterwards, so no concurrent password write can make the event report another row, and the required action needs neither a pre-update snapshot nor a hash or timestamp comparison to find out whether the local row changed. UserCredentialManager asks each updater once and keeps the first outcome that was handled, so updateCredential keeps reporting what it reported before. SubjectCredentialManagerCacheAdapter invalidates the cached user for updateCredentialAndGet as it does for every other mutating method, so the write path does not read credentials through the user cache. RecoveryAuthnCodesAction emits the id as well. CredentialHelper.createRecoveryCodesCredential now returns the credential it created in the local storage, or null when the userStorage handled the write, so the action applies the same emit-only-when-locally-stored rule as the other required actions. The tests compare the emitted value with the credential id actually persisted for the user, rather than only asserting that some id is present. RequiredActionUpdatePasswordFederatedTest covers the federated branch: a user whose password is held by a user-storage provider, with a stale password row left in the Keycloak DB, must not get that untouched row's id on the event. WebAuthnRegisterAndLoginTest asserts that the deprecated cloned event still carries the details it had before, as the id is added to the generic event only after that clone is emitted. The release notes mention the new event detail. The migration guide needs no entry, as the touched SPI interfaces only gain default methods. Closes #50247 Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Signed-off-by: Nuno Faria --- .../release_notes/topics/26_8_0.adoc | 4 + .../SubjectCredentialManagerCacheAdapter.java | 8 + .../credential/UserCredentialManager.java | 23 ++- .../org/keycloak/utils/CredentialHelper.java | 8 +- .../credential/CredentialInputUpdater.java | 9 + .../keycloak/credential/CredentialUpdate.java | 13 ++ .../models/SubjectCredentialManager.java | 17 ++ .../RecoveryAuthnCodesAction.java | 6 +- .../requiredactions/UpdatePassword.java | 5 +- .../requiredactions/UpdateTotp.java | 3 + .../requiredactions/WebAuthnRegister.java | 7 +- .../credential/OTPCredentialProvider.java | 6 +- .../PasswordCredentialProvider.java | 16 +- ...iredActionUpdatePasswordFederatedTest.java | 188 ++++++++++++++++++ .../RecoveryAuthnCodesAuthenticatorTest.java | 6 + .../WebAuthnRegisterAndLoginTest.java | 15 +- .../AppInitiatedActionResetPasswordTest.java | 8 +- .../actions/RequiredActionTotpSetupTest.java | 10 +- .../webauthn/WebAuthnIdlessTest.java | 7 + 19 files changed, 340 insertions(+), 19 deletions(-) create mode 100644 server-spi/src/main/java/org/keycloak/credential/CredentialUpdate.java create mode 100644 tests/base/src/test/java/org/keycloak/tests/actions/RequiredActionUpdatePasswordFederatedTest.java diff --git a/docs/documentation/release_notes/topics/26_8_0.adoc b/docs/documentation/release_notes/topics/26_8_0.adoc index 6e83e13fe99..1192ae6458f 100644 --- a/docs/documentation/release_notes/topics/26_8_0.adoc +++ b/docs/documentation/release_notes/topics/26_8_0.adoc @@ -122,6 +122,10 @@ When the executor is attached to a client policy, node hostnames are validated a Administrators managing deployments that use the legacy adapter node registration feature should add the `secure-client-node-hostname` executor to a client policy and configure the allowed hostname patterns. Hostname patterns match against DNS hostnames and IPv4 addresses. Port suffixes are always rejected. Patterns are matched against the bare hostname or IP address. +== Credential ID in credential update events + +The `UPDATE_CREDENTIAL` events emitted by built-in required actions now carry the `credential_id` detail when a credential was created or updated in the {project_name} credential store, as the `REMOVE_CREDENTIAL` event already did. The detail is omitted when an external user-storage provider handles the update because there is no {project_name} credential ID to report. + = Administration == Declarative client management with Admin API v2 (preview) diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/SubjectCredentialManagerCacheAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/SubjectCredentialManagerCacheAdapter.java index ddb6fe68ec5..4f9d9c41dcb 100644 --- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/SubjectCredentialManagerCacheAdapter.java +++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/SubjectCredentialManagerCacheAdapter.java @@ -17,6 +17,8 @@ package org.keycloak.models.cache.infinispan; +import java.util.Optional; + import org.keycloak.credential.CredentialInput; import org.keycloak.credential.CredentialModel; import org.keycloak.credential.UserCredentialManager; @@ -41,6 +43,12 @@ public boolean updateCredential(CredentialInput input) { return super.updateCredential(input); } + @Override + public Optional updateCredentialAndGet(CredentialInput input) { + invalidateCacheForEntity(); + return super.updateCredentialAndGet(input); + } + @Override public void updateStoredCredential(CredentialModel cred) { invalidateCacheForEntity(); diff --git a/model/storage/src/main/java/org/keycloak/credential/UserCredentialManager.java b/model/storage/src/main/java/org/keycloak/credential/UserCredentialManager.java index 901ed1b0479..8855e933db6 100644 --- a/model/storage/src/main/java/org/keycloak/credential/UserCredentialManager.java +++ b/model/storage/src/main/java/org/keycloak/credential/UserCredentialManager.java @@ -20,6 +20,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Objects; +import java.util.Optional; import java.util.stream.Stream; import org.keycloak.common.util.reflections.Types; @@ -93,21 +94,37 @@ public boolean isValid(List inputs) { @Override public boolean updateCredential(CredentialInput input) { + return update(input).handled(); + } + + @Override + public Optional updateCredentialAndGet(CredentialInput input) { + return Optional.ofNullable(update(input).storedCredential()); + } + + /** + * Updates a credential of the user with the given input on the updater handling that credential type. + */ + private CredentialUpdate update(CredentialInput input) { if (!StorageId.isLocalStorage(user.getId())) throwExceptionIfInvalidUser(user); if (user.isFederated()) { UserStorageProviderModel model = getStorageProviderModel(realm, user.getFederationLink()); - if (model == null || !model.isEnabled()) return false; + if (model == null || !model.isEnabled()) return CredentialUpdate.NOT_HANDLED; CredentialInputUpdater updater = getStorageProviderInstance(model, CredentialInputUpdater.class); if (updater != null && updater.supportsCredentialType(input.getType())) { - if (updater.updateCredential(realm, user, input)) return true; + CredentialUpdate update = updater.updateCredentialAndGet(realm, user, input); + if (update.handled()) return update; } } return getCredentialProviders(session, CredentialInputUpdater.class) .filter(updater -> updater.supportsCredentialType(input.getType())) - .anyMatch(updater -> updater.updateCredential(realm, user, input)); + .map(updater -> updater.updateCredentialAndGet(realm, user, input)) + .filter(CredentialUpdate::handled) + .findFirst() + .orElse(CredentialUpdate.NOT_HANDLED); } @Override diff --git a/server-spi-private/src/main/java/org/keycloak/utils/CredentialHelper.java b/server-spi-private/src/main/java/org/keycloak/utils/CredentialHelper.java index 65fa48d44b0..dcb5bcdd558 100755 --- a/server-spi-private/src/main/java/org/keycloak/utils/CredentialHelper.java +++ b/server-spi-private/src/main/java/org/keycloak/utils/CredentialHelper.java @@ -112,8 +112,11 @@ public static boolean createOTPCredential(KeycloakSession session, RealmModel re /** * Create RecoveryCodes credential either in userStorage or local storage (Keycloak DB) + * + * @return the credential created in the local storage, or {@code null} when it was created in the userStorage + * and hence there is no Keycloak credential ID available */ - public static void createRecoveryCodesCredential(KeycloakSession session, RealmModel realm, UserModel user, RecoveryAuthnCodesCredentialModel credentialModel, List generatedCodes) { + public static CredentialModel createRecoveryCodesCredential(KeycloakSession session, RealmModel realm, UserModel user, RecoveryAuthnCodesCredentialModel credentialModel, List generatedCodes) { var recoveryCodeCredentialProvider = session.getProvider(CredentialProvider.class, "keycloak-recovery-authn-codes"); String recoveryCodesJson; try { @@ -126,8 +129,9 @@ public static void createRecoveryCodesCredential(KeycloakSession session, RealmM boolean userStorageCreated = user.credentialManager().updateCredential(recoveryCodesCredential); if (userStorageCreated) { logger.debugf("Created RecoveryCodes credential for user '%s' in the user storage", user.getUsername()); + return null; } else { - recoveryCodeCredentialProvider.createCredential(realm, user, credentialModel); + return recoveryCodeCredentialProvider.createCredential(realm, user, credentialModel); } } diff --git a/server-spi/src/main/java/org/keycloak/credential/CredentialInputUpdater.java b/server-spi/src/main/java/org/keycloak/credential/CredentialInputUpdater.java index e86f23d3e56..fce656d2070 100644 --- a/server-spi/src/main/java/org/keycloak/credential/CredentialInputUpdater.java +++ b/server-spi/src/main/java/org/keycloak/credential/CredentialInputUpdater.java @@ -50,4 +50,13 @@ public interface CredentialInputUpdater { default Stream getCredentials(RealmModel realm, UserModel user) { return Stream.empty(); } + + /** + * Updates a credential of the user with the given input, reporting the credential written to the Keycloak + * credential store. The default implementation delegates to + * {@link #updateCredential(RealmModel, UserModel, CredentialInput)} and reports no credential. + */ + default CredentialUpdate updateCredentialAndGet(RealmModel realm, UserModel user, CredentialInput input) { + return new CredentialUpdate(updateCredential(realm, user, input), null); + } } diff --git a/server-spi/src/main/java/org/keycloak/credential/CredentialUpdate.java b/server-spi/src/main/java/org/keycloak/credential/CredentialUpdate.java new file mode 100644 index 00000000000..2fd510d4ea5 --- /dev/null +++ b/server-spi/src/main/java/org/keycloak/credential/CredentialUpdate.java @@ -0,0 +1,13 @@ +package org.keycloak.credential; + +/** + * The outcome of a credential update performed by a {@link CredentialInputUpdater}. + * + * @param handled whether the updater handled the input + * @param storedCredential the credential written to the Keycloak credential store, or {@code null} if the updater + * wrote it elsewhere or has no data about it + */ +public record CredentialUpdate(boolean handled, CredentialModel storedCredential) { + + public static final CredentialUpdate NOT_HANDLED = new CredentialUpdate(false, null); +} diff --git a/server-spi/src/main/java/org/keycloak/models/SubjectCredentialManager.java b/server-spi/src/main/java/org/keycloak/models/SubjectCredentialManager.java index eb29149aa7c..2f673d44e99 100644 --- a/server-spi/src/main/java/org/keycloak/models/SubjectCredentialManager.java +++ b/server-spi/src/main/java/org/keycloak/models/SubjectCredentialManager.java @@ -19,6 +19,7 @@ import java.util.Arrays; import java.util.List; +import java.util.Optional; import java.util.stream.Stream; import org.keycloak.credential.CredentialInput; @@ -54,6 +55,22 @@ default boolean isValid(CredentialInput... inputs) { */ boolean updateCredential(CredentialInput input); + /** + * Updates a credential of the entity with the inputs provided by the entity, and returns the credential as + * written to the Keycloak credential store. + *

+ * The default implementation performs the update and reports no stored credential. Implementations writing + * credentials to the Keycloak credential store are expected to override it; leaving the default in place only + * means callers cannot identify the credential that was written. + * + * @return the credential written to the Keycloak credential store, or an empty {@link Optional} when nothing + * has been written there, for example because a user-storage provider handled the update + */ + default Optional updateCredentialAndGet(CredentialInput input) { + updateCredential(input); + return Optional.empty(); + } + /** * Updates a credential of the entity with an updated {@link CredentialModel}. * Usually called by a {@link org.keycloak.credential.CredentialProvider}. diff --git a/services/src/main/java/org/keycloak/authentication/requiredactions/RecoveryAuthnCodesAction.java b/services/src/main/java/org/keycloak/authentication/requiredactions/RecoveryAuthnCodesAction.java index 36b5fc0f04a..a43482675c8 100644 --- a/services/src/main/java/org/keycloak/authentication/requiredactions/RecoveryAuthnCodesAction.java +++ b/services/src/main/java/org/keycloak/authentication/requiredactions/RecoveryAuthnCodesAction.java @@ -16,6 +16,7 @@ import org.keycloak.authentication.RequiredActionProvider; import org.keycloak.authentication.authenticators.browser.RecoveryAuthnCodesFormAuthenticator; import org.keycloak.common.Profile; +import org.keycloak.credential.CredentialModel; import org.keycloak.events.Details; import org.keycloak.events.EventBuilder; import org.keycloak.events.EventType; @@ -135,7 +136,10 @@ public void processAction(RequiredActionContext reqActionContext) { AuthenticatorUtil.logoutOtherSessions(reqActionContext); } - createRecoveryCodesCredential(reqActionContext.getSession(), reqActionContext.getRealm(), reqActionContext.getUser(), credentialModel, generatedCodes); + CredentialModel createdCredential = createRecoveryCodesCredential(reqActionContext.getSession(), reqActionContext.getRealm(), reqActionContext.getUser(), credentialModel, generatedCodes); + if (createdCredential != null) { + event.detail(Details.CREDENTIAL_ID, createdCredential.getId()); + } reqActionContext.success(); } diff --git a/services/src/main/java/org/keycloak/authentication/requiredactions/UpdatePassword.java b/services/src/main/java/org/keycloak/authentication/requiredactions/UpdatePassword.java index 69bd5099d55..01e5333aaf3 100755 --- a/services/src/main/java/org/keycloak/authentication/requiredactions/UpdatePassword.java +++ b/services/src/main/java/org/keycloak/authentication/requiredactions/UpdatePassword.java @@ -145,7 +145,10 @@ public void processAction(RequiredActionContext context) { } try { - user.credentialManager().updateCredential(UserCredentialModel.password(passwordNew, false)); + user.credentialManager() + .updateCredentialAndGet(UserCredentialModel.password(passwordNew, false)) + .ifPresent(credential -> event.detail(Details.CREDENTIAL_ID, credential.getId())); + context.success(); deprecatedEvent.success(); } catch (ModelException me) { diff --git a/services/src/main/java/org/keycloak/authentication/requiredactions/UpdateTotp.java b/services/src/main/java/org/keycloak/authentication/requiredactions/UpdateTotp.java index 727c467f809..7f27b4d3358 100644 --- a/services/src/main/java/org/keycloak/authentication/requiredactions/UpdateTotp.java +++ b/services/src/main/java/org/keycloak/authentication/requiredactions/UpdateTotp.java @@ -191,6 +191,9 @@ public void processAction(RequiredActionContext context) { } context.getAuthenticationSession().removeAuthNote(Constants.TOTP_SECRET_KEY); + if (credentialModel.getId() != null) { + event.detail(Details.CREDENTIAL_ID, credentialModel.getId()); + } context.success(); deprecatedEvent.success(); } diff --git a/services/src/main/java/org/keycloak/authentication/requiredactions/WebAuthnRegister.java b/services/src/main/java/org/keycloak/authentication/requiredactions/WebAuthnRegister.java index fdf615d3447..148cf1c27a8 100644 --- a/services/src/main/java/org/keycloak/authentication/requiredactions/WebAuthnRegister.java +++ b/services/src/main/java/org/keycloak/authentication/requiredactions/WebAuthnRegister.java @@ -41,6 +41,7 @@ import org.keycloak.common.util.Base64Url; import org.keycloak.common.util.CollectionUtil; import org.keycloak.common.util.UriUtils; +import org.keycloak.credential.CredentialModel; import org.keycloak.credential.CredentialProvider; import org.keycloak.credential.WebAuthnCredentialModelInput; import org.keycloak.credential.WebAuthnCredentialProvider; @@ -337,7 +338,7 @@ public void processAction(RequiredActionContext context) { WebAuthnCredentialProvider webAuthnCredProvider = (WebAuthnCredentialProvider) this.session.getProvider(CredentialProvider.class, getCredentialProviderId()); WebAuthnCredentialModel newCredentialModel = webAuthnCredProvider.getCredentialModelFromCredentialInput(credential, label); - webAuthnCredProvider.createCredential(context.getRealm(), context.getUser(), newCredentialModel); + CredentialModel createdCredential = webAuthnCredProvider.createCredential(context.getRealm(), context.getUser(), newCredentialModel); String aaguid = newCredentialModel.getWebAuthnCredentialData().getAaguid(); logger.debugv("WebAuthn credential registration success for user {0}. credentialType = {1}, publicKeyCredentialId = {2}, publicKeyCredentialLabel = {3}, publicKeyCredentialAAGUID = {4}", @@ -349,6 +350,10 @@ public void processAction(RequiredActionContext context) { .detail(WebAuthnConstants.PUBKEY_CRED_LABEL_ATTR, label) .detail(WebAuthnConstants.PUBKEY_CRED_AAGUID_ATTR, aaguid); context.getEvent().clone().event(originalEventType).success(); + // the deprecated event is emitted first, so that it keeps carrying the same details as before + if (createdCredential != null) { + context.getEvent().detail(Details.CREDENTIAL_ID, createdCredential.getId()); + } context.success(); } catch (WebAuthnPolicyException wpe) { logger.debug("WebAuthn policy violation during registration.", wpe); diff --git a/services/src/main/java/org/keycloak/credential/OTPCredentialProvider.java b/services/src/main/java/org/keycloak/credential/OTPCredentialProvider.java index bef8ed2203b..7e80aaea4e6 100644 --- a/services/src/main/java/org/keycloak/credential/OTPCredentialProvider.java +++ b/services/src/main/java/org/keycloak/credential/OTPCredentialProvider.java @@ -51,7 +51,11 @@ public CredentialModel createCredential(RealmModel realm, UserModel user, OTPCre if (credentialModel.getCreatedDate() == null) { credentialModel.setCreatedDate(Time.currentTimeMillis()); } - return user.credentialManager().createStoredCredential(credentialModel); + CredentialModel createdCredential = user.credentialManager().createStoredCredential(credentialModel); + if (createdCredential != null) { + credentialModel.setId(createdCredential.getId()); + } + return createdCredential; } @Override diff --git a/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java b/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java index 161ac1afa34..0a22865dd9c 100644 --- a/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java +++ b/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java @@ -84,7 +84,7 @@ public PasswordCredentialModel getPassword(RealmModel realm, UserModel user) { return PasswordCredentialModel.createFromCredentialModel(passwords.get(0)); } - public boolean createCredential(RealmModel realm, UserModel user, String password) { + public CredentialModel createCredential(RealmModel realm, UserModel user, String password) { PasswordPolicy policy = realm.getPasswordPolicy(); PolicyError error = session.getProvider(PasswordPolicyManagerProvider.class).validate(realm, user, password); @@ -92,16 +92,15 @@ public boolean createCredential(RealmModel realm, UserModel user, String passwor PasswordHashProvider hash = getHashProvider(policy); if (hash == null) { - return false; + return null; } try { PasswordCredentialModel credentialModel = hash.encodedCredential(password, policy.getHashIterations()); credentialModel.setCreatedDate(Time.currentTimeMillis()); - createCredential(realm, user, credentialModel); + return createCredential(realm, user, credentialModel); } catch (Throwable t) { throw new ModelException(t.getMessage(), t); } - return true; } @Override @@ -187,7 +186,14 @@ public boolean supportsCredentialType(String credentialType) { @Override public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { - return createCredential(realm, user, input.getChallengeResponse()); + return updateCredentialAndGet(realm, user, input).handled(); + } + + @Override + public CredentialUpdate updateCredentialAndGet(RealmModel realm, UserModel user, CredentialInput input) { + CredentialModel credential = createCredential(realm, user, input.getChallengeResponse()); + + return new CredentialUpdate(credential != null, credential); } @Override diff --git a/tests/base/src/test/java/org/keycloak/tests/actions/RequiredActionUpdatePasswordFederatedTest.java b/tests/base/src/test/java/org/keycloak/tests/actions/RequiredActionUpdatePasswordFederatedTest.java new file mode 100644 index 00000000000..972a790d3ec --- /dev/null +++ b/tests/base/src/test/java/org/keycloak/tests/actions/RequiredActionUpdatePasswordFederatedTest.java @@ -0,0 +1,188 @@ +package org.keycloak.tests.actions; + +import java.util.List; + +import org.keycloak.admin.client.resource.UserResource; +import org.keycloak.common.util.MultivaluedHashMap; +import org.keycloak.credential.CredentialModel; +import org.keycloak.credential.CredentialProvider; +import org.keycloak.credential.PasswordCredentialProvider; +import org.keycloak.credential.PasswordCredentialProviderFactory; +import org.keycloak.events.Details; +import org.keycloak.events.EventType; +import org.keycloak.models.LDAPConstants; +import org.keycloak.models.RealmModel; +import org.keycloak.models.UserModel; +import org.keycloak.models.credential.PasswordCredentialModel; +import org.keycloak.representations.idm.ComponentRepresentation; +import org.keycloak.representations.idm.CredentialRepresentation; +import org.keycloak.representations.idm.UserRepresentation; +import org.keycloak.storage.UserStorageProvider; +import org.keycloak.testframework.annotations.InjectEvents; +import org.keycloak.testframework.annotations.InjectRealm; +import org.keycloak.testframework.annotations.KeycloakIntegrationTest; +import org.keycloak.testframework.events.EventAssertion; +import org.keycloak.testframework.events.Events; +import org.keycloak.testframework.oauth.OAuthClient; +import org.keycloak.testframework.oauth.annotations.InjectOAuthClient; +import org.keycloak.testframework.realm.ManagedRealm; +import org.keycloak.testframework.remote.providers.runonserver.FetchOnServer; +import org.keycloak.testframework.remote.providers.runonserver.RunOnServer; +import org.keycloak.testframework.remote.runonserver.InjectRunOnServer; +import org.keycloak.testframework.remote.runonserver.RunOnServerClient; +import org.keycloak.testframework.ui.annotations.InjectPage; +import org.keycloak.testframework.ui.page.LoginPage; +import org.keycloak.testframework.ui.page.LoginPasswordUpdatePage; +import org.keycloak.testframework.util.ApiUtil; +import org.keycloak.tests.common.CustomProvidersServerConfig; +import org.keycloak.tests.providers.federation.UserMapStorageFactory; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@KeycloakIntegrationTest(config = CustomProvidersServerConfig.class) +public class RequiredActionUpdatePasswordFederatedTest { + + private static final String USERNAME = "federated-update-password"; + private static final String FEDERATED_PASSWORD = "Federated-password1"; + private static final String LOCAL_PASSWORD = "Local-password1"; + private static final String UPDATED_PASSWORD = "Federated-password2"; + + @InjectRealm + ManagedRealm managedRealm; + + @InjectOAuthClient + OAuthClient oauth; + + @InjectEvents + Events events; + + @InjectRunOnServer(permittedPackages = "org.keycloak.tests") + RunOnServerClient runOnServer; + + @InjectPage + LoginPage loginPage; + + @InjectPage + LoginPasswordUpdatePage updatePasswordPage; + + // The user storage provider handles the password update, so the password stored in the Keycloak DB is left + // untouched and its ID must not be reported on the UPDATE_CREDENTIAL event + @Test + public void updatePasswordHandledByUserStorageDoesNotReportCredentialId() { + addUserStorageProvider(); + + UserResource user = addFederatedUser(); + String userId = user.toRepresentation().getId(); + + // updateCredential is always answered by the provider, so the password of the user is stored there only + resetPassword(user, FEDERATED_PASSWORD); + Assertions.assertTrue(user.credentials().isEmpty(), "Password should not be stored in the Keycloak DB"); + + // Store a password in the Keycloak DB too. It has to be written directly, as going through the credential + // manager would hand the write to the provider again + storeLocalPassword(); + String localPassword = localPasswordFingerprint(); + + UserRepresentation userRep = user.toRepresentation(); + userRep.setRequiredActions(List.of(UserModel.RequiredAction.UPDATE_PASSWORD.name())); + user.update(userRep); + + events.clear(); + + oauth.openLoginForm(); + // The provider validates passwords itself and is asked before the local store, so the federated password is + // the one the user authenticates with + loginPage.fillLogin(USERNAME, FEDERATED_PASSWORD); + loginPage.submit(); + + updatePasswordPage.assertCurrent(); + updatePasswordPage.changePassword(UPDATED_PASSWORD, UPDATED_PASSWORD); + + Assertions.assertTrue(oauth.parseLoginResponse().isSuccess()); + EventAssertion.assertSuccess(events.poll()).type(EventType.UPDATE_PASSWORD) + .details(Details.CREDENTIAL_TYPE, PasswordCredentialModel.TYPE).userId(userId); + EventAssertion.assertSuccess(events.poll()).type(EventType.UPDATE_CREDENTIAL) + .details(Details.CREDENTIAL_TYPE, PasswordCredentialModel.TYPE).userId(userId) + .withoutDetails(Details.CREDENTIAL_ID); + + // Assert the locally stored password is still the very same one as before the update + assertEquals(localPassword, localPasswordFingerprint()); + } + + private void addUserStorageProvider() { + ComponentRepresentation provider = new ComponentRepresentation(); + provider.setName("memory"); + provider.setProviderId(UserMapStorageFactory.PROVIDER_ID); + provider.setProviderType(UserStorageProvider.class.getName()); + provider.setConfig(new MultivaluedHashMap<>()); + provider.getConfig().putSingle("priority", "0"); + provider.getConfig().putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.WRITABLE.name()); + + String providerId = ApiUtil.getCreatedId(managedRealm.admin().components().add(provider)); + managedRealm.cleanup().add(realm -> realm.components().component(providerId).remove()); + } + + private UserResource addFederatedUser() { + UserRepresentation userRep = new UserRepresentation(); + userRep.setUsername(USERNAME); + userRep.setEmail(USERNAME + "@email.cz"); + userRep.setFirstName("firstName"); + userRep.setLastName("lastName"); + userRep.setEnabled(true); + + // No cleanup for the user, it is removed along with the provider it is federated from + String userId = ApiUtil.getCreatedId(managedRealm.admin().users().create(userRep)); + + UserResource user = managedRealm.admin().users().get(userId); + Assertions.assertNotNull(user.toRepresentation().getFederationLink(), "User should be federated"); + return user; + } + + private void resetPassword(UserResource user, String password) { + CredentialRepresentation credential = new CredentialRepresentation(); + credential.setType(CredentialRepresentation.PASSWORD); + credential.setValue(password); + credential.setTemporary(false); + user.resetPassword(credential); + } + + private void storeLocalPassword() { + runOnServer.run(ServerCode.storeLocalPassword()); + } + + // The ID, the creation date and the secret of the locally stored password, used to assert the local row was + // left untouched by the update + private String localPasswordFingerprint() { + return runOnServer.fetchString(ServerCode.localPasswordFingerprint()); + } + + // The class capturing a lambda is loaded on the server to run it, so the code running there is kept out of the + // test class, which references admin client classes that are not available on the server + public static class ServerCode { + + public static RunOnServer storeLocalPassword() { + return session -> { + RealmModel realm = session.getContext().getRealm(); + UserModel user = session.users().getUserByUsername(realm, USERNAME); + PasswordCredentialProvider passwordProvider = (PasswordCredentialProvider) session + .getProvider(CredentialProvider.class, PasswordCredentialProviderFactory.PROVIDER_ID); + passwordProvider.createCredential(realm, user, LOCAL_PASSWORD); + }; + } + + public static FetchOnServer localPasswordFingerprint() { + return session -> { + RealmModel realm = session.getContext().getRealm(); + UserModel user = session.users().getUserByUsername(realm, USERNAME); + CredentialModel password = user.credentialManager() + .getStoredCredentialsByTypeStream(PasswordCredentialModel.TYPE) + .findFirst() + .orElseThrow(() -> new AssertionError("Password credential is not stored in the Keycloak DB")); + return password.getId() + "|" + password.getCreatedDate() + "|" + password.getSecretData(); + }; + } + } +} diff --git a/tests/base/src/test/java/org/keycloak/tests/forms/RecoveryAuthnCodesAuthenticatorTest.java b/tests/base/src/test/java/org/keycloak/tests/forms/RecoveryAuthnCodesAuthenticatorTest.java index fb9ae20a898..7bf43a94094 100644 --- a/tests/base/src/test/java/org/keycloak/tests/forms/RecoveryAuthnCodesAuthenticatorTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/forms/RecoveryAuthnCodesAuthenticatorTest.java @@ -172,6 +172,12 @@ private void testSetupRecoveryAuthnCodesLogoutOtherSessions(boolean logoutOtherS .userId(event1.getUserId()) .details(Details.USERNAME, testUser.getUsername()) .details(Details.CREDENTIAL_TYPE, RecoveryAuthnCodesCredentialModel.TYPE).getEvent(); + String storedCredentialId = testUser.admin().credentials().stream() + .filter(credential -> RecoveryAuthnCodesCredentialModel.TYPE.equals(credential.getType())) + .findFirst() + .orElseThrow() + .getId(); + assertEquals(storedCredentialId, event2.getDetails().get(Details.CREDENTIAL_ID)); event2 = EventAssertion.expectLoginSuccess(events.poll()).sessionId(event2.getDetails().get(Details.CODE_ID)).userId(event2.getUserId()) .details(Details.USERNAME, testUser.getUsername()).getEvent(); diff --git a/tests/webauthn/src/test/java/org/keycloak/tests/webauthn/WebAuthnRegisterAndLoginTest.java b/tests/webauthn/src/test/java/org/keycloak/tests/webauthn/WebAuthnRegisterAndLoginTest.java index 8a2a06253e1..49635d1a8f2 100644 --- a/tests/webauthn/src/test/java/org/keycloak/tests/webauthn/WebAuthnRegisterAndLoginTest.java +++ b/tests/webauthn/src/test/java/org/keycloak/tests/webauthn/WebAuthnRegisterAndLoginTest.java @@ -119,7 +119,9 @@ public void registerUserSuccess() { .details(Details.REDIRECT_URI, testApp.getRedirectionUri()) .details(Details.CUSTOM_REQUIRED_ACTION, WebAuthnRegisterFactory.PROVIDER_ID) .details(WebAuthnConstants.PUBKEY_CRED_LABEL_ATTR, authenticatorLabel) - .details(WebAuthnConstants.PUBKEY_CRED_AAGUID_ATTR, ALL_ZERO_AAGUID); + .details(WebAuthnConstants.PUBKEY_CRED_AAGUID_ATTR, ALL_ZERO_AAGUID) + // the credential ID is reported on UPDATE_CREDENTIAL only, the deprecated event keeps the details it carried before + .withoutDetails(Details.CREDENTIAL_ID); String regPubKeyCredentialId1 = event.getDetails().get(WebAuthnConstants.PUBKEY_CRED_ID_ATTR); @@ -129,7 +131,8 @@ public void registerUserSuccess() { .details(Details.REDIRECT_URI, testApp.getRedirectionUri()) .details(Details.CUSTOM_REQUIRED_ACTION, WebAuthnRegisterFactory.PROVIDER_ID) .details(WebAuthnConstants.PUBKEY_CRED_LABEL_ATTR, authenticatorLabel) - .details(WebAuthnConstants.PUBKEY_CRED_AAGUID_ATTR, ALL_ZERO_AAGUID); + .details(WebAuthnConstants.PUBKEY_CRED_AAGUID_ATTR, ALL_ZERO_AAGUID) + .details(Details.CREDENTIAL_ID, storedCredentialId(userId, WebAuthnCredentialModel.TYPE_TWOFACTOR)); String regPubKeyCredentialId2 = event2.getDetails().get(WebAuthnConstants.PUBKEY_CRED_ID_ATTR); @@ -472,6 +475,14 @@ private List getCredentials(String userId) { return managedRealm.admin().users().get(userId).credentials(); } + private String storedCredentialId(String userId, String credentialType) { + return getCredentials(userId).stream() + .filter(credential -> credentialType.equals(credential.getType())) + .map(CredentialRepresentation::getId) + .findFirst() + .orElseThrow(); + } + private void updateRealmWithDefaultWebAuthnSettings() { managedRealm.updateWithCleanup(r -> r.webAuthn(false, builder -> builder.signatureAlgorithms(List.of("ES256")) diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionResetPasswordTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionResetPasswordTest.java index 170f7a4e206..bd639ffe534 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionResetPasswordTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/AppInitiatedActionResetPasswordTest.java @@ -183,7 +183,13 @@ public void resetPassword() throws Exception { }); EventAssertion.expectRequiredAction(events.poll()).type(EventType.UPDATE_PASSWORD); - EventAssertion.expectRequiredAction(events.poll()).type(EventType.UPDATE_CREDENTIAL).details(Details.CREDENTIAL_TYPE, PasswordCredentialModel.TYPE); + EventRepresentation updateCredentialEvent = EventAssertion.expectRequiredAction(events.poll()).type(EventType.UPDATE_CREDENTIAL).details(Details.CREDENTIAL_TYPE, PasswordCredentialModel.TYPE).getEvent(); + String storedCredentialId = AdminApiUtil.findUserByUsernameId(managedRealm.admin(), "test-user@localhost").credentials().stream() + .filter(credential -> PasswordCredentialModel.TYPE.equals(credential.getType())) + .findFirst() + .orElseThrow() + .getId(); + assertEquals(storedCredentialId, updateCredentialEvent.getDetails().get(Details.CREDENTIAL_ID)); MimeMessage[] receivedMessages = mail.getReceivedMessages(); Assertions.assertEquals(2, receivedMessages.length); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionTotpSetupTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionTotpSetupTest.java index 4081379187a..70f3b8feb73 100755 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionTotpSetupTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/actions/RequiredActionTotpSetupTest.java @@ -199,10 +199,16 @@ public void setupTotpRegister() { Assertions.assertTrue(oauth.parseLoginResponse().isSuccess()); - EventAssertion.expectRequiredAction(events.poll()).type(EventType.UPDATE_CREDENTIAL) + EventRepresentation updateCredentialEvent = EventAssertion.expectRequiredAction(events.poll()).type(EventType.UPDATE_CREDENTIAL) .userId(userId) .details(Details.CREDENTIAL_TYPE, OTPCredentialModel.TYPE) - .details(Details.USERNAME, "setuptotp"); + .details(Details.USERNAME, "setuptotp").getEvent(); + String storedCredentialId = managedRealm.admin().users().get(userId).credentials().stream() + .filter(credential -> OTPCredentialModel.TYPE.equals(credential.getType())) + .findFirst() + .orElseThrow() + .getId(); + assertEquals(storedCredentialId, updateCredentialEvent.getDetails().get(Details.CREDENTIAL_ID)); Assertions.assertTrue(oauth.parseLoginResponse().isSuccess()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/WebAuthnIdlessTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/WebAuthnIdlessTest.java index 1f662bc410c..4d193cb848c 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/WebAuthnIdlessTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/WebAuthnIdlessTest.java @@ -239,6 +239,13 @@ protected String usernamePasswordAuthWithAuthSetup(String username, boolean isPa .filter(cred -> cred.getType().equals(credType)) .filter(cred -> cred.getUserLabel().equals(authenticatorLabel)) .collect(Collectors.toList()).size(), is(1)); + + String storedCredentialId = userRes.credentials().stream() + .filter(cred -> cred.getType().equals(credType)) + .filter(cred -> cred.getUserLabel().equals(authenticatorLabel)) + .map(CredentialRepresentation::getId) + .findFirst().orElseThrow(); + assertThat(eventRep2.getDetails().get(Details.CREDENTIAL_ID), equalTo(storedCredentialId)); assertThat(getVirtualAuthManager().getCurrent().getAuthenticator().getCredentials().stream() .filter(cred -> cred.isResidentCredential() == withResidentKey) .collect(Collectors.toList()).size(), is(1)); From 89c0b73a50333520a2d1a6591d3084d54c1b9601 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Barto=C5=A1?= Date: Tue, 6 Oct 2026 10:25:19 +0200 Subject: [PATCH 2/2] Fix release notes, avoid executing other updater MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Martin Bartoš --- docs/documentation/release_notes/index.adoc | 3 +++ docs/documentation/release_notes/topics/26_8_0.adoc | 5 ----- docs/documentation/release_notes/topics/27_0_0.adoc | 5 +++++ .../credential/PasswordCredentialProvider.java | 13 ++++++++----- 4 files changed, 16 insertions(+), 10 deletions(-) create mode 100644 docs/documentation/release_notes/topics/27_0_0.adoc diff --git a/docs/documentation/release_notes/index.adoc b/docs/documentation/release_notes/index.adoc index c967141475d..d89085260a0 100644 --- a/docs/documentation/release_notes/index.adoc +++ b/docs/documentation/release_notes/index.adoc @@ -13,6 +13,9 @@ include::topics/templates/document-attributes.adoc[] :release_header_latest_link: {releasenotes_link_latest} include::topics/templates/release-header.adoc[] +== {project_name_full} 27.0.0 +include::topics/27_0_0.adoc[leveloffset=2] + == {project_name_full} 26.8.0 include::topics/26_8_0.adoc[leveloffset=2] diff --git a/docs/documentation/release_notes/topics/26_8_0.adoc b/docs/documentation/release_notes/topics/26_8_0.adoc index 1192ae6458f..e263f4fb4c6 100644 --- a/docs/documentation/release_notes/topics/26_8_0.adoc +++ b/docs/documentation/release_notes/topics/26_8_0.adoc @@ -122,10 +122,6 @@ When the executor is attached to a client policy, node hostnames are validated a Administrators managing deployments that use the legacy adapter node registration feature should add the `secure-client-node-hostname` executor to a client policy and configure the allowed hostname patterns. Hostname patterns match against DNS hostnames and IPv4 addresses. Port suffixes are always rejected. Patterns are matched against the bare hostname or IP address. -== Credential ID in credential update events - -The `UPDATE_CREDENTIAL` events emitted by built-in required actions now carry the `credential_id` detail when a credential was created or updated in the {project_name} credential store, as the `REMOVE_CREDENTIAL` event already did. The detail is omitted when an external user-storage provider handles the update because there is no {project_name} credential ID to report. - = Administration == Declarative client management with Admin API v2 (preview) @@ -281,4 +277,3 @@ For setup instructions and common configuration patterns, see link:{adminguide_l The social identity provider section on the login page has been refreshed with updated icons, a new divider layout, and improved button labels. If you have a custom login theme, see the link:{upgradingguide_link}[{upgradingguide_name}] for details on what changed. - diff --git a/docs/documentation/release_notes/topics/27_0_0.adoc b/docs/documentation/release_notes/topics/27_0_0.adoc new file mode 100644 index 00000000000..17e94f3f9ef --- /dev/null +++ b/docs/documentation/release_notes/topics/27_0_0.adoc @@ -0,0 +1,5 @@ += Security and Standards + +== Credential ID in credential update events + +The `UPDATE_CREDENTIAL` events emitted by built-in required actions now carry the `credential_id` detail when a credential was created or updated in the {project_name} credential store, as the `REMOVE_CREDENTIAL` event already did. The detail is omitted when an external user-storage provider handles the update because there is no {project_name} credential ID to report. diff --git a/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java b/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java index 0a22865dd9c..21b7d916813 100644 --- a/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java +++ b/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java @@ -85,6 +85,10 @@ public PasswordCredentialModel getPassword(RealmModel realm, UserModel user) { } public CredentialModel createCredential(RealmModel realm, UserModel user, String password) { + return createCredentialAndGet(realm, user, password).storedCredential(); + } + + private CredentialUpdate createCredentialAndGet(RealmModel realm, UserModel user, String password) { PasswordPolicy policy = realm.getPasswordPolicy(); PolicyError error = session.getProvider(PasswordPolicyManagerProvider.class).validate(realm, user, password); @@ -92,12 +96,13 @@ public CredentialModel createCredential(RealmModel realm, UserModel user, String PasswordHashProvider hash = getHashProvider(policy); if (hash == null) { - return null; + return CredentialUpdate.NOT_HANDLED; } try { PasswordCredentialModel credentialModel = hash.encodedCredential(password, policy.getHashIterations()); credentialModel.setCreatedDate(Time.currentTimeMillis()); - return createCredential(realm, user, credentialModel); + CredentialModel storedCredential = createCredential(realm, user, credentialModel); + return new CredentialUpdate(true, storedCredential); } catch (Throwable t) { throw new ModelException(t.getMessage(), t); } @@ -191,9 +196,7 @@ public boolean updateCredential(RealmModel realm, UserModel user, CredentialInpu @Override public CredentialUpdate updateCredentialAndGet(RealmModel realm, UserModel user, CredentialInput input) { - CredentialModel credential = createCredential(realm, user, input.getChallengeResponse()); - - return new CredentialUpdate(credential != null, credential); + return createCredentialAndGet(realm, user, input.getChallengeResponse()); } @Override