Add just the refactoring from #26.
All checks were successful
/ Verify (pull_request) Successful in 45s

This is based off #31, so that needs to be merged first.
This commit is contained in:
Stefan Bethke 2026-07-19 10:45:08 +02:00
commit 218ee1dd57
2 changed files with 105 additions and 99 deletions

View file

@ -1,21 +1,12 @@
package de.ccc.hamburg.keycloak.attribute_endpoints; package de.ccc.hamburg.keycloak.attribute_endpoints;
import java.util.Collection; import jakarta.ws.rs.*;
import java.util.List; import jakarta.ws.rs.core.MediaType;
import java.util.Map; import jakarta.ws.rs.core.Response;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import org.keycloak.component.ComponentModel; import org.keycloak.component.ComponentModel;
import org.keycloak.models.ClientModel; import org.keycloak.models.*;
import org.keycloak.models.KeycloakContext; import org.keycloak.representations.userprofile.config.UPAttribute;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserProvider;
import org.keycloak.representations.userprofile.config.UPConfig; import org.keycloak.representations.userprofile.config.UPConfig;
import org.keycloak.services.managers.AppAuthManager; import org.keycloak.services.managers.AppAuthManager;
import org.keycloak.services.managers.Auth; import org.keycloak.services.managers.Auth;
@ -23,16 +14,11 @@ import org.keycloak.services.managers.AuthenticationManager.AuthResult;
import org.keycloak.services.resource.RealmResourceProvider; import org.keycloak.services.resource.RealmResourceProvider;
import org.keycloak.userprofile.UserProfileProvider; import org.keycloak.userprofile.UserProfileProvider;
import jakarta.ws.rs.ForbiddenException; import java.util.Collection;
import jakarta.ws.rs.GET; import java.util.List;
import jakarta.ws.rs.NotAuthorizedException; import java.util.Map;
import jakarta.ws.rs.NotFoundException; import java.util.regex.Pattern;
import jakarta.ws.rs.Path; import java.util.stream.Stream;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.ServerErrorException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
public class AttributeEndpointsResourceProvider implements RealmResourceProvider { public class AttributeEndpointsResourceProvider implements RealmResourceProvider {
private static final Logger LOG = Logger.getLogger(AttributeEndpointsResourceProvider.class); private static final Logger LOG = Logger.getLogger(AttributeEndpointsResourceProvider.class);
@ -51,22 +37,57 @@ public class AttributeEndpointsResourceProvider implements RealmResourceProvider
public void close() { public void close() {
} }
/**
* Returns a list of all attribute values selected by the attribute group attributeGroupName.
*
* @param attributeGroupName attribute group name
* @return a list of attribute values.
*/
@GET @GET
@Path("export/{slug}") @Path("export/{slug}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Response exportAttributeValues(@PathParam("slug") String slug) { public Response exportAttributeValues(@PathParam("slug") String attributeGroupName) {
KeycloakContext context = session.getContext(); AttributeExportContext ctx = new AttributeExportContext(attributeGroupName);
RealmModel realm = context.getRealm();
List<String> attribute_list = ctx.users
.map(user -> {
Stream<String> attributeStream = ctx.attributeNames.stream()
.map(attributeName -> user.getAttributeStream(attributeName).toList())
.flatMap(Collection::stream);
return attributeStream
.filter(attribute -> !attribute.isEmpty())
.toList();
})
.flatMap(List::stream)
.filter(ctx.filter::matches)
.toList();
return Response.ok(attribute_list).build();
}
/**
* Resolves and validates the configuration and request state needed to export attribute
* values for a given slug, exposing the results as member variables.
*/
private class AttributeExportContext {
List<String> attributeNames;
UserModel authUser;
String configAttributeGroup;
RegExFilter filter;
UPConfig upconfig;
Stream<UserModel> users;
AttributeExportContext(String slug) {
RealmModel realm = session.getContext().getRealm();
List<ComponentModel> componentList = realm.getComponentsStream() List<ComponentModel> componentList = realm.getComponentsStream()
.filter(c -> c.getProviderId().equals(AdminUiPage.PROVIDER_ID)) .filter(c -> c.getProviderId().equals(AdminUiPage.PROVIDER_ID))
.filter(c -> c.getConfig().getFirst("slug").equals(slug)) .filter(c -> c.getConfig().getFirst("slug").equals(slug))
.toList(); .toList();
Auth auth = AttributeEndpointsResourceProvider.getAuth(session);
if (componentList.isEmpty()) { if (componentList.isEmpty()) {
throw new NotFoundException("Endpoint not found."); throw new NotFoundException("Endpoint not found");
} }
if (componentList.size() > 1) { if (componentList.size() > 1) {
@ -76,76 +97,46 @@ public class AttributeEndpointsResourceProvider implements RealmResourceProvider
ComponentModel component = componentList.get(0); ComponentModel component = componentList.get(0);
String configAuthRole = component.getConfig().getFirst("auth-role"); RoleModel authRole = realm.getRole(component.getConfig().getFirst("auth-role"));
RoleModel authRole = realm.getRole(configAuthRole);
if (authRole == null) { if (authRole == null) {
throw new ServerErrorException("Endpoint Configuration Error - auth-role does not exist.", 500); throw new ServerErrorException("Endpoint Configuration Error - auth-role does not exist.", 500);
} }
String configMatchRole = component.getConfig().getFirst("match-role"); RoleModel matchRole = realm.getRole(component.getConfig().getFirst("match-role"));
RoleModel matchRole = realm.getRole(configMatchRole);
if (matchRole == null) { if (matchRole == null) {
throw new ServerErrorException("Endpoint Configuration Error - match-role does not exist.", 500); throw new ServerErrorException("Endpoint Configuration Error - match-role does not exist.", 500);
} }
UserProfileProvider profileProvider = session.getProvider(UserProfileProvider.class); upconfig = session.getProvider(UserProfileProvider.class).getConfiguration();
UPConfig upconfig = profileProvider.getConfiguration(); configAttributeGroup = component.getConfig().getFirst("attribute-group");
String configAttributeGroup = component.getConfig().getFirst("attribute-group"); if (upconfig.getGroups().stream().noneMatch(g -> g.getName().equals(configAttributeGroup))) {
if (!upconfig.getGroups().stream().anyMatch(g -> g.getName().equals(configAttributeGroup))) {
throw new ServerErrorException("Endpoint Configuration Error - attribute-group does not exist.", 500); throw new ServerErrorException("Endpoint Configuration Error - attribute-group does not exist.", 500);
} }
String configAttributeRegex = component.getConfig().getFirst("attribute-regex");
Boolean regexIsBlank = configAttributeRegex == null;
if (!regexIsBlank) {
try { try {
Pattern.compile(configAttributeRegex); filter = new RegExFilter(component.getConfig().getFirst("attribute-regex"));
} catch (Exception e) { } catch (Exception e) {
throw new ServerErrorException( throw new ServerErrorException(
"Endpoint Configuration Error - attribute-regex is not a valid regex pattern.", 500); "Endpoint Configuration Error - attribute-regex is not a valid regex pattern.", 500);
} }
}
UserModel authUser = auth.getUser(); authUser = AttributeEndpointsResourceProvider.getAuth(session).getUser();
if (!authUser.hasRole(authRole)) { if (!authUser.hasRole(authRole)) {
LOG.info("User " + authUser.getUsername() + " does not have required role " + authRole.getName()); LOG.info("User " + authUser.getUsername() + " does not have required role " + authRole.getName() + " for attribute endpoint " + slug);
throw new ForbiddenException("User does not have required auth role."); throw new ForbiddenException("User does not have required auth role.");
} }
List<String> attributeNames = upconfig.getAttributes() // select all attributes that match configAttributeGroup, or that are in a group that matches configAttributeGroup
attributeNames = upconfig.getAttributes()
.stream() .stream()
.filter(a -> a.getGroup() != null && a.getGroup().equals(configAttributeGroup)) .filter(a -> a.getGroup() != null && a.getGroup().equals(configAttributeGroup))
.map(a -> a.getName()) .map(UPAttribute::getName)
.toList(); .toList();
UserProvider userProvider = session.users(); UserProvider userProvider = session.users();
Stream<UserModel> users = userProvider.searchForUserStream(realm, Map.of()) users = userProvider.searchForUserStream(realm, Map.of())
.filter(user -> user.hasRole(matchRole)); .filter(user -> user.hasRole(matchRole));
List<String> attribute_list = users
.map(user -> {
Stream<String> attributeStream = attributeNames.stream()
.map(attributeName -> user.getAttributeStream(attributeName).toList())
.flatMap(Collection::stream);
return attributeStream
.filter(attribute -> !attribute.isEmpty())
.toList();
})
.flatMap(List::stream)
.filter(attribute -> {
if (regexIsBlank) {
return true;
} }
final Pattern pattern = Pattern.compile(configAttributeRegex);
final Matcher matcher = pattern.matcher(attribute);
return matcher.find();
})
.toList();
return Response.ok(attribute_list).build();
} }
private static Auth getAuth(KeycloakSession session) { private static Auth getAuth(KeycloakSession session) {
@ -156,8 +147,25 @@ public class AttributeEndpointsResourceProvider implements RealmResourceProvider
} }
RealmModel realm = session.getContext().getRealm(); RealmModel realm = session.getContext().getRealm();
ClientModel client = auth.getClient(); ClientModel client = auth.client();
return new Auth(realm, auth.getToken(), auth.getUser(), client, auth.getSession(), false); return new Auth(realm, auth.token(), auth.user(), client, auth.session(), false);
}
private static class RegExFilter {
Pattern pattern;
RegExFilter(String regex) {
if (regex == null)
pattern = null;
else
pattern = Pattern.compile(regex);
}
boolean matches(String input) {
if (pattern == null)
return true;
return pattern.matcher(input).matches();
}
} }
} }

View file

@ -24,9 +24,7 @@ import java.util.Map;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;