Compare commits

..

6 commits

Author SHA1 Message Date
510c045070 Formatting
All checks were successful
/ Verify (pull_request) Successful in 52s
/ Verify (push) Successful in 46s
2026-07-21 21:20:15 +02:00
218ee1dd57 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.
2026-07-19 13:21:57 +02:00
f204ab7f28 Add just the testing setup from #26.
All checks were successful
/ Verify (pull_request) Successful in 1m12s
/ Verify (push) Successful in 53s
Important: there are changes here to adapt the tests and the Keycloak test realm that are incompatible with the changes in #29. Ultimately, the changes in #29 need to be applied over this.
2026-07-19 10:27:51 +02:00
6cd678b414 Spell option correctly
All checks were successful
/ Verify (push) Successful in 45s
2026-07-18 21:41:42 +02:00
89ce38f6c1 Be less verbose when building
Some checks failed
/ Verify (push) Failing after 17s
2026-07-18 21:40:39 +02:00
0a84d2ddf9 Only build when pushing to main
All checks were successful
/ Verify (push) Successful in 46s
or on a pull request
2026-07-18 21:38:50 +02:00
6 changed files with 163 additions and 182 deletions

View file

@ -1,10 +1,12 @@
on: on:
pull_request: pull_request:
push: push:
branches:
- main
jobs: jobs:
test: ansible-lint:
name: Test name: Verify
runs-on: docker runs-on: docker
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
@ -12,6 +14,6 @@ jobs:
run: | run: |
apt update apt update
apt install -y maven apt install -y maven
- name: Run maven verify test - name: Run maven verify
run: | run: |
mvn -f attribute-endpoints-provider verify test mvn -f attribute-endpoints-provider --batch-mode --no-transfer-progress verify

118
README.md
View file

