Repository navigation
Add client type support to Admin API v2 - #50895
arnabnandy7 wants to merge 15 commits into
Conversation
Apply configured client types during v2 client creation while preserving omitted type-controlled values and explicit update semantics. Closes keycloak#50894 Signed-off-by: Arnab Nandy <arnab_nandy7@yahoo.com>
There was a problem hiding this comment.
Pull request overview
Adds client-type support to Admin API v2 client creation and updates.
Changes:
- Exposes client
typethrough representations and OpenAPI. - Applies client-type defaults while preserving omitted fields.
- Adds typed-client creation and merge-patch tests.
Reviewed changes
Copilot reviewed 10 out of 10 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
InteropTest.java |
Adds typed-client regression tests. |
DefaultClientService.java |
Integrates client-type handling. |
OIDCClientModelMapper.java |
Refactors authentication mapping. |
ClientModelMapper.java |
Adds field-exclusion mapping. |
BaseClientModelMapper.java |
Implements excluded-field support. |
SAMLClientRepresentation.java |
Tracks explicit logout updates. |
OIDCClientRepresentation.java |
Tracks explicit OIDC fields. |
BaseRepresentation.java |
Records explicitly set fields. |
BaseClientRepresentation.java |
Adds the client type property. |
openapi.json |
Documents the client type schema. |
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Signed-off-by: Arnab Nandy <arnab_nandy7@yahoo.com>
Signed-off-by: Arnab Nandy <arnab_nandy7@yahoo.com>
51c824e to
b3f3ea1
Compare
Signed-off-by: Arnab Nandy <arnab_nandy7@yahoo.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Signed-off-by: Arnab Nandy <arnab_nandy7@yahoo.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Signed-off-by: Arnab Nandy <arnab_nandy7@yahoo.com>
Signed-off-by: Arnab Nandy <arnab_nandy7@yahoo.com>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 15 out of 15 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (1)
rest/admin-v2/tests/src/test/java/org/keycloak/tests/admin/client/v2/InteropTest.java:398
- This regression only patches fields that are mutable in the
oidctype, so it does not exercise the new client-type rejection path or parameterized error response. Add a typed service-account patch that explicitly removesSERVICE_ACCOUNT(or changes another fixed field) and assert the 400 response includes the controlled option inparams.
getClientsApi().client(client.getClientId()).patchClient(
new ByteArrayInputStream(mapper.writeValueAsBytes(patch)));
Unreported flaky test detectedIf the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR. org.keycloak.testsuite.forms.MultipleTabsLoginTest#multipleTabsParallelLoginTestWithAuthSessionExpiredAndRequiredActionKeycloak CI - Forms IT (chrome) |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 13 out of 13 changed files in this pull request and generated no new comments.
Suppressed comments (1)
rest/admin-v2/services/src/main/java/org/keycloak/services/client/DefaultClientService.java:106
- This preservation list omits the other SAML fields that client types can control. For example, an omitted
signDocumentsis mapped toremoveAttribute("saml.server.signature"); if a custom SAML type fixes that option, the type-aware delegate rejects the null update, so even a minimal typed SAML creation fails. Add the SAML representation-to-option mappings and explicit-field tracking so omitted controlled SAML values are excluded while explicit updates still reach validation.
private static final List<TypeControlledField> TYPE_CONTROLLED_FIELDS = List.of(
new TypeControlledField("redirectUris", "redirectUris", Set.class),
new TypeControlledField("webOrigins", "webOrigins", Set.class),
new TypeControlledField("auth", "publicClient", Boolean.class),
FRONT_CHANNEL_LOGOUT_FIELD);
9e7f63a to
ddcbb7c
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 13 out of 13 changed files in this pull request and generated no new comments.
Suppressed comments (4)
rest/admin-v2/api/src/main/java/org/keycloak/representations/admin/v2/BaseClientRepresentation.java:174
setRolesnow defensively copies, but it doesn’t callmarkFieldAsExplicitlySet("roles"). With the newly introduced explicit-field tracking, roles updates via JSON patch/merge-patch (or any caller using this setter) won’t be recognized as explicitly provided, which can lead to inconsistent update behavior compared toredirectUris,displayName, etc. AddmarkFieldAsExplicitlySet("roles")in this setter for consistent semantics.
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles) {
this.roles = roles == null ? new LinkedHashSet<>() : new LinkedHashSet<>(roles);
}
rest/admin-v2/api/src/main/java/org/keycloak/representations/admin/v2/OIDCClientRepresentation.java:100
setServiceAccountRolesdefensively copies but doesn’t mark the field as explicitly set. Given the new “explicitly set” mechanism and its use in service logic, this is likely an omission and can cause service-account role changes to be treated as “not provided by the client.” CallmarkFieldAsExplicitlySet("serviceAccountRoles")here (and keep the defensive copy).
public void setServiceAccountRoles(Set<String> serviceAccountRoles) {
this.serviceAccountRoles = serviceAccountRoles == null ? new LinkedHashSet<>() : new LinkedHashSet<>(serviceAccountRoles);
}
rest/admin-v2/services/src/main/java/org/keycloak/services/client/scim/BaseClientModelSchema.java:234
- Clearing explicit-set state is done only in the
fromModel(ClientModel, List<String>)overload. If otherfromModel(...)overloads (e.g., those usingincludeFields) also populate via setters that mark fields explicitly set, they may now return representations with differentisFieldExplicitlySet(...)behavior depending on the overload used. Consider centralizingrep.clearExplicitlySetFields()in a shared private helper (or applying it consistently across allfromModeloverloads) to guarantee uniform model→representation behavior.
public R fromModel(ClientModel model, List<String> attributes) {
R rep = createRepresentation();
populate(rep, model, attributes, null);
rep.clearExplicitlySetFields();
return rep;
}
rest/admin-v2/services/src/main/java/org/keycloak/services/ServiceExceptionMapper.java:34
- This replaces the entity returned by
KeycloakErrorHandlerwhenever parameters are present, which can drop existing error payload fields (e.g., any structured fields the handler already set). To avoid changing the response shape unexpectedly, consider: (1) if the existing entity is already anErrorRepresentation, enrich it by setting params; otherwise (2) preserve the original entity and only add params via a wrapper field/structure that maintains backward-compatible fields.
Response response = KeycloakErrorHandler.getResponse(session, exception.toWebApplicationException());
Optional<Object[]> parameters = exception.getParameters();
if (exception.getMessage() != null && parameters.isPresent()
&& response.getMediaType() != null && MediaType.APPLICATION_JSON_TYPE.isCompatible(response.getMediaType())) {
ErrorRepresentation error = new ErrorRepresentation();
error.setErrorMessage(exception.getMessage());
error.setParams(parameters.get());
return Response.fromResponse(response).entity(error).build();
}
return response;
There was a problem hiding this comment.
Pull request overview
Cop 8 ilot rev 10BC8 iewed 13 out of 13 changed files in this pull request and generated no new comments.
Suppressed comments (4)
rest/admin-v2/api/src/main/java/org/keycloak/representations/admin/v2/BaseClientRepresentation.java:174
setRolesnow defensively copies the incoming set but does not callmarkFieldAsExplicitlySet("roles"). With explicit-field tracking introduced in this PR,isFieldExplicitlySet("roles")will remain false even when roles were provided (including via merge-patch), which can lead to incorrect “field came from patch” detection. AddmarkFieldAsExplicitlySet("roles")(or document why roles should be excluded from tracking if that’s intentional).
public void setRoles(Set<String> roles) {
this.roles = roles == null ? new LinkedHashSet<>() : new LinkedHashSet<>(roles);
}
rest/admin-v2/api/src/main/java/org/keycloak/representations/admin/v2/OIDCClientRepresentation.java:100
setServiceAccountRolesdefensively copies the incoming set but does not mark the field as explicitly set. This makesisFieldExplicitlySet("serviceAccountRoles")inaccurate when the field is provided by clients (including merge-patch). Consider addingmarkFieldAsExplicitlySet("serviceAccountRoles")for consistency with other setters introduced/updated in this PR.
public void setServiceAccountRoles(Set<String> serviceAccountRoles) {
this.serviceAccountRoles = serviceAccountRoles == null ? new LinkedHashSet<>() : new LinkedHashSet<>(serviceAccountRoles);
}
rest/admin-v2/services/src/main/java/org/keycloak/services/ServiceExceptionMapper.java:37
- This replaces whatever JSON entity
KeycloakErrorHandlerproduced with a newErrorRepresentationcontaining onlyerrorMessageandparams, potentially dropping other error fields (e.g., error codes/details) that clients may rely on. A safer approach is to preserve/augment the existing entity when it is already anErrorRepresentation(or a known error payload type), and only fall back to creating a fresh entity when there isn’t one to enrich.
Response response = KeycloakErrorHandler.getResponse(session, exception.toWebApplicationException());
Optional<Object[]> parameters = exception.getParameters();
if (exception.getMessage() != null && parameters.isPresent()
&& response.getMediaType() != null && MediaType.APPLICATION_JSON_TYPE.isCompatible(response.getMediaType())) {
ErrorRepresentation error = new ErrorRepresentation();
error.setErrorMessage(exception.getMessage());
error.setParams(parameters.get());
return Response.fromResponse(response).entity(error).build();
}
return response;
rest/admin-v2/tests/src/test/java/org/keycloak/tests/admin/client/v2/RepresentationDefensiveCopyTest.java:24
- Prefer
assertFalse(...)/assertTrue(...)overassertEquals(false/true, ...)for clearer intent and better failure messages in JUnit 5.
assertEquals(false, representation.isFieldExplicitlySet("type"));
assertEquals(true, representation.isFieldExplicitlySet("description"));
ddcbb7c to
08ec6ff
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 13 out of 13 changed files in this pull request and generated 1 comment.
Suppressed comments (2)
rest/admin-v2/services/src/main/java/org/keycloak/services/client/scim/BaseClientModelSchema.java:234
rep.clearExplicitlySetFields()is applied in thefromModel(ClientModel, List<String>)overload, but the file also contains afromModel(ClientModel, Set<String>)overload (line 227) where the same clearing step may be missing. Since setters now mark fields as explicitly set, returning model-derived representations with populatedexplicitlySetFieldscan cause inconsistent behavior depending on which overload is used. Consider clearingexplicitlySetFieldsin all model->representationfromModel(...)overloads afterpopulate(...).
public R fromModel(ClientModel model, List<String> attributes) {
R rep = createRepresentation();
populate(rep, model, attributes, null);
rep.clearExplicitlySetFields();
return rep;
}
rest/admin-v2/services/src/main/java/org/keycloak/services/ServiceExceptionMapper.java:65
parametersis anObject[]and is stored directly into the response entity/map. Since arrays are mutable, this can lead to accidental mutation after enrichment (even ifServiceExceptiondefensively copies on construction). To keep responses stable and consistent with the defensive-copy intent, clone the array (or convert to an immutableList) before setting it onErrorRepresentation/ putting it into the map.
static Object addParameters(Object entity, String message, Object[] parameters) {
if (entity instanceof ErrorRepresentation error) {
if (error.getErrorMessage() == null) {
error.setErrorMessage(message);
}
error.setParams(parameters);
return error;
}
if (entity instanceof OAuth2ErrorRepresentation error) {
Map<String, Object> enriched = new LinkedHashMap<>();
enriched.put("error", error.getError());
if (error.getErrorDescription() != null) {
enriched.put("error_description", error.getErrorDescription());
}
enriched.put("errorMessage", message);
enriched.put("params", parameters);
return enriched;
}
ErrorRepresentation error = new ErrorRepresentation();
error.setErrorMessage(message);
error.setParams(parameters);
return error;
}
…ure/v2-client-types Signed-off-by: Arnab Nandy <arnab_nandy7@yahoo.com>
08ec6ff to
887e2f1
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 13 out of 13 changed files in this pull request and generated no new comments.
Suppressed comments (5)
rest/admin-v2/services/src/main/java/org/keycloak/services/ServiceExceptionMapper.java:60
- This converts
OAuth2ErrorRepresentationinto aMapbut only carries overerroranderror_description, dropping any other OAuth2 fields that may be present (e.g.,error_uriif supported by the representation). To avoid losing data, preserve all supported OAuth2 error fields when enriching (either by copying every relevant field into the map, or by enriching without changing the entity shape).
if (entity instanceof OAuth2ErrorRepresentation error) {
Map<String, Object> enriched = new LinkedHashMap<>();
enriched.put("error", error.getError());
if (error.getErrorDescription() != null) {
enriched.put("error_description", error.getErrorDescription());
}
enriched.put("errorMessage", message);
enriched.put("params", stableParameters);
return enriched;
}
rest/admin-v2/api/src/main/java/org/keycloak/representations/admin/v2/OIDCClientRepresentation.java:75
- This setter changes the semantic meaning of an explicit JSON
null(or programmaticsetLoginFlows(null)) to an empty set. For merge-patch,nulltypically means 'remove/unset', which is distinct from 'set to empty'. Consider preservingnullinternally (while still defensively copying when non-null) and letting higher-level patch handling decide hownullshould map to model behavior.
public void setLoginFlows(Set<Flow> loginFlows) {
markFieldAsExplicitlySet("loginFlows");
this.loginFlows = loginFlows == null ? new LinkedHashSet<>() : new LinkedHashSet<>(loginFlows);
}
rest/admin-v2/api/src/main/java/org/keycloak/representations/admin/v2/BaseClientRepresentation.java:168
- Same as with
loginFlows: convertingnullto an empty set makes it impossible to represent an explicitnullvalue in input payloads and conflates 'unset' with 'empty'. If the API relies on explicit-field tracking + merge-patch semantics, it’s safer to keepnullasnull(and only defensively copy when non-null) so server-side logic can distinguish omitted vs explicit-null vs explicit-empty.
public void setRedirectUris(Set<String> redirectUris) {
markFieldAsExplicitlySet("redirectUris");
this.redirectUris = redirectUris == null ? new LinkedHashSet<>() : new LinkedHashSet<>(redirectUris);
}
rest/admin-v2/api/src/main/java/org/keycloak/representations/admin/v2/BaseClientRepresentation.java:177
- Same as with
loginFlows: convertingnullto an empty set makes it impossible to represent an explicitnullvalue in input payloads and conflates 'unset' with 'empty'. If the API relies on explicit-field tracking + merge-patch semantics, it’s safer to keepnullasnull(and only defensively copy when non-null) so server-side logic can distinguish omitted vs explicit-null vs explicit-empty.
public void setRoles(Set<String> roles) {
markFieldAsExplicitlySet("roles");
this.roles = roles == null ? new LinkedHashSet<>() : new LinkedHashSet<>(roles);
}
rest/admin-v2/services/src/main/java/org/keycloak/services/client/DefaultClientService.java:104
- For
redirectUris/webOrigins, usingSet.classas theoptionTyperisksclientType.getTypeValue(...)returningnullpurely due to a type mismatch (if the underlying stored value is e.g. aList<String>), which would incorrectly treat those fields as not type-controlled. AlignoptionTypewith the actual stored option value type used byClientType(or use a more tolerant approach for collection types) to ensure the omit/override logic behaves deterministically.
private static final List<TypeControlledField> TYPE_CONTROLLED_FIELDS = List.of(
new TypeControlledField("redirectUris", "redirectUris", Set.class),
new TypeControlledField("webOrigins", "webOrigins", Set.class),
new TypeControlledField("auth", "publicClient", Boolean.class),
|
Thank you for the PR @arnabnandy7, but I'm closing this until we fully triage the issue. |
@shawkins once you do please let me know or reopen with design so that I can refactor. |
Closes #50894
This adds client-type support when creating and updating clients through Admin API v2.
The v2 client creation flow now:
typein the v2 representation and generated OpenAPI schemaRegression coverage includes creating a minimal service-account client and clearing mutable typed-client properties through a merge patch.
The protocol-default changes remain in #50801 and are intentionally excluded from this PR.