8000 shows what patching logic should look like by shawkins · Pull Request #40450 · 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package org.keycloak.representations.admin.v2;

import java.util.LinkedHashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_ABSENT)
public class BaseRepresentation {

@JsonIgnore
protected Map<String, Object> additionalFields = new LinkedHashMap<String, Object>();

@JsonAnyGetter
public Map<String, Object> getAdditionalFields() {
return additionalFields;
}

@JsonAnySetter
public void setAdditionalField(String name, Object value) {
this.additionalFields.put(name, value);
}

public void setAdditionalFields(Map<String, Object> additionalFields) {
this.additionalFields = additionalFields;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.LinkedHashSet;
import java.util.Set;

@JsonInclude(JsonInclude.Include.NON_ABSENT)
public class ClientRepresentation {
public class ClientRepresentation extends BaseRepresentation {

public static final String OIDC = "openid-connect";

@JsonProperty(required = true)
@JsonPropertyDescription("ID uniquely identifying this client")
private String clientId;

Expand All @@ -24,7 +24,7 @@ public class ClientRepresentation {

@JsonProperty(defaultValue = OIDC)
@JsonPropertyDescription("The protocol used to communicate with the client")
private String protocol = OIDC;
private String protocol;

@JsonPropertyDescription("Whether this client is enabled")
private Boolean enabled;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package org.keycloak.admin.api;

public enum FieldValidation {
Ignore,
Strict,
Warn
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,32 @@
package org.keycloak.admin.api.client;

import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;

import org.keycloak.admin.api.FieldValidation;
import org.keycloak.representations.admin.v2.ClientRepresentation;

import com.fasterxml.jackson.databind.JsonNode;

public interface ClientApi {

@GET
@Produces(MediaType.APPLICATION_JSON)
ClientRepresentation getClient();

@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
ClientRepresentation createOrUpdateClient(ClientRepresentation client, @PathParam("fieldValidation") FieldValidation fieldValidation);

@PATCH
@Consumes("application/merge-patch+json")
@Produces(MediaType.APPLICATION_JSON)
ClientRepresentation patchClient(JsonNode patch, @PathParam("fieldValidation") FieldValidation fieldValidation);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Field validation might need a better name not to be confused with regular validations (from semantic perspective etc.). Possibly something like unknownFieldsPolicy but not sure.

Also should we really give the power to set this policy to the user? Shouldn't it rather be a global server option? In other words, do we really want to set this per request?

@shawkins shawkins Jun 16, 2025 •
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Field validation might need a better name not to be confused with regular validations (from semantic perspective etc.)

It is possible to tie this to "optional" semantic validation - for example in kubernetes the handling of the StatefulSet serviceName - it is not required unless fieldValidation=Strict.

Possibly something like unknownFieldsPolicy but not sure.

8000

Yes the naming can be whatever we want.

Also should we really give the power to set this policy to the user? Shouldn't it rather be a global server option? In other words, do we really want to set this per request?

You would probably want control per request yes. You can certainly make a case for session or server level control as well.

@vmuzikar vmuzikar Jun 24, 2025 •
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes the naming can be whatever we want.

Thinking about that more, maybe fieldNameValidation would be better? WDYT?

You would probably want control per request yes. You can certainly make a case for session or server level control as well.

Ok. We can add the server level one as a follow-up.


}
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
package org.keycloak.admin.api.client;

import java.util.stream.Stream;

import org.keycloak.admin.api.FieldValidation;
import org.keycloak.provider.Provider;
import org.keycloak.representations.admin.v2.ClientRepresentation;

import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import org.keycloak.provider.Provider;
import org.keycloak.representations.admin.v2.ClientRepresentation;

import java.util.stream.Stream;

public interface ClientsApi extends Provider {

Expand All @@ -20,15 +21,10 @@ public interface ClientsApi extends Provider {
@Consumes(MediaType.APPLICATION_JSON)
Stream<ClientRepresentation> getClients();

@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
ClientRepresentation createOrUpdateClient(ClientRepresentation client);

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
ClientRepresentation createClient(ClientRepresentation client);
ClientRepresentation createClient(ClientRepresentation client, @PathParam("fieldValidation") FieldValidation fieldValidation);

@Path("{id}")
ClientApi client(@PathParam("id") String id);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,33 +1,83 @@
package org.keycloak.admin.api.client;

import jakarta.ws.rs.GET;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import java.io.IOException;

import org.keycloak.admin.api.FieldValidation;
import org.keycloak.http.HttpResponse;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.admin.v2.ClientRepresentation;
import org.keycloak.services.ErrorResponse;
import org.keycloak.services.ServiceException;
import org.keycloak.services.client.ClientService;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;

import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;

public class DefaultClientApi implements ClientApi {
private final KeycloakSession session;
private final RealmModel realm;
private final String clientId;
private final ClientService clientService;
private HttpResponse response;

public DefaultClientApi(KeycloakSession session, String clientId) {
this.session = session;
this.clientId = clientId;
this.realm = session.getContext().getRealm();
this.clientService = session.services().clients();
this.response = session.getContext().getHttpResponse();
}

@GET
@Produces(MediaType.APPLICATION_JSON)
@Override
public ClientRepresentation getClient() {
return clientService.getClient(realm, clientId, null)
.orElseThrow(() -> new NotFoundException("Cannot find the specified client"));
}

@Override
public ClientRepresentation createOrUpdateClient(ClientRepresentation client, FieldValidation fieldValidation) {
try {
var result = clientService.createOrUpdate(realm, client, true);
if (result.created()) {
response.setStatus(Response.Status.CREATED.getStatusCode());
}
return result.representation();
} catch (ServiceException e) {
throw new WebApplicationException(e.getMessage(), e.getSuggestedResponseStatus().orElse(Response.Status.BAD_REQUEST));
}
}

@Override
public ClientRepresentation patchClient(JsonNode patch, FieldValidation fieldValidation) {
// patches don't yet allow for creating
ClientRepresentation client = getClient();
try {
// TODO: there should be a more centralized objectmapper
final ObjectReader objectReader = new ObjectMapper().readerForUpdating(client);
ClientRepresentation updated = objectReader.readValue(patch);

// TODO: reuse in the other methods
if (!updated.getAdditionalFields().isEmpty()) {
if (fieldValidation == null || fieldValidation == FieldValidation.Strict) {
// validation failed
throw new WebApplicationException("Payload contains unknown fields: " + updated.getAdditionalFields().keySet(), Response.Status.BAD_REQUEST);
} else if (fieldValidation == FieldValidation.Warn) {
response.addHeader("WARNING", "Payload contains unknown fields: " + updated.getAdditionalFields().keySet());
}
}
return clientService.createOrUpdate(realm, updated, true).representation();
} catch (JsonProcessingException e) {
// TODO: kubernetes uses 422 instead
throw new WebApplicationException(e.getMessage(), Response.Status.BAD_REQUEST);
} catch (IOException e) {
throw ErrorResponse.error("Unknown Error Occurred", Response.Status.INTERNAL_SERVER_ERROR);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
package org.keycloak.admin.api.client;

import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.stream.Stream;

import org.keycloak.admin.api.FieldValidation;
import org.keycloak.http.HttpResponse;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.admin.v2.ClientRepresentation;
import org.keycloak.services.ServiceException;
import org.keycloak.services.client.ClientService;

import java.util.stream.Stream;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;

public class DefaultClientsApi implements ClientsApi {
private final KeycloakSession session;
Expand All @@ -32,41 +28,22 @@ public DefaultClientsApi(KeycloakSession session, RealmModel realm) {
this.response = session.getContext().getHttpResponse();
}

@GET
@Produces(MediaType.APPLICATION_JSON)
@Override
@GET
public Stream<ClientRepresentation> getClients() {
return clientService.getClients(realm, null, null, null);
}

@Override
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public ClientRepresentation createOrUpdateClient(ClientRepresentation client) {
try {
// TODO return 200, or 201 if did not exist
response.setStatus(Response.Status.OK.getStatusCode());
return clientService.createOrUpdateClient(realm, client);
} catch (ServiceException e) {
throw new WebApplicationException(e.getMessage(), e.getSuggestedResponseStatus().orElse(Response.Status.BAD_REQUEST));
}
}

@Override
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public ClientRepresentation createClient(ClientRepresentation client) {
public ClientRepresentation createClient(ClientRepresentation client, FieldValidation fieldValidation) {
try {
response.setStatus(Response.Status.CREATED.getStatusCode());
return clientService.createClient(realm, client);
return clientService.createOrUpdate(realm, client, false).representation();
} catch (ServiceException e) {
throw new WebApplicationException(e.getMessage(), e.getSuggestedResponseStatus().orElse(Response.Status.BAD_REQUEST));
}
}

@Path("{id}")
@Override
public ClientApi client(@PathParam("id") String clientId) {
return new DefaultClientApi(session, clientId);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package org.keycloak.models.mapper;

import org.keycloak.models.ClientModel;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.admin.v2.ClientRepresentation;

public interface ClientModelMapper {

ClientRepresentation fromModel(ClientModel model);

// ClientModel toModel(ClientModel baseModel, ClientRepresentation representation);
void toModel(ClientModel model, ClientRepresentation rep, RealmModel realm);
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
package org.keycloak.services.client;

import java.util.Optional;
import java.util.stream.Stream;

import org.keycloak.models.RealmModel;
import org.keycloak.representations.admin.v2.ClientRepresentation;
import org.keycloak.services.Service;
import org.keycloak.services.ServiceException;

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

import java.util.Optional;
import java.util.stream.Stream;

public interface ClientService extends Service {

public static class ClientSearchOptions {
Expand All @@ -27,6 +25,8 @@ public static class ClientSortAndSliceOptions {
// NOTE: this is not always the most desirable way to do pagination
}

public record CreateOrUpdateResult(ClientRepresentation representation, boolean created) {}

Optional<ClientRepresentation> getClient(RealmModel realm, String clientId, ClientProjectionOptions projectionOptions);

Stream<ClientRepresentation> getClients(RealmModel realm, ClientProjectionOptions projectionOptions, ClientSearchOptions searchOptions, ClientSortAndSliceOptions sortAndSliceOptions);
Expand All @@ -35,21 +35,6 @@ public static class ClientSortAndSliceOptions {

Stream<ClientRepresentation> deleteClients(RealmModel realm, ClientSearchOptions searchOptions);

default ClientRepresentation createOrUpdateClient(RealmModel realm, ClientRepresentation client) throws ServiceException {
// If we can paramertize the services, it makes sense to define default handling like this
// but this duplicate the existence check
try {
return createClient(realm, client);
} catch (ServiceException e) {
if (!e.getSuggestedResponseStatus().filter(Status.CONFLICT::equals).isPresent()) {
throw e;
}
}
return updateClient(realm, client);
}

ClientRepresentation updateClient(RealmModel realm, ClientRepresentation client) throws ServiceException;

ClientRepresentation createClient(RealmModel realm, ClientRepresentation client) throws ServiceException;
CreateOrUpdateResult createOrUpdate(RealmModel realm, ClientRepresentation client, boolean allowUpdate) throws ServiceException;

}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ public interface MapStructClientModelMapper extends ClientModelMapper {
@Override
ClientRepresentation fromModel(ClientModel model);

@BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
// we don't want to ignore nulls so that we completely overwrite the state
@Override
void toModel(@MappingTarget ClientModel model, ClientRepresentation rep, @Context RealmModel realm);

@Named("getRoleStrings")
Expand Down
Loading
0