8000 Check ownership of every resource of a user-managed permission by sguilhen · Pull Request #55537 · 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 @@ -17,6 +17,7 @@
package org.keycloak.authorization.protection.policy;

import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -45,6 +46,7 @@
import org.keycloak.authorization.store.ResourceStore;
import org.keycloak.events.admin.OperationType;
import org.keycloak.events.admin.ResourceType;
import org.keycloak.representations.idm.authorization.AbstractPolicyRepresentation;
import org.keycloak.representations.idm.authorization.UmaPermissionRepresentation;
import org.keycloak.services.ErrorResponseException;
import org.keycloak.services.resources.admin.AdminEventBuilder;
Expand Down Expand Up @@ -110,7 +112,11 @@ public Response update(@PathParam("policyId") String policyId, String payload) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Failed to parse representation", Status.BAD_REQUEST);
}

String resourceId = getAssociatedResourceId(policyId);
Policy policy = getPolicy(policyId);

checkOwnsAllResources(policy);

String resourceId = getAssociatedResourceId(policy);
Set<String> resources = Optional.ofNullable(representation.getResources()).orElse(Set.of());

if (resources.isEmpty() || (resources.size() == 1 && resources.contains(resourceId))) {
Expand All @@ -125,7 +131,7 @@ public Response update(@PathParam("policyId") String policyId, String payload) {
@Path("{policyId}")
@DELETE
public Response delete(@PathParam("policyId") String policyId) {
checkRequest(getAssociatedResourceId(policyId), null);
checkOwnsAllResources(getPolicy(policyId));
PolicyTypeResourceService.class.cast(delegate.getResource(policyId)).delete();
return Response.noContent().build();
}
Expand All @@ -134,7 +140,7 @@ public Response delete(@PathParam("policyId") String policyId) {
@GET
@Produces("application/json")
public Response findById(@PathParam("policyId") String policyId) {
checkRequest(getAssociatedResourceId(policyId), null);
checkOwnsAllResources(getPolicy(policyId));
Comment thread
sguilhen marked this conversation as resolved.
Resolved
return PolicyTypeResourceService.class.cast(delegate.getResource(policyId)).findById(null);
}

Expand All @@ -146,7 +152,28 @@ public Response find(@QueryParam("name") String name,
@QueryParam("scope") String scope,
@QueryParam("first") Integer firstResult,
@QueryParam("max") Integer maxResult) {
return delegate.findAll(null, name, "uma", null, resource, scope, true, identity.getId(), null, firstResult, maxResult);
Response response = delegate.findAll(null, name, "uma", null, resource, scope, true, identity.getId(), null, firstResult, maxResult);

if (response.getStatus() != Status.OK.getStatusCode()) {
return response;
}

// the owner filter above matches the policy's own owner field, which does not guarantee the caller
// owns every resource the policy governs if it was wired up to span multiple resources directly
// through the authorization model
List<?> policies = (List<?>) response.getEntity();
List<?> owned = policies.stream().filter(this::ownsAllResources).collect(Collectors.toList());

return Response.ok(owned).build();
}

private boolean ownsAllResources(Object representation) {
try {
checkOwnsAllResources(getPolicy(((AbstractPolicyRepresentation) representation).getId()));
return true;
} catch (ErrorResponseException e) {
return false;
}
}

private Policy getPolicy(@PathParam("policyId") String policyId) {
Expand Down Expand Up @@ -204,7 +231,21 @@ private void checkRequest(String resourceId, UmaPermissionRepresentation represe
}
}

private String getAssociatedResourceId(String policyId) {
return getPolicy(policyId).getResources().iterator().next().getId();
private String getAssociatedResourceId(Policy policy) {
return policy.getResources().iterator().next().getId();
}

private void checkOwnsAllResources(Policy policy) {
Set<Resource> resources = policy.getResources();

// a policy not associated with any resource, like an admin-managed policy or one bound to a resource
// type, has no owner to check the caller against and is not managed through this endpoint
if (resources.isEmpty()) {
throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Policy with [" + policy.getId() + "] is not associated with any resource", Status.BAD_REQUEST);
}

for (Resource resource : resources) {
checkRequest(resource.getId(), null);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,22 @@

import jakarta.ws.rs.core.Response.Status;

import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.client.AuthzClient;
import org.keycloak.authorization.client.Configuration;
import org.keycloak.authorization.client.resource.ProtectionResource;
import org.keycloak.authorization.client.util.HttpResponseException;
import org.keycloak.authorization.model.Policy;
import org.keycloak.authorization.model.ResourceServer;
import org.keycloak.authorization.store.ResourceStore;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.authorization.ResourceRepresentation;
import org.keycloak.representations.idm.authorization.ResourceServerRepresentation;
import org.keycloak.representations.idm.authorization.UmaPermissionRepresentation;
import org.keycloak.testframework.annotations.InjectClient;
import org.keycloak.testframework.annotations.InjectHttpClient;
import org.keycloak.testframework.annotations.InjectKeycloakUrls;
Expand All @@ -26,15 +35,19 @@
import org.keycloak.testframework.realm.RealmBuilder;
import org.keycloak.testframework.realm.RealmConfig;
import org.keycloak.testframework.realm.UserBuilder;
import org.keycloak.testframework.remote.runonserver.InjectRunOnServer;
import org.keycloak.testframework.remote.runonserver.RunOnServerClient;
import org.keycloak.testframework.server.KeycloakUrls;

import org.apache.http.client.HttpClient;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

@KeycloakIntegrationTest
public class ProtectionApiTest {
Expand All @@ -53,6 +66,9 @@ public class ProtectionApiTest {
@InjectHttpClient
HttpClient httpClient;

@InjectRunOnServer(permittedPackages = "org.keycloak.tests")
RunOnServerClient runOnServer;

private AuthzClient authzClient;

@BeforeEach
Expand Down Expand Up @@ -89,6 +105,177 @@ public void testRejectsClientSuppliedIdWithoutChangingExistingResource() {
assertNotNull(created.getId());
}

// CVE-2025-14778 guarded update() against resources owned by other users, but delete() and findById()
// still resolved ownership from an arbitrary resource of the policy (Policy.getResources() is backed by
// a HashSet, so which resource is "first" depends on resource id hashing), and update() still fell back
// to that resource when a request omits the resources field. A policy spanning resources of different
// owners is only reachable by an administrator wiring it up directly, as simulated here. Because the old
// code only ever inspected one arbitrary resource, a single trial has roughly even odds of coincidentally
// rejecting the request even without the fix; repeating with fresh resources drives that down to
// virtually zero, so this reliably fails without the fix instead of passing by chance.
private static final int OWNERSHIP_CHECK_TRIALS = 15;

@Test
public void testDeleteAndFindByIdRejectPolicyWithResourcesFromDifferentOwners() {
for (int i = 0; i < OWNERSHIP_CHECK_TRIALS; i++) {
ResourceRepresentation aliceResource = authzClient.protection("alice", "password").resource()
.create(ownerManagedResource("alice-resource-" + i));
ResourceRepresentation martaResource = authzClient.protection("marta", "password").resource()
.create(ownerManagedResource("marta-resource-" + i));

String policyId = createMultiOwnerPolicy(aliceResource.getId(), martaResource.getId(), "alice");

assertThrows(RuntimeException.class,
() -> authzClient.protection("alice", "password").policy(aliceResource.getId()).delete(policyId));
assertThrows(RuntimeException.class,
() -> authzClient.protection("alice", "password").policy(aliceResource.getId()).findById(policyId));

// untouched by the rejected delete attempt; checked through the admin API, since the self-service
// endpoint rejects reads of this policy for either owner
assertNotNull(resourceServer.admin().authorization().policies().policy(policyId).toRepresentation());
}
}

@Test
public void testUpdateRejectsPolicyWithResourcesFromDifferentOwnersWhenResourcesFieldIsOmitted() {
for (int i = 0; i < OWNERSHIP_CHECK_TRIALS; i++) {
ResourceRepresentation aliceResource = authzClient.protection("alice", "password").resource()
.create(ownerManagedResource("alice-resource-" + i));
ResourceRepresentation martaResource = authzClient.protection("marta", "password").resource()
.create(ownerManagedResource("marta-resource-" + i));

String policyId = createMultiOwnerPolicy(aliceResource.getId(), martaResource.getId(), "alice");

UmaPermissionRepresentation permission = new UmaPermissionRepresentation();
permission.setId(policyId);

// the client omits the resources field entirely, which must not bypass the ownership check
// against a resource it did not explicitly submit
assertThrows(RuntimeException.class,
() -> authzClient.protection("alice", "password").policy(aliceResource.getId()).update(permission));
}
}

@Test
public void testDeleteAndFindByIdAllowSingleOwnerMultiResourcePolicy() {
ResourceRepresentation resourceA = authzClient.protection("alice", "password").resource()
.create(ownerManagedResource("alice-resource-a"));
ResourceRepresentation resourceB = authzClient.protection("alice", "password").resource()
.create(ownerManagedResource("alice-resource-b"));

String policyId = createMultiOwnerPolicy(resourceA.getId(), resourceB.getId(), "alice");

assertNotNull(authzClient.protection("alice", "password").policy(resourceA.getId()).findById(policyId));

authzClient.protection("alice", "password").policy(resourceA.getId()).delete(policyId);

RuntimeException exception = assertThrows(RuntimeException.class,
() -> authzClient.protection("alice", "password").policy(resourceA.getId()).findById(policyId));
assertEquals(404, ((HttpResponseException) exception.getCause()).getStatusCode());
}

// the collection endpoint filters by the policy's own owner field, which a policy spanning resources of
// different owners can still carry even though the caller does not own every resource it governs
@Test
public void testFindExcludesPolicyWithResourcesFromDifferentOwners() {
ResourceRepresentation aliceOwnResource = authzClient.protection("alice", "password").resource()
.create(ownerManagedResource("alice-own-resource"));
UmaPermissionRepresentation ownPermission = new UmaPermissionRepresentation();
ownPermission.setName("alice-own-permission");
ownPermission.addUser("marta");
authzClient.protection("alice", "password").policy(aliceOwnResource.getId()).create(ownPermission);

ResourceRepresentation aliceResource = authzClient.protection("alice", "password").resource()
.create(ownerManagedResource("alice-shared-resource"));
ResourceRepresentation martaResource = authzClient.protection("marta", "password").resource()
.create(ownerManagedResource("marta-shared-resource"));
String mixedOwnerPolicyId = createMultiOwnerPolicy(aliceResource.getId(), martaResource.getId(), "alice");

// PolicyResource.find() scopes the query to the resource passed to policy(...), so each call below
// must be scoped to a resource the policy in question actually governs
List<UmaPermissionRepresentation> ownResourcePolicies = authzClient.protection("alice", "password")
.policy(aliceOwnResource.getId()).find(null, null, null, null);
assertTrue(ownResourcePolicies.stream().anyMatch(p -> "alice-own-permission".equals(p.getName())));

List<UmaPermissionRepresentation> mixedResourcePolicies = authzClient.protection("alice", "password")
.policy(aliceResource.getId()).find(null, null, null, null);
assertFalse(mixedResourcePolicies.stream().anyMatch(p -> mixedOwnerPolicyId.equals(p.getId())));
}

// a policy associated with no resource at all (an admin-managed policy, or one bound to a resource
// type) has no resource owner to check the caller against, so it must be rejected rather than accepted
@Test
public void testDeleteAndFindByIdRejectPolicyWithoutResources() {
String policyId = KeycloakModelUtils.generateId();
String realmName = realm.getName();

runOnServer.run(session -> createPolicyWithoutResources(session, realmName, policyId));

for (String user : List.of("alice", "marta")) {
assertThrows(RuntimeException.class, () -> authzClient.protection(user, "password").policy(policyId).delete(policyId));
assertThrows(RuntimeException.class, () -> authzClient.protection(user, "password").policy(policyId).findById(policyId));
}

assertNotNull(resourceServer.admin().authorization().policies().policy(policyId).toRepresentation());
}

private ResourceRepresentation ownerManagedResource(String name) {
ResourceRepresentation resource = new ResourceRepresentation(name, Set.of());
resource.setOwnerManagedAccess(true);
return resource;
}

/**
* Creates a uma policy associated with two resources without going through the self-service create/update
* flow, which never allows a single policy to span resources owned by different users. This simulates a
* policy wired up directly through the authorization model, e.g. by an administrator.
*/
private String createMultiOwnerPolicy(String resourceAId, String resourceBId, String policyOwner) {
String policyId = KeycloakModelUtils.generateId();
String realmName = realm.getName();

runOnServer.run(session -> createMultiOwnerPolicy(session, realmName, resourceAId, resourceBId, policyOwner, policyId));

return policyId;
}

private static void createMultiOwnerPolicy(KeycloakSession session, String realmName, String resourceAId, String resourceBId, String policyOwner, String policyId) {
AuthorizationProvider provider = getAuthorizationProvider(session, realmName);
ResourceServer resourceServer = provider.getStoreFactory().getResourceServerStore().findByClient(getResourceServerClient(session));
ResourceStore resourceStore = provider.getStoreFactory().getResourceStore();

Policy policy = provider.getStoreFactory().getPolicyStore().create(resourceServer, umaPolicyRepresentation(policyId));
policy.setOwner(session.users().getUserByUsername(session.getContext().getRealm(), policyOwner).getId());
policy.addResource(resourceStore.findById(resourceServer, resourceAId));
policy.addResource(resourceStore.findById(resourceServer, resourceBId));
}

private static void createPolicyWithoutResources(KeycloakSession session, String realmName, String policyId) {
AuthorizationProvider provider = getAuthorizationProvider(session, realmName);

Policy policy = provider.getStoreFactory().getPolicyStore().create(
provider.getStoreFactory().getResourceServerStore().findByClient(getResourceServerClient(session)),
umaPolicyRepresentation(policyId));
policy.setOwner(session.users().getUserByUsername(session.getContext().getRealm(), "alice").getId());
}

private static AuthorizationProvider getAuthorizationProvider(KeycloakSession session, String realmName) {
RealmModel realm = session.realms().getRealmByName(realmName);
session.getContext().setRealm(realm);
return session.getProvider(AuthorizationProvider.class);
}

private static ClientModel getResourceServerClient(KeycloakSession session) {
return session.getContext().getRealm().getClientByClientId(RESOURCE_SERVER_ID);
}

private static UmaPermissionRepresentation umaPolicyRepresentation(String policyId) {
UmaPermissionRepresentation representation = new UmaPermissionRepresentation();
representation.setId(policyId);
representation.setName(policyId);
return representation;
}

public static class TestRealmConfig implements RealmConfig {

@Override
Expand Down
Loading
0