8000 Allow local attribute updates for read-only LDAP users by Oluwatobi-Mustapha · Pull Request #54840 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
8000
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ Operations that fetch a single user (for example during login) are usually cache
Users and admins can modify user metadata, users through the <<account-service, Account Console>>, and administrators through the Admin Console. The `Edit Mode` configuration on the LDAP configuration page defines the user's LDAP update privileges.

READ_ONLY::
You cannot change the username, email, first name, last name, and other mapped attributes. {project_name} shows an error anytime a user attempts to update these fields. Password updates are not supported.
You cannot change the username, LDAP metadata, or attributes mapped from LDAP, such as email, first name, and last name. Password updates are not supported.
When *Import Users* is enabled, you can add, update, and remove local profile attributes that neither the LDAP provider nor its mappers manage, subject to <<user-profile,User Profile>> permissions and validation.

WRITABLE::
You can change the username, email, first name, last name, and other mapped attributes and passwords and synchronize them automatically with the LDAP store.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,13 @@ Explicit `false` values for `wantAssertionsSigned` and `validateSignature` remai

Disabling signature validation reduces protection against forged identity-provider responses.

=== Attribute ownership in custom LDAP mappers

When *Import Users* is enabled for a read-only LDAP provider, User Profile permissions apply to attributes stored only in {project_name}.
Previously, the read-only provider blocked most attribute writes even if no mapper declared the attribute.
If you maintain a custom LDAP mapper, return every attribute it manages from `getUserAttributes()` to keep those attributes read-only. The base implementation returns an empty set.
Override `managesUserAttribute(String)` if the mapper recognizes names beyond exact matches, and use `getSearchableUserAttributes()` to exclude attributes that cannot be searched in LDAP.

// ------------------------ Notable changes ------------------------ //
== Notable changes

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,8 @@ protected UserModel proxy(RealmModel realm, UserModel local, LDAPObject ldapObje
switch (editMode) {
case READ_ONLY:
if (model.isImportEnabled()) {
proxied = new ReadonlyLDAPUserModelDelegate(local);
List<LDAPStorageMapper> mappers = getMappers(realm).toList();
proxied = new ReadonlyLDAPUserModelDelegate(local, readOnlyAttributes(realm, mappers, getMappedUserAttributes(mappers)));
} else {
proxied = new ReadOnlyUserModelDelegate(local);
}
Expand Down Expand Up @@ -535,16 +536,16 @@ private Condition createSearchCondition(LDAPQueryConditionsBuilder conditionsBui

/**
* Searches LDAP using logical conjunction of params. It uses the LDAP mappers
* (method <em>getUserAttributes</em>) to control what attributes are
* (method <em>getSearchableUserAttributes</em>) to control what attributes are
* managed by the ldap server. If one attribute is not defined by the
* mappers then empty stream is returned (the attribute is not mapped
* into ldap, therefore no ldap user can have the specified value).
*/
private Stream<LDAPObject> searchLDAPByAttributes(RealmModel realm, Map<String, String> attributes, Integer firstResult, Integer maxResults) {
// get the attributes that are managed by the configured ldap mappers
// get attributes backed by LDAP and supported in search conditions
Set<String> managedAttrs = realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName())
.map(mapperManager::getMapper)
.map(LDAPStorageMapper::getUserAttributes)
.map(LDAPStorageMapper::getSearchableUserAttributes)
.flatMap(Set::stream)
.collect(Collectors.toSet());

Expand Down Expand Up @@ -1233,12 +1234,8 @@ public List<AttributeMetadata> decorateUserProfile(String providerId, UserProfil
.count();
RealmModel realm = session.getContext().getRealm();
// 1 - get configured attributes from LDAP mappers and add them to the user profile (if they not already present)
List<String> attributes = realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName())
.sorted(ldapMappersComparator.sortAsc())
.flatMap(mapperModel -> {
LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
return ldapMapper.getUserAttributes().stream();
}).toList();
List<LDAPStorageMapper> mappers = getMappers(realm).toList();
List<String> attributes = getMappedUserAttributes(mappers);

List<AttributeMetadata> metadatas = new ArrayList<>();

Expand Down Expand Up @@ -1269,16 +1266,46 @@ public List<AttributeMetadata> decorateUserProfile(String providerId, UserProfil
}
}

// 3 - make all attributes read-only for LDAP users in case that LDAP itself is read-only
// 3 - protect LDAP-owned attributes, leaving local attributes subject to User Profile permissions
if (getEditMode() == EditMode.READ_ONLY) {
Predicate<String> readOnly = model.isImportEnabled() ? readOnlyAttributes(realm, mappers, attributes)
: name -> !INTERNAL_ATTRIBUTES.contains(name);
Stream.concat(metadata.getAttributes().stream(), metadatas.stream())
.filter((m) -> !INTERNAL_ATTRIBUTES.contains(m.getName()))
.filter(m -> readOnly.test(m.getName()))
.forEach(attrMetadata -> attrMetadata.addWriteCondition(AttributeMetadata.ALWAYS_FALSE));
}

return metadatas;
}

private Stream<LDAPStorageMapper> getMappers(RealmModel realm) {
return realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName())
.sorted(ldapMappersComparator.sortAsc())
.map(mapperManager::getMapper);
}

