8000 refactor: adding a roles service for v2 by shawkins · Pull Request #55049 · 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
11 changes: 11 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,17 @@ For example, if an administrator marked the user's email as not verified, a late
Previously, the flag was left unchanged for existing users with an unchanged address in this situation.
If this behavior is not desired, set *Trust Email* to *OFF* for that identity provider. {project_name} then leaves the flag unchanged for existing users whose email address has not changed, and sets it to `false` for new users until the email is verified locally.

=== Client roles managed through Admin API v2 emit client events instead of role events
// https://github.com/keycloak/keycloak/issues/51326

When managing clients using the declarative Client Admin API v2 (`client-admin-api:v2`), role modifications no longer emit individual `CLIENT_ROLE` admin events (`CREATE` or `DELETE`).
Instead, operations emit a single `CLIENT` admin event (`CREATE`, `UPDATE`, or `DELETE`) representing the client resource as a whole, with the `apiVersion` detail set to `v2`.

The `representation` property of the `CLIENT` event contains the full declarative client representation, including the updated list of client roles in the `roles` field.
Because the representation reflects the resulting state of the client rather than an incremental delta of modified roles, event listeners and integrations that previously tracked individual `CLIENT_ROLE` events must now inspect the client's `roles` field and compare it against the previously known state or snapshot of the client to determine which roles were added, modified, or removed.

Managing client roles through the legacy Admin API v1 role endpoints (`/admin/realms/{realm}/clients/{id}/roles`) continues to emit individual `CLIENT_ROLE` admin events as before.

=== Custom truststore in `kcadm` and `kcreg` now rejects self-signed certificates not present in the truststore

When `kcadm` or `kcreg` is configured with a custom truststore (via `--truststore` or `config truststore`), a self-signed server certificate is now only accepted if it has been explicitly imported into that truststore.
Expand Down
9 changes: 9 additions & 0 deletions docs/guides/admin-api/admin-api-v2.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,15 @@ The Admin API v2 uses the same CLI tool described in the {adminguide_link}#admin

<@kc.admin parameters="--v2 config credentials --server http://localhost:8080 --realm master --user admin"/>

== Admin Events

When managing clients with the Admin API v2, administrative events are emitted at the client resource level (`resourceType=CLIENT`) rather than at the child resource level.
Client roles configured on a client representation are managed declaratively and do not produce individual `CLIENT_ROLE` admin events.

When a client is created, updated, or deleted through Admin API v2, {project_name} emits a single `CLIENT` admin event with the `apiVersion: v2` detail.
The event representation contains the serialized client representation, including the full list of client roles in the `roles` field.
Because the event representation reflects the desired resulting state of the client rather than an incremental diff of individual role changes, event listeners that need to track specific role additions or removals should compare the `roles` list in the event representation with a previously saved snapshot or state of that client.

== Available Resources

For details on filtering and projection, see <@links.adminapi id="querying" />.
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
import org.keycloak.representations.admin.v2.validation.PatchClient;
import org.keycloak.representations.admin.v2.validation.PutClient;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.scim.filter.ScimFilterException;
import org.keycloak.scim.model.filter.ScimAttributeJpaExpressionResolver;
import org.keycloak.scim.model.filter.ScimJPAPredicateEvaluator;
Expand All @@ -57,7 +56,6 @@
import org.keycloak.scim.resource.spi.BaseResourceTypeProvider;
import org.keycloak.scim.resource.spi.SearchOptions;
import org.keycloak.scim.resource.spi.SortField;
import org.keycloak.services.RolesService;
import org.keycloak.services.ServiceException;
import org.keycloak.services.client.ClientSortField;
import org.keycloak.services.client.SimpleClientModel;
Expand All @@ -75,9 +73,9 @@
import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.resources.admin.AdminEventBuilder;
import org.keycloak.services.resources.admin.AdminRoot;
import org.keycloak.services.resources.admin.RoleContainerResource;
import org.keycloak.services.resources.admin.fgap.AdminPermissionEvaluator;
import org.keycloak.services.resources.admin.fgap.AdminPermissions;
import org.keycloak.services.roles.RoleService;
import org.keycloak.validation.ValidationUtil;
import org.keycloak.validation.jakarta.HibernateValidatorProvider;
import org.keycloak.validation.jakarta.JakartaValidatorProvider;
Expand All @@ -101,7 +99,7 @@ public class ClientResourceTypeProvider extends BaseResourceTypeProvider<ClientM
private final AdminEventBuilder adminEventBuilder;
private final RealmModel realm;
private final JakartaValidatorProvider validator;
private final RolesService rolesService;
private final RoleService roleService;

