8000 Allow adding realm users as an organization member by pedroigor · Pull Request #29029 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
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 @@ -17,10 +17,8 @@

package org.keycloak.admin.client.resource;

import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
Expand All @@ -32,10 +30,6 @@ public interface OrganizationMemberResource {
@Produces(MediaType.APPLICATION_JSON)
UserRepresentation toRepresentation();

@PUT
@Consumes(MediaType.APPLICATION_JSON)
Response update(UserRepresentation organization);

@DELETE
Response delete();
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public interface OrganizationMembersResource {

@POST
@Consumes(MediaType.APPLICATION_JSON)
Response addMember(UserRepresentation member);
Response addMember(String userId);

@GET
@Produces(MediaType.APPLICATION_JSON)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,14 @@ List<OrganizationRepresentation> search(
@QueryParam("first") Integer first,
@QueryParam("max") Integer max
);

/**
* Return all organizations that match the specified filter.
*
* @param search a {@code String} representing either an organization name or domain.
* @return a list containing the matched organizations.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
List<OrganizationRepresentation> search(@QueryParam("search") String search);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@

package org.keycloak.organization.jpa;

import static org.keycloak.models.OrganizationModel.USER_ORGANIZATION_ATTRIBUTE;
import static org.keycloak.models.OrganizationModel.ORGANIZATION_ATTRIBUTE;
import static org.keycloak.models.jpa.PaginationUtils.paginateQuery;
import static org.keycloak.utils.StreamsUtil.closing;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand All @@ -29,6 +30,7 @@
import jakarta.persistence.NoResultException;
import jakarta.persistence.TypedQuery;
import org.keycloak.connections.jpa.JpaConnectionProvider;
import org.keycloak.models.FederatedIdentityModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.GroupProvider;
import org.keycloak.models.IdentityProviderModel;
Expand Down Expand Up @@ -94,7 +96,7 @@ public boolean remove(OrganizationModel organization) {
GroupModel group = getOrganizationGroup(organization);

//TODO: won't scale, requires a better mechanism for bulk deleting users
userProvider.getGroupMembersStream(realm, group).forEach(userModel -> userProvider.removeUser(realm, userModel));
userProvider.getGroupMembersStream(realm, group).forEach(userModel -> removeMember(organization, userModel));
groupProvider.removeGroup(realm, group);

realm.removeIdentityProviderByAlias(entity.getIdpAlias());
Expand Down Expand Up @@ -122,12 +124,12 @@ public boolean addMember(OrganizationModel organization, UserModel user) {
return false;
}

if (user.getFirstAttribute(USER_ORGANIZATION_ATTRIBUTE) != null) {
if (user.getFirstAttribute(ORGANIZATION_ATTRIBUTE) != null) {
throw new ModelException("User [" + user.getId() + "] is a member of a different organization");
}

user.joinGroup(group);
user.setSingleAttribute(USER_ORGANIZATION_ATTRIBUTE, entity.getId());
user.setSingleAttribute(ORGANIZATION_ATTRIBUTE, entity.getId());

return true;
}
Expand Down Expand Up @@ -185,7 +187,7 @@ public UserModel getMemberById(OrganizationModel organization, String id) {
return null;
}

String orgId = user.getFirstAttribute(USER_ORGANIZATION_ATTRIBUTE);
String orgId = user.getFirstAttribute(ORGANIZATION_ATTRIBUTE);

if (organization.getId().equals(orgId)) {
return user;
Expand All @@ -198,7 +200,7 @@ public UserModel getMemberById(OrganizationModel organization, String id) {
public OrganizationModel getByMember(UserModel member) {
throwExceptionIfObjectIsNull(member, "User");

String orgId = member.getFirstAttribute(USER_ORGANIZATION_ATTRIBUTE);
String orgId = member.getFirstAttribute(ORGANIZATION_ATTRIBUTE);

if (orgId == null) {
return null;
Expand All @@ -214,6 +216,9 @@ public boolean addIdentityProvider(OrganizationModel organization, IdentityProvi

OrganizationEntity organizationEntity = getEntity(organization.getId());
organizationEntity.setIdpAlias(identityProvider.getAlias());
identityProvider.getConfig().put(ORGANIZATION_ATTRIBUTE, organization.getId());
realm.updateIdentityProvider(identityProvider);

return true;
}

Expand All @@ -236,6 +241,48 @@ public boolean removeIdentityProvider(OrganizationModel organization) {
return true;
}

@Override
public boolean isManagedMember(OrganizationModel organization, UserModel member) {
throwExceptionIfObjectIsNull(organization, "organization");

if (member == null) {
return false;
}

IdentityProviderModel identityProvider = organization.getIdentityProvider();

if (identityProvider == null) {
return false;
}

FederatedIdentityModel federatedIdentity = userProvider.getFederatedIdentity(realm, member, identityProvider.getAlias());

return federatedIdentity != null;
}

@Override
public boolean removeMember(OrganizationModel organization, UserModel member) {
throwExceptionIfObjectIsNull(organization, "organization");
throwExceptionIfObjectIsNull(member, "member");

OrganizationModel userOrg = getByMember(member);

if (userOrg == null || !userOrg.equals(organization)) {
return false;
}

if (isManagedMember(organization, member)) {
userProvider.removeUser(realm, member);
} else {
List<String> organizations = member.getAttributes().get(ORGANIZATION_ATTRIBUTE);
organizations.remove(organization.getId());
member.setAttribute(ORGANIZATION_ATTRIBUTE, organizations);
member.leaveGroup(getOrganizationGroup(organization));
}

return true;
}

@Override
public boolean isEnabled() {
return getAllStream().findAny().isPresent();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.keycloak.models.OrganizationDomainModel;
import org.keycloak.models.OrganizationModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.jpa.JpaModel;
import org.keycloak.models.jpa.entities.OrganizationDomainEntity;
import org.keycloak.models.jpa.entities.OrganizationEntity;
Expand Down Expand Up @@ -133,6 +134,11 @@ public IdentityProviderModel getIdentityProvider() {
return provider.getIdentityProvider(this);
}

@Override
public boolean isManaged(UserModel user) {
return provider.isManagedMember(this, user);
}

@Override
public OrganizationEntity getEntity() {
return entity;
Expand All @@ -154,6 +160,20 @@ public String toString() {
.append(getGroupId()).toString();
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OrganizationModel)) return false;

OrganizationModel that = (OrganizationModel) o;
return that.getId().equals(getId());
}

@Override
public int hashCode() {
return getId().hashCode();
}

private OrganizationDomainModel toModel(OrganizationDomainEntity entity) {
return new OrganizationDomainModel(entity.getName(), entity.isVerified());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,4 +156,35 @@ default Stream<OrganizationModel> getAllStream() {
* @return {@code true} if organization is supported. Otherwise, returns {@code false}
*/
boolean isEnabled();

/**
* <p>Indicates if the given {@code member} is managed by the organization.
*
* <p>A member is managed by the organization whenever the member cannot exist without the organization they belong
* to so that their lifecycle is bound to the organization lifecycle. For instance, when a member is federated from
* the identity provider associated with an organization, there is a strong relationship between the member identity
* and the organization.
*
* <p>On the other hand, existing realm users whose identities are not intrinsically linked to an organization but
* are eventually joining an organization are not managed by the organization. They have a lifecycle that does not
* depend on the organization they are linked to.
*
* @param organization the organization
* @param member the member
* @return {@code true} if the {@code member} is managed by the given {@code organization}. Otherwise, returns {@code false}
*/
boolean isManagedMember(OrganizationModel organization, UserModel member);

/**
* <p>Removes a member from the organization.
*
* <p>This method can either remove the given {@code member} entirely from the realm (and the organization) or only
* remove the link to the {@code organization} so that the user still exists but is no longer a member of the organization.
* The decision to remove the user entirely or only the link depends on whether the user is managed by the organization or not, respectively.
*
* @param organization the organization
* @param member the member
* @return {@code true} if the given {@code member} is a member and was successfully removed from the organization. Otherwise, returns {@code false}
*/
boolean removeMember(OrganizationModel organization, UserModel member);
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

public interface OrganizationModel {

String USER_ORGANIZATION_ATTRIBUTE = "kc.org";
String ORGANIZATION_ATTRIBUTE = "kc.org";

String getId();

Expand All @@ -41,4 +41,6 @@ public interface OrganizationModel {
void setDomains(Set<OrganizationDomainModel> domains);

IdentityProviderModel getIdentityProvider();

boolean isManaged(UserModel user);
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ public class IdentityProviderBean {
private RealmModel realm;
private final KeycloakSession session;

public IdentityProviderBean() {
this.session = null;
}

public IdentityProviderBean(RealmModel realm, KeycloakSession session, List<IdentityProviderModel> identityProviders, URI baseURI) {
this.realm = realm;
this.session = session;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,32 +79,23 @@ public OrganizationMemberResource(KeycloakSession session, OrganizationModel org

@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response addMember(UserRepresentation rep) {
public Response addMember(String id) {
auth.realm().requireManageRealm();
if (rep == null || !Objects.equals(rep.getUsername(), rep.getEmail())) {
throw ErrorResponse.error("To add a member to the organization it is expected the username and the email is the same.", Status.BAD_REQUEST);
UserModel user = session.users().getUserById(realm, id);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if the user is not a local user i.e user imported from LDAP or a custom user federation? (id in f:uuid:uuid format) Do we want to allow the user to become a member?

@pedroigor pedroigor Apr 24, 2024 •
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't this handled by UserStorageManager? I don't see any reason why don't allow any realm user to become a member.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@martin-kanis please correct me if I am wrong ... I believe the question or concern might come from a fact that there is no control over those users who are not local keycloak users, so any update to those users (such as messing up with kc.org attribute) might be done outside of Keycloak.

Would there be needed some mechanism to prevent/detect this kind of outside updates?

@pedroigor pedroigor Apr 24, 2024 •
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For LDAP, we can do that as attributes like this one are very likely to be managed through a mapper. For custom providers, it will depend on how they are managing the user attributes.

Federated users (from custom providers) have their attributes stored in a specific table in Keycloak. I think we can handle such cases as well.

We can discuss this in a follow-up if you guys want as this PR is blocking others to go in. It is a very valid point and we need to see how to deal with custom user storages.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, a mapper would probably be in place for cases like this if we are to propagate the persistence of the org attribute to LDAP. But the question still remains - if an admin changes the org in LDAP, how are we going to handle that? Will we need to validate these changes when re-importing/validating the user?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we don't allow creating a mapper to kc.org we don't need to worry about this, I would say.

The real problem, I would say, is with custom user providers because they have access to internals and can easily bypass user profile or any other validation we enforce elsewhere.


if (user == null) {
throw ErrorResponse.error("User does not exist", Status.BAD_REQUEST);
}

UsersResource usersResource = new UsersResource(session, auth, adminEvent);
Response response = usersResource.createUser(rep);

if (Status.CREATED.getStatusCode() == response.getStatus()) {

UserModel member = session.users().getUserByUsername(realm, rep.getEmail());

String errorMessage;
try {
if (provider.addMember(organization, member)) {
return response;
}
errorMessage = "Assigning the User as member of the organization was not succesful.";
} catch (ModelException me) {
errorMessage = me.getMessage();
try {
if (provider.addMember(organization, user)) {
return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(user.getId()).build()).build();
}
throw ErrorResponse.error(errorMessage, Status.BAD_REQUEST);
} catch (ModelException me) {
throw ErrorResponse.error(me.getMessage(), Status.BAD_REQUEST);
}

return response;
throw ErrorResponse.error("User is already a member of the organization.", Status.CONFLICT);
}

@GET
Expand Down Expand Up @@ -136,7 +127,11 @@ public Response delete(@PathParam("id") String id) {

UserModel member = getMember(id);

return new UserResource(session, member, auth, adminEvent).deleteUser();
if (provider.removeMember(organization, member)) {
return Response.noContent().build();
}

throw ErrorResponse.error("Not a member of the organization", Status.BAD_REQUEST);
}

@Path("{id}")
Expand All @@ -158,6 +153,11 @@ public OrganizationRepresentation getOrganization(@PathParam("id") String id) {

UserModel member = getMember(id);
OrganizationModel organization = provider.getByMember(member);

if (organization == null) {
throw ErrorResponse.error("Not associated with an organization", Status.NOT_FOUND);
}

OrganizationRepresentation rep = new OrganizationRepresentation();

rep.setId(organization.getId());
Expand Down
Loading
0