private List<String> getMappedUserAttributes(List<LDAPStorageMapper> mappers) {
return mappers.stream()
.flatMap(mapper -> mapper.getUserAttributes().stream())
.distinct()
.toList();
}

private Predicate<String> readOnlyAttributes(RealmModel realm, List<LDAPStorageMapper> mappers, List<String> mappedAttributes) {
Set<String> attributes = new HashSet<>(List.of(UserModel.USERNAME, LDAPConstants.LDAP_ID, LDAPConstants.LDAP_ENTRY_DN,
KerberosConstants.KERBEROS_PRINCIPAL));
if (realm.isRegistrationEmailAsUsername()) {
attributes.add(UserModel.EMAIL);
}
// Mappers can populate built-in properties using a differently cased name.
for (String property : List.of(UserModel.FIRST_NAME, UserModel.LAST_NAME, UserModel.EMAIL)) {
if (mappedAttributes.stream().anyMatch(property::equalsIgnoreCase)) {
attributes.add(property);
}
}
return name -> attributes.contains(name) || mappers.stream().anyMatch(mapper -> mapper.managesUserAttribute(name));
}

@Override
public Stream<CredentialModel> getCredentials(RealmModel realm, UserModel user) {
LDAPObject ldapObject = loadLDAPUserByUuid(realm, user.getFirstAttribute(LDAPConstants.LDAP_ID));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.keycloak.models.UserModel;
Expand All @@ -36,33 +37,56 @@
*/
public class ReadonlyLDAPUserModelDelegate extends UserModelDelegate {

private final Predicate<String> readOnlyAttribute;

public ReadonlyLDAPUserModelDelegate(UserModel delegate) {
this(delegate, name -> !INTERNAL_ATTRIBUTES.contains(name));
}

public ReadonlyLDAPUserModelDelegate(UserModel delegate, Predicate<String> readOnlyAttribute) {
super(delegate);
this.readOnlyAttribute = readOnlyAttribute;
}

@Override
public void setUsername(String username) {
if (!readOnlyAttribute.test(UserModel.USERNAME)) {
super.setUsername(username);
return;
}
if (!Objects.equals(getUsername(), username)) {
throw new ReadOnlyException("Federated storage is not writable");
}
}

@Override
public void setLastName(String lastName) {
if (!readOnlyAttribute.test(UserModel.LAST_NAME)) {
super.setLastName(lastName);
return;
}
if (!Objects.equals(getLastName(), lastName)) {
throw new ReadOnlyException("Federated storage is not writable");
}
}

@Override
public void setFirstName(String first) {
if (!readOnlyAttribute.test(UserModel.FIRST_NAME)) {
super.setFirstName(first);
return;
}
if (!Objects.equals(getFirstName(), first)) {
throw new ReadOnlyException("Federated storage is not writable");
}
}

@Override
public void setEmail(String email) {
if (!readOnlyAttribute.test(UserModel.EMAIL)) {
super.setEmail(email);
return;
}
if (!Objects.equals(getEmail(), email)) {
throw new ReadOnlyException("Federated storage is not writable");
}
Expand All @@ -75,7 +99,7 @@ public void setSingleAttribute(String name, String value) {

@Override
public void setAttribute(String name, List<String> values) {
if (INTERNAL_ATTRIBUTES.contains(name)) {
if (!readOnlyAttribute.test(name)) {
super.setAttribute(name, values);
return;
}
Expand All @@ -86,7 +110,7 @@ public void setAttribute(String name, List<String> values) {

@Override
public void removeAttribute(String name) {
if (INTERNAL_ATTRIBUTES.contains(name)) {
if (!readOnlyAttribute.test(name)) {
super.removeAttribute(name);
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
package org.keycloak.storage.ldap.mappers;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;

import org.keycloak.component.ComponentModel;
Expand Down Expand Up @@ -66,6 +68,16 @@ public void onRegisterUserToLDAP(LDAPObject ldapUser, UserModel localUser, Realm

}

@Override
public Set<String> getUserAttributes() {
return Collections.singleton(getUserModelAttribute());
}
Comment thread
Oluwatobi-Mustapha marked this conversation as resolved.
Resolved

@Override
public Set<String> getSearchableUserAttributes() {
return Collections.emptySet();
}

@Override
public UserModel proxy(final LDAPObject ldapUser, UserModel delegate, RealmModel realm) {
String userModelAttrName = getUserModelAttribute();
Expand Down Expand Up @@ -131,4 +143,4 @@ public void beforeLDAPQuery(LDAPQuery query) {

}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,32 @@ public interface LDAPStorageMapper extends Provider {
Set<String> mandatoryAttributeNames();

/**
* Method that returns user model attributes, which this mapper maps to Keycloak users
* Method that returns user model attributes, which this mapper maps to Keycloak users.
* All attributes managed by the mapper must be declared here so that they remain protected
* when the LDAP provider's edit mode is {@code READ_ONLY}.
*
* @return user model attributes. Returns empty set if not user attributes provided by this mapper. Never returns null.
*/
Set<String> getUserAttributes();

/**
* Returns whether the mapper manages the given user model attribute name.
* Override this method if the mapper recognizes names beyond exact matches of its declared attributes.
*/
default boolean managesUserAttribute(String name) {
return getUserAttributes().contains(name);
}

/**
* Returns user model attributes that can be used to build LDAP search conditions.
* By default, all attributes mapped by this mapper are searchable in LDAP.
*
* @return user model attributes backed by LDAP. Never returns null.
*/
default Set<String> getSearchableUserAttributes() {
return getUserAttributes();
}

/**
* Called when invoke proxy on LDAP federation provider
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,11 @@ public Set<String> getUserAttributes() {
return Collections.singleton(getUserModelAttribute());
}

@Override
public boolean managesUserAttribute(String name) {
return getUserModelAttribute().equalsIgnoreCase(name);
}

// throw ModelDuplicateException if there is different user in model with same email
protected void checkDuplicateEmail(String userModelAttrName, String email, RealmModel realm, KeycloakSession session, UserModel user) {
if (email == null || realm.isDuplicateEmailsAllowed()) return;
Expand Down Expand Up @@ -417,7 +422,7 @@ private String decodeValue(String value) {

@Override
public String getFirstAttribute(String name) {
if (name.equalsIgnoreCase(userModelAttrName)) {
if (managesUserAttribute(name)) {
return decodeValue(ldapUser.getAttributeAsString(ldapAttrName));
} else {
return super.getFirstAttribute(name);
Expand All @@ -426,7 +431,7 @@ public String getFirstAttribute(String name) {

@Override
public Stream<String> getAttributeStream(String name) {
if (name.equalsIgnoreCase(userModelAttrName)) {
if (managesUserAttribute(name)) {
Collection<String> ldapAttrValue = ldapUser.getAttributeAsSet(ldapAttrName);
if (ldapAttrValue == null) {
return Stream.empty();
Expand Down
Loading
Loading
0