@ -1,39 +1,16 @@
# Attribute Endpoints Provider - Export User Attributes # Attribute Endpoints Provider
This is a Keycloak Provider that exports user profile attribute values. This is a Keycloak Provider that exports an anonymized list of user profile attribute values.
The selection of attributes and authorization is manage through an endpoint configuration. For this it will provide API endpoints for every configured attribute-group.
The configuration of the provider is possible via an admin page.
## Usage Every endpoint responds with a list of all attribute values, that:
- are in the attribute group matching `attribute-group`
The provider adds an object type "Attribute Endpoints" to the Keycloak admin website. - match an optional RegEx Pattern `attribute-regex`
You configure the provider by creating one or more endpoint configurations. - belong to a user with a role matching `match-role`
- are non-empty
Each endpoint configuration requires:
- a name that is the reference in the endpoint URL (slug)
- the name of a role that the calling user must have to be allowed to query this endpoint
- the name of an attribute or an attribute group that should be exported
- the name of a role that users must have to be included in the list
- an optional regular expression that must match to have a value included
- whether to default to the user email if the attribute is empty
> **Note** The attribute (group) and the roles need to exist before you can create the endpoint configuration.
There are two endpoints returning JSON:
- `export/slug`: collate all attribute values into a single list
- `export/slug/map`: produce a map of lists, with the key being the attribute name
No other data is included in the response, in particular, there is no information on which attribute value is associated with which user.
User Attribute values can be single or multi-value; the resulting list will include them as a flattened list.
> **⚠️ Note** The authorization and the selection of the user attributes are not tied together in any way.
> Every user that has the matching role will have all the attributes included that are specified in the endpoint configuration.
> In other words, if you are exporting an attribute group, all attributes will be included.
> **⚠️ Note** Keycloak has no concept of authorization for individual user attributes (for example, based on assigned roles).
> Users will be able to see and edit any attribute that has been made available to users, irrespective of whether a user would
> be included in an endpoint configuration export or not.
Multivalue attributes are flattened in the response.
## Building ## Building
@ -43,8 +20,79 @@ Once all dependencies are met, simply call `make` to build the provider, which s
There's also `make clean` available for removing the output directory. There's also `make clean` available for removing the output directory.
To add the provider to your Keycloak install, copy `attribute-endpoints-provider/target/attribute-endpoints-provider-1.0-SNAPSHOT.jar` to the Keycloak Provider directory (`/opt/keycloak/providers/).
## Testing Setup ## Testing Setup
See [testing/README.md](testing/README.md) for details on the Docker Compose based setup that includes a realm and the ability to attach a debugger to the running Keycloak. See [testing/README.md](testing/README.md) for details on the Docker Compose based setup that includes a realm and the ability to attach a debugger to the running Keycloak.
## Example Setup
We assume an unconfigured, fresh Keycloak installation running under `http://localhost:8080`.
(This can be achieved by running the provided `compose.yaml` after building the provider as outlined in [Building](#building).)
1. Add a new realm
e.g. "TestRealm"
2. Under `Realm Settings > User profile > Attributes Group`, add a new attribute Group
Example:
- `Name` = `"my-attributes-group"`
- `Display name` = `"Endpoint Attributes"`
- `Display description` = `"Attributes exported by the provider."`
3. Under `Realm Settings > User profile > Attributes`, add a new attribute
Example:
- `Attribute [Name]` = `"ssh-keys"`
- `Display name ` = `"SSH Keys"`
- `Multivalued` = `On`
- `Attribute group` = `"my-attributes-group"`
- `Who can edit?` = `user, admin`
- `Validators`
You can add validators, which will limit what values the user can enter. These validators are ignored by the provider.
4. Under `Realm roles`, add two new roles
Example:
1. `Role name` = `"myattribute-match"`
2. `Role name` = `"myattribute-export"`
5. Under `Users`, add a new user
Example:
- `Username` = `"user"`
- `Email` = `"user@example.com"`
- `First name` = `"User"`
- `Last name` = `"User"`
- `SSH Keys` = `"example-value-1", "example-value-2"`
6. In the Settings of the newly created user, go to `Role mapping > Assing role > Realm roles` and check the role `myattribute-match`
7. create a second user to use the provider
- `Username` = `"bot-user"`
- `Email` = `"bot@example.com"`
- `First name` = `"Bot"`
- `Last name` = `"Bot"`
- After creating:
- give it the role `myattribute-export`
- set a password in the users settings `Creadentials > Set password`. For Example `"password"`
8. Under `Attribute Endpoints > Create item`, add a new endpoint to the provider
Example:
- `Slug` = `"ssh_keys"`
- `Attribute Group` = `"my-attributes-group"`
- `Match Role` = `"myattribute-match"`
- `Auth Role` = `"myattribute-export"`
- `Attribute RegEx` = `".*"`
9. Aquire an OIDC Access Token:
```shell
curl --request POST \
--url http://localhost:8080/realms/TestRealm/protocol/openid-connect/token \
--header 'content-type: application/x-www-form-urlencoded' \
--data scope=openid \
--data username=bot-user \
--data password=password \
--data grant_type=password \
--data client_id=admin-cli
```
10. copy the value of the response key `access_token` and use it in a second request:
```shell
curl --request GET \
--url http://localhost:8080/realms/TestRealm/attribute-endpoints-provider/export/ssh_keys \
--header 'authorization: Bearer ey...' \
--header 'content-type: application/json'
```
11. You should get a response like this:
```json
["example-value-1","example-value-2"]
```
Although this example uses a simple bot account to authenticate to Keycloak, we recommend using a client with service account, when using this provider programmatically.

View file

@ -1,12 +1,15 @@
package de.ccc.hamburg.keycloak.attribute_endpoints; package de.ccc.hamburg.keycloak.attribute_endpoints;
import com.google.auto.service.AutoService; import java.util.List;
import java.util.regex.Pattern;
import org.keycloak.Config; import org.keycloak.Config;
import org.keycloak.component.ComponentModel; import org.keycloak.component.ComponentModel;
import org.keycloak.component.ComponentValidationException; import org.keycloak.component.ComponentValidationException;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.provider.ProviderConfigProperty; import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.provider.ProviderConfigurationBuilder; import org.keycloak.provider.ProviderConfigurationBuilder;
import org.keycloak.representations.userprofile.config.UPConfig; import org.keycloak.representations.userprofile.config.UPConfig;
@ -14,8 +17,7 @@ import org.keycloak.services.ui.extend.UiPageProvider;
import org.keycloak.services.ui.extend.UiPageProviderFactory; import org.keycloak.services.ui.extend.UiPageProviderFactory;
import org.keycloak.userprofile.UserProfileProvider; import org.keycloak.userprofile.UserProfileProvider;
import java.util.List; import com.google.auto.service.AutoService;
import java.util.regex.Pattern;
/** /**
* Implements UiPageProvider to show a config page in the admin * Implements UiPageProvider to show a config page in the admin
@ -41,7 +43,6 @@ public class AdminUiPage implements UiPageProvider, UiPageProviderFactory<Compon
return PROVIDER_ID; return PROVIDER_ID;
} }
@Override
public String getHelpText() { public String getHelpText() {
return "Configure endpoints of the Attribute Endpoint Provider."; return "Configure endpoints of the Attribute Endpoint Provider.";
} }
@ -49,7 +50,7 @@ public class AdminUiPage implements UiPageProvider, UiPageProviderFactory<Compon
@Override @Override
public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel model) { public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel model) {
String errorString = "\n"; String errorString = "\n";
boolean hasError = false; Boolean hasError = false;
Pattern slugPattern = Pattern.compile("^[a-zA-Z0-9_-]*$"); Pattern slugPattern = Pattern.compile("^[a-zA-Z0-9_-]*$");
String configAttributeSlug = model.getConfig().getFirst("slug"); String configAttributeSlug = model.getConfig().getFirst("slug");
@ -85,15 +86,13 @@ public class AdminUiPage implements UiPageProvider, UiPageProviderFactory<Compon
if (configAttributeGroup == null) { if (configAttributeGroup == null) {
hasError = true; hasError = true;
errorString += " • [Attribute Group] can not be empty\n"; errorString += " • [Attribute Group] can not be empty\n";
} else if (upconfig.getAttributes().stream().noneMatch(a -> } else if (!upconfig.getGroups().stream().anyMatch(g -> g.getName().equals(configAttributeGroup))) {
a.getName().equals(configAttributeGroup)
|| (a.getGroup() != null && a.getGroup().equals(configAttributeGroup)))) {
hasError = true; hasError = true;
errorString += " • [Attribute Group] no matching Attribute or Attribute Group\n"; errorString += " • [Attribute Group] does not exist\n";
} }
String configAttributeRegex = model.getConfig().getFirst("attribute-regex"); String configAttributeRegex = model.getConfig().getFirst("attribute-regex");
boolean regexIsBlank = configAttributeRegex == null; Boolean regexIsBlank = configAttributeRegex == null;
if (!regexIsBlank) { if (!regexIsBlank) {
try { try {
@ -114,47 +113,40 @@ public class AdminUiPage implements UiPageProvider, UiPageProviderFactory<Compon
return ProviderConfigurationBuilder.create() return ProviderConfigurationBuilder.create()
.property() .property()
.name("slug") .name("slug")
.label("Endpoint URL Slug") .label("Slug")
.helpText( .helpText(
"The slug in the path of the API endpoint (e.g. /realms/:realm/attribute-endpoint-provider/export/:slug)") "The slug in the path of the API endpoint (e.g. /realms/:realm/attribute-endpoint-provider/export/:slug)")
.type(ProviderConfigProperty.STRING_TYPE) .type(ProviderConfigProperty.STRING_TYPE)
.add() .add()
.property()
.name("auth-role")
.label("Endpoint Role")
.helpText("Calling this endpoint configuration requires an authenticated user that has this role.")
.type(ProviderConfigProperty.STRING_TYPE)
.add()
.property() .property()
.name("attribute-group") .name("attribute-group")
.label("Attribute Name or Group") .label("Attribute Group")
.helpText("The attribute or attribute group to export.") .helpText("The attribute group to export.")
.type(ProviderConfigProperty.STRING_TYPE) .type(ProviderConfigProperty.STRING_TYPE)
.add() .add()
.property() .property()
.name("match-role") .name("match-role")
.label("User Match Role") .label("Match Role")
.helpText("Only users with this role will have the attributes exported.") .helpText("Export only attributes of users with this role.")
.type(ProviderConfigProperty.STRING_TYPE)
.add()
.property()
.name("auth-role")
.label("Auth Role")
.helpText("Role needeed by the authenticated account to be able to use this endpoint.")
.type(ProviderConfigProperty.STRING_TYPE) .type(ProviderConfigProperty.STRING_TYPE)
.add() .add()
.property() .property()
.name("attribute-regex") .name("attribute-regex")
.label("Validation Regex") .label("Attribute RegEx")
.helpText("Only values matching this regex will be included in the result. Optional.") .helpText("A RegEx Rule used to verify each attribute value. Only matching values are returned.")
.type(ProviderConfigProperty.STRING_TYPE) .type(ProviderConfigProperty.STRING_TYPE)
.add() .add()
.property()
.name("default-to-user-email")
.label("Default to User Email")
.helpText("When the attribute value is empty, use the users email address instead. If the value is not a valid email address, it will not be included in the export.")
.type(ProviderConfigProperty.BOOLEAN_TYPE)
.add()
.build(); .build();
} }

View file

@ -18,7 +18,6 @@ import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
public class AttributeEndpointsResourceProvider implements RealmResourceProvider { public class AttributeEndpointsResourceProvider implements RealmResourceProvider {
@ -52,9 +51,8 @@ public class AttributeEndpointsResourceProvider implements RealmResourceProvider
List<String> attribute_list = ctx.users List<String> attribute_list = ctx.users
.map(user -> { .map(user -> {
Stream<String> attributeStream = ctx.attributeNames.stream(); Stream<String> attributeStream = ctx.attributeNames.stream()
.map(attributeName -> user.getAttributeStream(attributeName).toList())
attributeStream = attributeStream.map(attributeName -> ctx.MapUserAttribute(user, attributeName).toList())
.flatMap(Collection::stream); .flatMap(Collection::stream);
return attributeStream return attributeStream
@ -68,46 +66,14 @@ public class AttributeEndpointsResourceProvider implements RealmResourceProvider
return Response.ok(attribute_list).build(); return Response.ok(attribute_list).build();
} }
/**
* Return a map of lists of attribute values. For each attribute in the named attribute
* group, add an entry in the resulting map with the attribute name as the key, and the
* values as a list as the values.
*
* @param attributeGroupName attribute group name
* @return a map of attribute names and their values
*/
@GET
@Path("export/{attributeGroupName}/map")
@Produces(MediaType.APPLICATION_JSON)
public Response exportAttributeValuesMap(@PathParam("attributeGroupName") String attributeGroupName) {
AttributeExportContext ctx = new AttributeExportContext(attributeGroupName);
List<UserModel> userList = ctx.users.toList();
Map<String, List<String>> attributeMap = ctx.attributeNames.stream()
.collect(Collectors.toMap(
attributeName -> attributeName,
attributeName -> userList.stream()
.flatMap(user -> ctx.MapUserAttribute(user, attributeName))
.filter(attribute -> !attribute.isEmpty())
.filter(ctx.filter::matches)
.toList()));
return Response.ok(attributeMap).build();
}
/** /**
* Resolves and validates the configuration and request state needed to export attribute * Resolves and validates the configuration and request state needed to export attribute
* values for a given slug, exposing the results as member variables. * values for a given slug, exposing the results as member variables.
*/ */
private class AttributeExportContext { private class AttributeExportContext {
final Pattern validEmail = Pattern.compile("@");
List<String> attributeNames; List<String> attributeNames;
UserModel authUser; UserModel authUser;
String configAttributeGroup; String configAttributeGroup;
boolean defaultToUserEmail;
RegExFilter filter; RegExFilter filter;
UPConfig upconfig; UPConfig upconfig;
Stream<UserModel> users; Stream<UserModel> users;
@ -121,38 +87,37 @@ public class AttributeEndpointsResourceProvider implements RealmResourceProvider
.toList(); .toList();
if (componentList.isEmpty()) { if (componentList.isEmpty()) {
throw new NotFoundException("Attribute Endpoint " + slug + " not found"); throw new NotFoundException("Endpoint not found.");
} }
if (componentList.size() > 1) { if (componentList.size() > 1) {
throw new NotFoundException( throw new NotFoundException(
"Attribute Endpoint Configuration Error - Multiple configurations exist for " + slug); "Endpoint Configuration Error - Multiple configurations exist for this endpoint.");
} }
ComponentModel component = componentList.get(0); ComponentModel component = componentList.get(0);
RoleModel authRole = realm.getRole(component.getConfig().getFirst("auth-role")); RoleModel authRole = realm.getRole(component.getConfig().getFirst("auth-role"));
if (authRole == null) { if (authRole == null) {
throw new ServerErrorException("Attribute Endpoint " + slug + " Configuration Error - auth-role does not exist.", 500); throw new ServerErrorException("Endpoint Configuration Error - auth-role does not exist.", 500);
} }
RoleModel matchRole = realm.getRole(component.getConfig().getFirst("match-role")); RoleModel matchRole = realm.getRole(component.getConfig().getFirst("match-role"));
if (matchRole == null) { if (matchRole == null) {
throw new ServerErrorException("Attribute Endpoint " + slug + " Configuration Error - match-role does not exist.", 500); throw new ServerErrorException("Endpoint Configuration Error - match-role does not exist.", 500);
} }
upconfig = session.getProvider(UserProfileProvider.class).getConfiguration(); upconfig = session.getProvider(UserProfileProvider.class).getConfiguration();
configAttributeGroup = component.getConfig().getFirst("attribute-group"); configAttributeGroup = component.getConfig().getFirst("attribute-group");
if (upconfig.getGroups().stream().noneMatch(g -> g.getName().equals(configAttributeGroup)) && if (upconfig.getGroups().stream().noneMatch(g -> g.getName().equals(configAttributeGroup))) {
upconfig.getAttributes().stream().noneMatch(a -> a.getName().equals(configAttributeGroup))) { throw new ServerErrorException("Endpoint Configuration Error - attribute-group does not exist.", 500);
throw new ServerErrorException("Attribute Endpoint " + slug + " Configuration Error - no attribute or attribute group named " + configAttributeGroup + " found", 500);
} }
try { try {
filter = new RegExFilter(component.getConfig().getFirst("attribute-regex")); filter = new RegExFilter(component.getConfig().getFirst("attribute-regex"));
} catch (Exception e) { } catch (Exception e) {
throw new ServerErrorException( throw new ServerErrorException(
"Attribute Endpoint " + slug + " Configuration Error - attribute-regex is not a valid regex pattern.", 500); "Endpoint Configuration Error - attribute-regex is not a valid regex pattern.", 500);
} }
authUser = AttributeEndpointsResourceProvider.getAuth(session).getUser(); authUser = AttributeEndpointsResourceProvider.getAuth(session).getUser();
@ -164,34 +129,13 @@ public class AttributeEndpointsResourceProvider implements RealmResourceProvider
// select all attributes that match configAttributeGroup, or that are in a group that matches configAttributeGroup // select all attributes that match configAttributeGroup, or that are in a group that matches configAttributeGroup
attributeNames = upconfig.getAttributes() attributeNames = upconfig.getAttributes()
.stream() .stream()
.filter(a -> .filter(a -> a.getGroup() != null && a.getGroup().equals(configAttributeGroup))
a.getName().equals(configAttributeGroup)
|| (a.getGroup() != null && a.getGroup().equals(configAttributeGroup)))
.map(UPAttribute::getName) .map(UPAttribute::getName)
.toList(); .toList();
UserProvider userProvider = session.users(); UserProvider userProvider = session.users();
users = userProvider.searchForUserStream(realm, Map.of()) users = userProvider.searchForUserStream(realm, Map.of())
.filter(user -> user.hasRole(matchRole)); .filter(user -> user.hasRole(matchRole));
defaultToUserEmail = Boolean.parseBoolean(component.getConfig().getFirstOrDefault("default-to-user-email", "false"));
}
/**
* If defaultToUserEmail is set, default to user email if no attribute exists, and remove any value that is not
* a valid email address.
*
* @param user the user whose attributes are being exported
* @param attributeName the attribute to export
* @return a stream of attribute values
*/
Stream<String> MapUserAttribute(UserModel user, String attributeName) {
if (defaultToUserEmail) {
// need to load everything otherwise we can't check for non-existent attribute
Map<String, List<String>> attrs = user.getAttributes();
return attrs.getOrDefault(attributeName,
List.of(user.getEmail())).stream().filter(v -> !validEmail.matcher(v).matches());
}
return user.getAttributeStream(attributeName);
} }
} }

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;
@ -68,36 +66,34 @@ public class AttributeEndpointsResourceProviderTest {
List<ComponentModel> components = List.of( List<ComponentModel> components = List.of(
attributeEndpointComponent("dooris-ssh-keys", attributeEndpointComponent("dooris-ssh-keys",
"export-dooris-ssh-keys", "dooris-authorized", "dooris-ssh-keys", "export-dooris-ssh-keys", "dooris-authorized", "dooris-ssh-keys"),
false),
attributeEndpointComponent("mailing-list-addresses-chaos", attributeEndpointComponent("mailing-list-addresses-chaos",
"export-mailing-list-addresses", "mailing-list-chaos-member", MAILING_LIST_CHAOS, "export-mailing-list-addresses", "mailing-list-chaos-member", MAILING_LIST_CHAOS),
true),
attributeEndpointComponent("mailing-list-addresses-intern", attributeEndpointComponent("mailing-list-addresses-intern",
"export-mailing-list-addresses", "mailing-list-intern-member", MAILING_LIST_INTERN, "export-mailing-list-addresses", "mailing-list-intern-member", MAILING_LIST_INTERN));
true));
when(realm.getComponentsStream()).thenAnswer(inv -> components.stream()); when(realm.getComponentsStream()).thenAnswer(inv -> components.stream());
UserProfileProvider userProfileProvider = mock(UserProfileProvider.class); UserProfileProvider userProfileProvider = mock(UserProfileProvider.class);
when(session.getProvider(UserProfileProvider.class)).thenReturn(userProfileProvider); when(session.getProvider(UserProfileProvider.class)).thenReturn(userProfileProvider);
when(userProfileProvider.getConfiguration()).thenReturn(testUserProfileConfig()); when(userProfileProvider.getConfiguration()).thenReturn(testUserProfileConfig());
hacker = user("hacker", "hacker@example.net", Map.of( hacker = user("hacker", Map.of(
SSH_KEY_1, List.of("hacker-ssh-key-1"), SSH_KEY_1, "hacker-ssh-key-1",
SSH_KEY_2, List.of("hacker-ssh-key-2"), SSH_KEY_2, "hacker-ssh-key-2",
MAILING_LIST_INTERN, List.of("hacker+intern@example.net")), MAILING_LIST_CHAOS, "hacker+chaos@example.net",
MAILING_LIST_INTERN, "hacker+intern@example.net"),
List.of("dooris-authorized", "mailing-list-chaos-member", "mailing-list-intern-member")); List.of("dooris-authorized", "mailing-list-chaos-member", "mailing-list-intern-member"));
tester = user("tester", "tester@example.com", Map.of( tester = user("tester", Map.of(
SSH_KEY_1, List.of("tester-ssh-key-1"), SSH_KEY_1, "tester-ssh-key-1",
SSH_KEY_2, List.of("tester-ssh-key-2"), SSH_KEY_2, "tester-ssh-key-2",
MAILING_LIST_CHAOS, List.of("tester+chaos@example.com"), MAILING_LIST_CHAOS, "tester+chaos@example.com",
MAILING_LIST_INTERN, List.of("tester+intern@example.com")), MAILING_LIST_INTERN, "tester+intern@example.com"),
List.of("mailing-list-chaos-member")); List.of("mailing-list-chaos-member"));
noone = user("noone", "noone@example.org", Map.of( noone = user("noone", Map.of(
SSH_KEY_1, List.of("noone-ssh-key-1"), SSH_KEY_1, "noone-ssh-key-1",
SSH_KEY_2, List.of("noone-ssh-key-2"), SSH_KEY_2, "noone-ssh-key-2",
MAILING_LIST_CHAOS, List.of("noone+chaos@example.org"), MAILING_LIST_CHAOS, "noone+chaos@example.org",
MAILING_LIST_INTERN, List.of("noone+intern@example.org", "-")), MAILING_LIST_INTERN, "noone+intern@example.org"),
Collections.emptyList()); Collections.emptyList());
UserProvider userProvider = mock(UserProvider.class); UserProvider userProvider = mock(UserProvider.class);
@ -116,6 +112,7 @@ public class AttributeEndpointsResourceProviderTest {
} }
} }
/* NOTYET
@Test @Test
public void exportAttributeValuesMap_doorisSlug_returnsSshKeysPerAttribute() { public void exportAttributeValuesMap_doorisSlug_returnsSshKeysPerAttribute() {
try (Response response = callAuthenticatedAs("export-dooris-ssh-keys", try (Response response = callAuthenticatedAs("export-dooris-ssh-keys",
@ -128,7 +125,9 @@ public class AttributeEndpointsResourceProviderTest {
response.getEntity()); response.getEntity());
} }
} }
*/
/* NOTYET
@Test @Test
public void exportAttributeValues_mailingListChaosSlug_returnsAddressesOfAllMatchingUsers() { public void exportAttributeValues_mailingListChaosSlug_returnsAddressesOfAllMatchingUsers() {
try (Response response = callAuthenticatedAs("export-mailing-list-addresses", try (Response response = callAuthenticatedAs("export-mailing-list-addresses",
@ -136,10 +135,12 @@ public class AttributeEndpointsResourceProviderTest {
.exportAttributeValues("mailing-list-addresses-chaos"))) { .exportAttributeValues("mailing-list-addresses-chaos"))) {
assertEquals(200, response.getStatus()); assertEquals(200, response.getStatus());
assertEquals(List.of("hacker@example.net", "tester+chaos@example.com"), response.getEntity()); assertEquals(List.of("hacker+chaos@example.net", "tester+chaos@example.com"), response.getEntity());
} }
} }
*/
/* NOTYET
@Test @Test
public void exportAttributeValues_mailingListInternSlug_returnsAddressOfSingleMatchingUser() { public void exportAttributeValues_mailingListInternSlug_returnsAddressOfSingleMatchingUser() {
try (Response response = callAuthenticatedAs("export-mailing-list-addresses", try (Response response = callAuthenticatedAs("export-mailing-list-addresses",
@ -150,7 +151,9 @@ public class AttributeEndpointsResourceProviderTest {
assertEquals(List.of("hacker+intern@example.net"), response.getEntity()); assertEquals(List.of("hacker+intern@example.net"), response.getEntity());
} }
} }
*/
/* NOTYET
@Test @Test
public void exportAttributeValuesMap_mailingListChaosSlug_returnsAddressesPerAttribute() { public void exportAttributeValuesMap_mailingListChaosSlug_returnsAddressesPerAttribute() {
try (Response response = callAuthenticatedAs("export-mailing-list-addresses", try (Response response = callAuthenticatedAs("export-mailing-list-addresses",
@ -159,10 +162,11 @@ public class AttributeEndpointsResourceProviderTest {
assertEquals(200, response.getStatus()); assertEquals(200, response.getStatus());
assertEquals(Map.of(MAILING_LIST_CHAOS, assertEquals(Map.of(MAILING_LIST_CHAOS,
List.of("hacker@example.net", "tester+chaos@example.com")), List.of("hacker+chaos@example.net", "tester+chaos@example.com")),
response.getEntity()); response.getEntity());
} }
} }
*/
@Test @Test
public void exportAttributeValues_unknownSlug_throwsNotFound() { public void exportAttributeValues_unknownSlug_throwsNotFound() {
@ -178,11 +182,9 @@ public class AttributeEndpointsResourceProviderTest {
public void exportAttributeValues_duplicateSlugConfiguration_throwsNotFound() { public void exportAttributeValues_duplicateSlugConfiguration_throwsNotFound() {
List<ComponentModel> duplicateComponents = List.of( List<ComponentModel> duplicateComponents = List.of(
attributeEndpointComponent("duplicate-slug", attributeEndpointComponent("duplicate-slug",
"export-dooris-ssh-keys", "dooris-authorized", "dooris-ssh-keys", "export-dooris-ssh-keys", "dooris-authorized", "dooris-ssh-keys"),
false),
attributeEndpointComponent("duplicate-slug", attributeEndpointComponent("duplicate-slug",
"export-dooris-ssh-keys", "dooris-authorized", "dooris-ssh-keys", "export-dooris-ssh-keys", "dooris-authorized", "dooris-ssh-keys"));
false));
when(realm.getComponentsStream()).thenAnswer(inv -> duplicateComponents.stream()); when(realm.getComponentsStream()).thenAnswer(inv -> duplicateComponents.stream());
NotFoundException exception = assertThrows(NotFoundException.class, NotFoundException exception = assertThrows(NotFoundException.class,
@ -197,8 +199,7 @@ public class AttributeEndpointsResourceProviderTest {
public void exportAttributeValues_missingAuthRole_throwsServerError() { public void exportAttributeValues_missingAuthRole_throwsServerError() {
List<ComponentModel> components = List.of( List<ComponentModel> components = List.of(
attributeEndpointComponent("bad-auth-role", attributeEndpointComponent("bad-auth-role",
"nonexistent-role", "dooris-authorized", "dooris-ssh-keys", "nonexistent-role", "dooris-authorized", "dooris-ssh-keys"));
false));
when(realm.getComponentsStream()).thenAnswer(inv -> components.stream()); when(realm.getComponentsStream()).thenAnswer(inv -> components.stream());
ServerErrorException exception = assertThrows(ServerErrorException.class, ServerErrorException exception = assertThrows(ServerErrorException.class,
@ -213,8 +214,7 @@ public class AttributeEndpointsResourceProviderTest {
public void exportAttributeValues_missingMatchRole_throwsServerError() { public void exportAttributeValues_missingMatchRole_throwsServerError() {
List<ComponentModel> components = List.of( List<ComponentModel> components = List.of(
attributeEndpointComponent("bad-match-role", attributeEndpointComponent("bad-match-role",
"export-dooris-ssh-keys", "nonexistent-role", "dooris-ssh-keys", "export-dooris-ssh-keys", "nonexistent-role", "dooris-ssh-keys"));
false));
when(realm.getComponentsStream()).thenAnswer(inv -> components.stream()); when(realm.getComponentsStream()).thenAnswer(inv -> components.stream());
ServerErrorException exception = assertThrows(ServerErrorException.class, ServerErrorException exception = assertThrows(ServerErrorException.class,
@ -228,8 +228,7 @@ public class AttributeEndpointsResourceProviderTest {
@Test @Test
public void exportAttributeValues_invalidAttributeRegex_throwsServerError() { public void exportAttributeValues_invalidAttributeRegex_throwsServerError() {
ComponentModel component = attributeEndpointComponent("bad-regex", ComponentModel component = attributeEndpointComponent("bad-regex",
"export-dooris-ssh-keys", "dooris-authorized", "dooris-ssh-keys", "export-dooris-ssh-keys", "dooris-authorized", "dooris-ssh-keys");
false);
component.put("attribute-regex", "["); component.put("attribute-regex", "[");
when(realm.getComponentsStream()).thenAnswer(inv -> Stream.of(component)); when(realm.getComponentsStream()).thenAnswer(inv -> Stream.of(component));
@ -268,14 +267,13 @@ public class AttributeEndpointsResourceProviderTest {
} }
private static ComponentModel attributeEndpointComponent(String slug, String authRole, String matchRole, private static ComponentModel attributeEndpointComponent(String slug, String authRole, String matchRole,
String attributeGroup, boolean defaultToUserEmail) { String attributeGroup) {
ComponentModel component = new ComponentModel(); ComponentModel component = new ComponentModel();
component.setProviderId(AdminUiPage.PROVIDER_ID); component.setProviderId(AdminUiPage.PROVIDER_ID);
component.put("slug", slug); component.put("slug", slug);
component.put("auth-role", authRole); component.put("auth-role", authRole);
component.put("match-role", matchRole); component.put("match-role", matchRole);
component.put("attribute-group", attributeGroup); component.put("attribute-group", attributeGroup);
component.put("default-to-user-email", Boolean.toString(defaultToUserEmail));
return component; return component;
} }
@ -299,15 +297,13 @@ public class AttributeEndpointsResourceProviderTest {
return attribute; return attribute;
} }
private UserModel user(String username, String email, Map<String, List<String>> attributes, List<String> roleNames) { private UserModel user(String username, Map<String, String> attributes, List<String> roleNames) {
UserModel user = mock(UserModel.class); UserModel user = mock(UserModel.class);
when(user.getUsername()).thenReturn(username); when(user.getUsername()).thenReturn(username);
when(user.getEmail()).thenReturn(email.isBlank() ? null : email);
when(user.getAttributes()).thenReturn(attributes);
when(user.getAttributeStream(anyString())).thenAnswer(inv -> Stream.empty()); when(user.getAttributeStream(anyString())).thenAnswer(inv -> Stream.empty());
attributes.forEach((name, value) -> attributes.forEach((name, value) ->
when(user.getAttributeStream(eq(name))).thenAnswer(inv -> value.stream())); when(user.getAttributeStream(eq(name))).thenAnswer(inv -> Stream.of(value)));
when(user.hasRole(any(RoleModel.class))).thenReturn(false); when(user.hasRole(any(RoleModel.class))).thenReturn(false);
roleNames.forEach(name -> when(user.hasRole(roles.get(name))).thenReturn(true)); roleNames.forEach(name -> when(user.hasRole(roles.get(name))).thenReturn(true));

View file

@ -447,7 +447,8 @@
"attributes" : { "attributes" : {
"ssh-key-1" : [ "hacker-ssh-key-1" ], "ssh-key-1" : [ "hacker-ssh-key-1" ],
"mailing-list-address-intern" : [ "hacker+intern@example.net" ], "mailing-list-address-intern" : [ "hacker+intern@example.net" ],
"ssh-key-2" : [ "hacker-ssh-key-2" ] "ssh-key-2" : [ "hacker-ssh-key-2" ],
"mailing-list-address-chaos" : [ "hacker+chaos@example.net" ]
}, },
"enabled" : true, "enabled" : true,
"createdTimestamp" : 1784376038850, "createdTimestamp" : 1784376038850,
@ -1477,7 +1478,7 @@
"subType" : "authenticated", "subType" : "authenticated",
"subComponents" : { }, "subComponents" : { },
"config" : { "config" : {
"allowed-protocol-mapper-types" : [ "saml-user-attribute-mapper", "oidc-sha256-pairwise-sub-mapper", "oidc-usermodel-property-mapper", "saml-role-list-mapper", "oidc-usermodel-attribute-mapper", "saml-user-property-mapper", "oidc-full-name-mapper", "oidc-address-mapper" ] "allowed-protocol-mapper-types" : [ "saml-user-property-mapper", "oidc-usermodel-property-mapper", "saml-role-list-mapper", "oidc-full-name-mapper", "saml-user-attribute-mapper", "oidc-address-mapper", "oidc-usermodel-attribute-mapper", "oidc-sha256-pairwise-sub-mapper" ]
} }
}, { }, {
"id" : "a49de9bf-462b-4c61-bb52-0373732f4b1b", "id" : "a49de9bf-462b-4c61-bb52-0373732f4b1b",
@ -1537,7 +1538,7 @@
"subType" : "anonymous", "subType" : "anonymous",
"subComponents" : { }, "subComponents" : { },
"config" : { "config" : {
"allowed-protocol-mapper-types" : [ "saml-user-attribute-mapper", "oidc-usermodel-attribute-mapper", "oidc-sha256-pairwise-sub-mapper", "oidc-full-name-mapper", "saml-role-list-mapper", "oidc-usermodel-property-mapper", "oidc-address-mapper", "saml-user-property-mapper" ] "allowed-protocol-mapper-types" : [ "saml-role-list-mapper", "saml-user-attribute-mapper", "oidc-usermodel-attribute-mapper", "oidc-usermodel-property-mapper", "saml-user-property-mapper", "oidc-full-name-mapper", "oidc-address-mapper", "oidc-sha256-pairwise-sub-mapper" ]
} }
}, { }, {
"id" : "dd4024e9-f080-4319-aeb7-7f9906c345c5", "id" : "dd4024e9-f080-4319-aeb7-7f9906c345c5",
@ -1604,9 +1605,8 @@
"subComponents" : { }, "subComponents" : { },
"config" : { "config" : {
"match-role" : [ "mailing-list-intern-member" ], "match-role" : [ "mailing-list-intern-member" ],
"default-to-user-email" : [ "true" ], "attribute-group" : [ "mailing-list-addresses" ],
"auth-role" : [ "export-mailing-list-addresses" ], "auth-role" : [ "export-mailing-list-addresses" ],
"attribute-group" : [ "mailing-list-address-intern" ],
"slug" : [ "mailing-list-addresses-intern" ] "slug" : [ "mailing-list-addresses-intern" ]
} }
}, { }, {
@ -1625,9 +1625,8 @@
"subComponents" : { }, "subComponents" : { },
"config" : { "config" : {
"match-role" : [ "mailing-list-chaos-member" ], "match-role" : [ "mailing-list-chaos-member" ],
"default-to-user-email" : [ "true" ],
"attribute-group" : [ "mailing-list-address-chaos" ],
"auth-role" : [ "export-mailing-list-addresses" ], "auth-role" : [ "export-mailing-list-addresses" ],
"attribute-group" : [ "mailing-list-addresses" ],
"slug" : [ "mailing-list-addresses-chaos" ] "slug" : [ "mailing-list-addresses-chaos" ]
} }
} ] } ]