8000 [CIMD] Realm-level cap on total CIMD-persisted clients by tnorimat · Pull Request #48222 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
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
7 changes: 6 additions & 1 deletion docs/guides/securing-apps/mcp-authz-server.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -254,11 +254,16 @@ NOTE: The specification states that the `client_id` URL SHOULD NOT include a que

===== System-wide settings for the Client ID Metadata Document executor

The `client-id-metadata-document` executor has the following system-wide settings that control caching and metadata size limits. These settings cannot be configured through the Admin Console. Instead, they are configured as SPI options when starting {project_name}.
The `client-id-metadata-document` executor has the following system-wide settings that control caching, metadata size limits, and the number of clients. These settings cannot be configured through the Admin Console. Instead, they are configured as SPI options when starting {project_name}.

* *min-cache-time*: The minimum time (in seconds) that a fetched Client ID Metadata Document is cached. Default: `300` (5 minutes).
* *max-cache-time*: The maximum time (in seconds) that a fetched Client ID Metadata Document is cached. Default: `259200` (3 days).
* *upper-limit-metadata-bytes*: The maximum size (in bytes) of a Client ID Metadata Document that {project_name} accepts. Default: `5000` (5 KB).
* *max-clients*: The maximum number of clients in a realm.
When the number of clients in the realm, including clients that were not created from a Client ID Metadata Document, has reached this value, {project_name} rejects an authorization request whose `client_id` would create a new client.
The limit is checked before a client is created, so concurrent requests can exceed it by the number of clients that are being created at the same time.
`0` means unlimited.
Default: `1000`.

To configure these settings, use the `--spi-client-policy-executor--client-id-metadata-document--<property>=<value>` command-line option when starting {project_name}. For example:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,11 @@ private void process(PreAuthorizationRequestContext preAuthorizationRequestConte
return;
}

if (fetchOp == FetchOperation.CREATE) {
// Check max clients per realm before fetching the client metadata of a client that cannot be created
checkClientsLimit();
}