public ClientResourceTypeProvider(KeycloakSession session) {
super(session, SCHEMAS.values().stream());
Expand All @@ -110,7 +108,7 @@ public ClientResourceTypeProvider(KeycloakSession session) {
this.permissions = AdminPermissions.evaluator(session, realm, authInfo);
this.adminEventBuilder = new AdminEventV2Builder(realm, permissions.adminAuth(), session, session.getContext().getConnection()).resource(ResourceType.CLIENT);
this.validator = new HibernateValidatorProvider(new ValidationContext(session, realm));
this.rolesService = new RolesService(session, realm, permissions, adminEventBuilder);
this.roleService = new RoleService(session, realm, permissions);
}

public Map<String, BaseClientModelSchema<? extends BaseClientRepresentation>> getSchemaMap() {
Expand Down Expand Up @@ -234,8 +232,7 @@ private BaseClientRepresentation onCreateOrUpdate(BaseClientRepresentation clien
}

// Setup roles
var clientRoles = rolesService.resource(model);
handleRoles(clientRoles, client.getRoles());
handleRoles(model, client.getRoles());
Comment thread
vmuzikar marked this conversation as resolved.
Resolved

// OIDC specific
if (client instanceof OIDCClientRepresentation oidcClient) {
Expand Down Expand Up @@ -287,19 +284,17 @@ protected boolean onDelete(ClientModel client) {
}

/**
* Fires a v2 admin event for client operations (only enabled for testing now to avoid duplicated admin events)
* Fires a v2 admin event for client operations
*
* @param operationType the type of operation (CREATE, UPDATE, DELETE)
* @param representation the v2 representation of the client
*/
protected void fireAdminEvent(OperationType operationType, BaseClientRepresentation representation) {
if (Boolean.parseBoolean(System.getProperty("kc.admin-v2.client-service.events.enabled", "false"))) {
adminEventBuilder
.operation(operationType)
.resourcePath(session.getContext().getUri())
.representation(representation)
.success();
}
adminEventBuilder
.operation(operationType)
.resourcePath(session.getContext().getUri())
.representation(representation)
.success();
}

@Override
Expand Down Expand Up @@ -473,25 +468,25 @@ private String generateClientSecretIfNeeded(BaseClientRepresentation client, Cli
/**
* Declaratively manage client roles - ensures the client has exactly the roles specified in 'rolesFromRep'
* <p>
* Reuses API v1 logic
* Role events are intentionally not fired here, the client event carries the change.
*/
protected void handleRoles(RoleContainerResource clientRoles, Set<String> rolesFromRep) {
protected void handleRoles(ClientModel client, Set<String> rolesFromRep) {
Set<String> desiredRoleNames = Optional.ofNullable(rolesFromRep)
.orElse(Collections.emptySet());

Set<String> currentRoleNames = clientRoles.getRoles(null, null, null, false)
.map(RoleRepresentation::getName)
Set<String> currentRoleNames = roleService.list(client, null, null, null)
.map(RoleModel::getName)
.collect(Collectors.toSet());

// Add missing roles (in desiredRoleNames but not in currentRoleNames)
desiredRoleNames.stream()
.filter(roleName -> !currentRoleNames.contains(roleName))
.forEach(roleName -> clientRoles.doCreateRole(new RoleRepresentation(roleName, "", false)));
.forEach(roleName -> roleService.create(client, roleName, "", null));
Comment thread
vmuzikar marked this conversation as resolved.
Resolved

// Remove extra roles (in currentRoleNames but not in desiredRoleNames)
currentRoleNames.stream()
.filter(role -> !desiredRoleNames.contains(role))
.forEach(clientRoles::deleteRole);
.forEach(roleName -> roleService.delete(client, roleName));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,21 @@

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Set;

import org.keycloak.authentication.authenticators.client.ClientIdAndSecretAuthenticator;
import org.keycloak.common.Profile;
import org.keycloak.events.admin.OperationType;
import org.keycloak.events.admin.ResourceType;
import org.keycloak.representations.admin.v2.OIDCClientRepresentation;
import org.keycloak.representations.idm.AdminEventRepresentation;
import org.keycloak.representations.idm.RealmEventsConfigRepresentation;
import org.keycloak.testframework.annotations.InjectRealm;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.testframework.realm.ManagedRealm;
import org.keycloak.testframework.remote.runonserver.InjectRunOnServer;
import org.keycloak.testframework.remote.runonserver.RunOnServerClient;
import org.keycloak.testframework.server.KeycloakServerConfig;
import org.keycloak.testframework.server.KeycloakServerConfigBuilder;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

Expand All @@ -60,9 +59,6 @@
public class AdminEventV2Test extends AbstractClientApiV2Test {
private static final String TEST_CLIENT_ID = "v2-rep-test-client";

@InjectRunOnServer
RunOnServerClient runOnServer;

@InjectRealm
ManagedRealm testRealm;

Expand All @@ -73,11 +69,6 @@ public String getRealmName() {

@BeforeEach
public void setupAndClearEvents() {
runOnServer.run(session -> {
// enable Admin v2 events on the server
System.setProperty("kc.admin-v2.client-service.events.enabled", "true");
});

// Enable admin events on test realm
RealmEventsConfigRepresentation eventsConfig = testRealm.admin().getRealmEventsConfig();
eventsConfig.setAdminEventsEnabled(true);
Expand All @@ -88,14 +79,6 @@ public void setupAndClearEvents() {
testRealm.admin().clearAdminEvents();
}

@AfterEach
public void disableAdminEventsV2() {
runOnServer.run(session -> {
// enable Admin v2 events on the server
System.clearProperty("kc.admin-v2.client-service.events.enabled");
});
}

@Test
public void createClientFiresV2Event() throws Exception {
createTestClient();
Expand Down Expand Up @@ -209,6 +192,40 @@ public void deleteClientFiresV2Event() throws Exception {
}
}

@Test
public void updateClientRolesFiresOnlyClientEvent() throws Exception {
createTestClient();
try {
testRealm.admin().clearAdminEvents();
OIDCClientRepresentation rep = getTestClientRepresentation();
rep.setRoles(Set.of("role-a", "role-b"));

try (var response = getClientApi(TEST_CLIENT_ID).createOrUpdateClient(rep)) {
assertEquals(200, response.getStatus());
}

List<AdminEventRepresentation> events = testRealm.admin().getAdminEvents();
assertThat("Only the client event should be fired, not per-role events", events.size(), is(1));
AdminEventRepresentation event = events.get(0);
assertThat(event.getResourceType(), is(ResourceType.CLIENT.toString()));
assertThat(event.getOperationType(), is(OperationType.UPDATE.toString()));
assertThat(event.getDetails().get(API_VERSION_DETAIL_KEY), is(API_VERSION_V2));

testRealm.admin().clearAdminEvents();
rep.setRoles(Set.of("role-a"));

try (var response = getClientApi(TEST_CLIENT_ID).createOrUpdateClient(rep)) {
assertEquals(200, response.getStatus());
}

events = testRealm.admin().getAdminEvents();
assertThat("Only the client event should be fired when removing a role", events.size(), is(1));
assertThat(events.get(0).getResourceType(), is(ResourceType.CLIENT.toString()));
} finally {
deleteTestClient();
}
}

private void assertUpdateEventFired(String newDescription){
// Verify v2 UPDATE event was fired
List<AdminEventRepresentation> events = testRealm.admin().getAdminEvents();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public ResourceType getResourceType() {
@Override
public void remove(RealmModel realm, KeycloakSession session, RoleRepresentation roleRep) {
RoleModel role = realm.getRole(getName(roleRep));
RoleHelper helper = new RoleHelper(realm);
RoleHelper helper = new RoleHelper();
helper.deleteRole(role);
}

Expand All @@ -91,10 +91,6 @@ public void create(RealmModel realm, KeycloakSession session, RoleRepresentation
}

public static class RoleHelper extends RoleResource {
public RoleHelper(RealmModel realm) {
super(realm);
}

@Override
protected void deleteRole(RoleModel role) {
super.deleteRole(role);
Expand Down
Loading
Loading
0