// fetch Client ID Metadata
OIDCClientRepresentationWithCacheControl clientOIDCWithCacheControl = fetchClientMetadata(clientIdURI, fetchOp == FetchOperation.UPDATE, provider);
if (clientOIDCWithCacheControl == null) {
Expand Down Expand Up @@ -474,6 +479,34 @@ private void process(PreAuthorizationRequestContext preAuthorizationRequestConte
private static final ObjectMapper clientMetadataObjectMapper = JsonSerialization.createObjectMapperWithDefaults()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

// Max Clients per realm
public static final String ERR_CLIENTS_LIMIT_REACHED = "Max clients per realm reached";

/**
* Checks the max clients per realm limit. It is called before the client metadata is fetched, so that no request
* is sent to the client_id URL of a client that cannot be created.
*
* <p>The check is not atomic with the creation, in the same way as the max clients policy of the dynamic client
* registration: it does not see a client that a concurrent request is creating or has created but not committed
* yet. Therefore, concurrent requests can exceed the limit, by at most the number of creations that are in
* progress at the same time. Once the committed number of clients has reached the limit, every further creation
* is rejected.
*
* @throws ClientPolicyException when the limit is reached.
*/
private void checkClientsLimit() throws ClientPolicyException {
int maxClients = providerConfig.getMaxClients();
if (maxClients <= 0) {
// 0 or negative means unlimited
return;
}
long currentCount = session.getContext().getRealm().getClientsCount();
Comment thread
tnorimat marked this conversation as resolved.
Resolved
if (currentCount >= maxClients) {
getLogger().warnv("Max clients per realm reached: max={0}, current={1}", maxClients, currentCount);
throw new ClientPolicyException(OAuthErrorException.INVALID_REQUEST, ERR_CLIENTS_LIMIT_REACHED);
}
}

/**
* Verifies an authorization request to check if the request includes required parameters and follows the expected format.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public abstract class AbstractClientIdMetadataDocumentExecutorFactory
public static final String CONFIG_MIN_CACHE_TIME = "min-cache-time";
public static final String CONFIG_MAX_CACHE_TIME = "max-cache-time";
public static final String CONFIG_UPPER_LIMIT_METADATA_BYTES = "upper-limit-metadata-bytes";
public static final String CONFIG_MAX_CLIENTS = "max-clients";

protected ClientIdMetadataDocumentExecutorFactoryProviderConfig providerConfig;

Expand Down Expand Up @@ -178,6 +179,16 @@ public List<ProviderConfigProperty> getConfigMetadata() {
.defaultValue(ClientIdMetadataDocumentExecutorFactoryProviderConfig.DEFAULT_CONFIG_UPPER_LIMIT_METADATA_BYTES)
.add()

.property()
.name(CONFIG_MAX_CLIENTS)
.type("int")
.helpText("Max number of clients per realm for the CIMD. When the number of existing clients in a realm reaches this limit, " +
"an authorization request with a CIMD client_id that would create a new client is rejected. " +
"The limit is checked before a client is created, so concurrent requests can exceed it by the number of clients that are being created at the same time. " +
"0 means unlimited.")
.defaultValue(ClientIdMetadataDocumentExecutorFactoryProviderConfig.DEFAULT_CONFIG_MAX_CLIENTS)
.add()

.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ public class ClientIdMetadataDocumentExecutorFactoryProviderConfig {
*/
private final long upperLimitMetadataBytes;

/**
* Max Clients per realm
*/
private final int maxClients;

/**
* Default value for {@link #cimdProviderName} :
*/
Expand All @@ -52,13 +57,19 @@ public class ClientIdMetadataDocumentExecutorFactoryProviderConfig {
*/
public static final long DEFAULT_CONFIG_UPPER_LIMIT_METADATA_BYTES = 5000;

/**
* Default value for {@link #maxClients} : 1000
*/
public static final int DEFAULT_CONFIG_MAX_CLIENTS = 1000;


public ClientIdMetadataDocumentExecutorFactoryProviderConfig(Config.Scope config) {
this.config = config;
cimdProviderName = config.get(AbstractClientIdMetadataDocumentExecutorFactory.CONFIG_CIMD_PROVIDER_NAME, DEFAULT_CONFIG_CIMD_PROVIDER_NAME);
minCacheTime = config.getInt(AbstractClientIdMetadataDocumentExecutorFactory.CONFIG_MIN_CACHE_TIME, DEFAULT_CONFIG_MIN_CACHE_TIME);
maxCacheTime = config.getInt(AbstractClientIdMetadataDocumentExecutorFactory.CONFIG_MAX_CACHE_TIME, DEFAULT_CONFIG_MAX_CACHE_TIME);
upperLimitMetadataBytes = config.getLong(AbstractClientIdMetadataDocumentExecutorFactory.CONFIG_UPPER_LIMIT_METADATA_BYTES, DEFAULT_CONFIG_UPPER_LIMIT_METADATA_BYTES);
maxClients = config.getInt(AbstractClientIdMetadataDocumentExecutorFactory.CONFIG_MAX_CLIENTS, DEFAULT_CONFIG_MAX_CLIENTS);
}

public String getCimdProviderName() {
Expand All @@ -76,4 +87,8 @@ public int getMaxCacheTime() {
public long getUpperLimitMetadataBytes() {
return upperLimitMetadataBytes;
}

public int getMaxClients() {
return maxClients;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.keycloak.tests.client.policies;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
Expand All @@ -16,6 +17,7 @@
import org.keycloak.protocol.oauth2.cimd.clientpolicy.condition.ClientIdUriSchemeCondition;
import org.keycloak.protocol.oauth2.cimd.clientpolicy.condition.ClientIdUriSchemeConditionFactory;
import org.keycloak.protocol.oauth2.cimd.clientpolicy.executor.AbstractClientIdMetadataDocumentExecutor;
import org.keycloak.protocol.oauth2.cimd.clientpolicy.executor.AbstractClientIdMetadataDocumentExecutorFactory;
import org.keycloak.protocol.oauth2.cimd.clientpolicy.executor.ClientIdMetadataDocumentExecutor;
import org.keycloak.protocol.oauth2.cimd.clientpolicy.executor.ClientIdMetadataDocumentExecutorFactory;
import org.keycloak.protocol.oauth2.cimd.clientpolicy.executor.ClientIdMetadataDocumentExecutorFactoryProviderConfig;
Expand All @@ -33,6 +35,7 @@
import org.keycloak.representations.idm.ProtocolMapperRepresentation;
import org.keycloak.representations.oidc.OIDCClientRepresentation;
import org.keycloak.services.clientpolicy.condition.AnyClientConditionFactory;
import org.keycloak.services.clientpolicy.executor.ClientPolicyExecutorSpi;
import org.keycloak.services.clientpolicy.executor.PKCEEnforcerExecutor;
import org.keycloak.services.clientpolicy.executor.PKCEEnforcerExecutorFactory;
import org.keycloak.services.clientpolicy.executor.RejectImplicitGrantExecutor;
Expand Down Expand Up @@ -105,6 +108,7 @@ public class ClientIdMetadataDocumentTest {
private static final String LOGO_URI = "http://localhost:8500/logo.png";
private static final String RESOURCE = "https://mcp.example.com/api";
private static final int CIMD_EXECUTOR_MIN_CACHE_TIME_SEC = 300;
private static final int CIMD_MAX_CLIENTS_FOR_TEST = 20;

@InjectRealm
protected ManagedRealm realm;
Expand Down Expand Up @@ -1452,6 +1456,56 @@ public void testWellKnownNoneInTokenEndpointAuthMethods() {
Assertions.assertTrue(oidcConfig.getTokenEndpointAuthMethodsSupported().contains("none"));
}

@Test
public void testClientIdMetadataDocumentExecutorMaxClientsLimitReached() throws Exception {
setupConfigForMaxClientsLimit();

// Create dummy clients to fill the realm up to the max-clients limit (CIMD_MAX_CLIENTS_FOR_TEST)
int currentCount = realm.admin().clients().findAll().size();
int dummyCount = CIMD_MAX_CLIENTS_FOR_TEST - currentCount;
List<String> dummyClientIds = new ArrayList<>();
try {
for (int i = 0; i < dummyCount; i++) {
ClientRepresentation dummy = new ClientRepresentation();
String dummyClientId = "dummy-max-clients-" + i;
dummy.setClientId(dummyClientId);
try (Response response = realm.admin().clients().create(dummy)) {
Assertions.assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
}
dummyClientIds.add(dummyClientId);
}

Assertions.assertTrue(realm.admin().clients().findAll().size() >= CIMD_MAX_CLIENTS_FOR_TEST);

// the limit is checked before the client metadata is fetched, so a fetch that would fail is not attempted
cimd.setStatus(Response.Status.NOT_FOUND);

oauth.client(CLIENT_ID);
oauth.redirectUri(REDIRECT_URI);
oauth.openLoginForm();
errorPage.assertCurrent();
Assertions.assertEquals(AbstractClientIdMetadataDocumentExecutor.ERR_CLIENTS_LIMIT_REACHED, errorPage.getError());
} finally {
// Clean up dummy clients
for (String dummyClientId : dummyClientIds) {
List<ClientRepresentation> found = realm.admin().clients().findByClientId(dummyClientId);
if (!found.isEmpty()) {
realm.admin().clients().get(found.get(0).getId()).remove();
}
}
}
}

private void setupConfigForMaxClientsLimit() {
ClientIdUriSchemeCondition.Configuration conditionConfig = new ClientIdUriSchemeCondition.Configuration();
conditionConfig.setClientIdUriSchemes(List.of("http", "https"));
conditionConfig.setTrustedDomains(List.of("*.example.com", "localhost"));
ClientIdMetadataDocumentExecutor.Configuration executorConfig = newExecutorConfig();
executorConfig.setTrustedDomains(List.of("*.example.com", "localhost"));
executorConfig.setAllowHttpScheme(true);
updatePolicy(conditionConfig, executorConfig);
}

private String loginUserAndGetCode(boolean isGrantRequred) {
return loginUserAndGetCode(isGrantRequred, null);
}
Expand Down Expand Up @@ -1627,7 +1681,11 @@ private void logoutAndDelete(String cid, String idToken) {
public static class CimdServerConfig implements KeycloakServerConfig {
@Override
public KeycloakServerConfigBuilder configure(KeycloakServerConfigBuilder config) {
return config.features(Profile.Feature.CIMD, Profile.Feature.RESOURCE_INDICATORS);
return config.features(Profile.Feature.CIMD, Profile.Feature.RESOURCE_INDICATORS)
.spiOption(ClientPolicyExecutorSpi.SPI_NAME,
ClientIdMetadataDocumentExecutorFactory.PROVIDER_ID,
AbstractClientIdMetadataDocumentExecutorFactory.CONFIG_MAX_CLIENTS,
String.valueOf(CIMD_MAX_CLIENTS_FOR_TEST));
}
}

Expand Down
Loading
0