8000 [Quarkus 4] Adapt Keycloak JSON handling to Jackson 3 by Pepo48 · Pull Request #54612 · 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
1 change: 1 addition & 0 deletions .github/actions/conditional/conditions
8000
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ js/libs/ui-shared/ ci ci-webauthn
*.tsx codeql-typescript

rest/admin-v2/ admin-v2 ci-jackson3
core-jackson3/ ci-jackson3 ci-quarkus
integration/admin-client-jackson3/ ci-jackson3
integration/admin-client-core/ ci-jackson3
integration/admin-client/ ci-jackson3
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;

public final class AuthZen {

Expand Down Expand Up @@ -108,8 +106,7 @@ public enum EvaluationsSemantic {
}

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public record Options(EvaluationsSemantic evaluationsSemantic) {}
public record Options(@JsonProperty("evaluations_semantic") EvaluationsSemantic evaluationsSemantic) {}

@JsonInclude(JsonInclude.Include.NON_NULL)
public record EvaluationsRequest(
Expand Down
15 changes: 15 additions & 0 deletions core-jackson3/README.md
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.

It might be worth double checking if we need this compatibility layer, if we can't just migrate to Jackson 3.

Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Jackson 3 representation adapters

This module provides Jackson 3 serializers and deserializers for Keycloak's shared representation annotations.
The adapters are used by the server and the Jackson 3 admin client.

The module requires Java 17. Mapper configuration and provider registration are handled by the consuming modules.

## Synchronizing public client sources

The public Java clients are maintained in [keycloak/keycloak-client](https://github.com/keycloak/keycloak-client).
When synchronizing the Jackson 3 admin client, include `org/keycloak/json/jackson3/**/*.java` from the
`keycloak-core-jackson3` sources JAR alongside the admin-client sources. Source JARs are generated with the
`jboss-release` Maven profile.

The adapters are compiled as part of the Java 17 client. The shared `core` and `common` sources retain their Java 8 baseline.
72 changes: 72 additions & 0 deletions core-jackson3/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-parent</artifactId>
<version>999.0.0-SNAPSHOT</version>
</parent>

<artifactId>keycloak-core-jackson3</artifactId>
<name>Keycloak 10000 Core Jackson 3 Adapters</name>
<description>Jackson 3 adapters for shared Keycloak representation annotations, without mapper policy or provider registration.</description>

<properties>
<maven.compiler.release>17</maven.compiler.release>
</properties>

<dependencies>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-core</artifactId>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-common</artifactId>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<!-- Reference mapper for wire-contract parity tests only. -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.keycloak.admin.client.jackson3;
package org.keycloak.json.jackson3;

import java.io.Serial;

Expand All @@ -17,7 +17,7 @@
* Jackson 3 cannot expand the inner {@code @JsonDeserialize} (wrong package),
* so this introspector maps them to the Jackson 3 equivalents directly.
*/
class KeycloakAnnotationIntrospector3 extends JacksonAnnotationIntrospector {
public class KeycloakAnnotationIntrospector3 extends JacksonAnnotationIntrospector {

@Serial
private static final long serialVersionUID = 1L;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.keycloak.admin.client.jackson3;
package org.keycloak.json.jackson3;

import java.util.Map.Entry;

Expand All @@ -9,7 +9,7 @@
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ValueDeserializer;

class MultivaluedHashMapValueDeserializer3 extends ValueDeserializer<Object> {
public class MultivaluedHashMapValueDeserializer3 extends ValueDeserializer<Object> {

@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.keycloak.admin.client.jackson3;
package org.keycloak.json.jackson3;

import java.lang.reflect.Method;
import java.util.Arrays;
Expand All @@ -13,7 +13,7 @@
import tools.jackson.databind.SerializationContext;
import tools.jackson.databind.ValueSerializer;

class MultivaluedHashMapValueSerializer3 extends ValueSerializer<MultivaluedHashMap<String, String>> {
public class MultivaluedHashMapValueSerializer3 extends ValueSerializer<MultivaluedHashMap<String, String>> {

@Override
public void serialize(MultivaluedHashMap<String, String> map, JsonGenerator gen, SerializationContext ctxt) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.keycloak.admin.client.jackson3;
package org.keycloak.json.jackson3;

import java.util.List;
import java.util.Map;
Expand All @@ -12,7 +12,7 @@
import tools.jackson.databind.DeserializationContext;
import tools.jackson.databind.ValueDeserializer;

class ResourceTypeMapDeserializer3 extends ValueDeserializer<Map<String, ResourceType>> {
public class ResourceTypeMapDeserializer3 extends ValueDeserializer<Map<String, ResourceType>> {

@Override
public Map<String, ResourceType> deserialize(JsonParser p, DeserializationContext ctxt) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.keycloak.admin.client.jackson3;
package org.keycloak.json.jackson3;

import java.util.HashMap;
import java.util.LinkedList;
Expand All @@ -10,7 +10,7 @@
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ValueDeserializer;

class StringListMapDeserializer3 extends ValueDeserializer<Object> {
public class StringListMapDeserializer3 extends ValueDeserializer<Object> {

@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.keycloak.admin.client.jackson3;
package org.keycloak.json.jackson3;

import java.util.ArrayList;

Expand All @@ -7,19 +7,19 @@
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ValueDeserializer;

class StringOrArrayDeserializer3 extends ValueDeserializer<Object> {
public class StringOrArrayDeserializer3 extends ValueDeserializer<Object> {

@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) {
JsonNode jsonNode = ctxt.readTree(p);
if (jsonNode.isArray()) {
ArrayList<String> a = new ArrayList<>(1);
for (JsonNode child : jsonNode) {
a.add(child.stringValue());
a.add(child.isString() ? child.stringValue() : null);
}
return a.toArray(new String[0]);
} else {
return new String[] { jsonNode.stringValue() };
return new String[] { jsonNode.isString() ? jsonNode.stringValue() : null };
}
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package org.keycloak.admin.client.jackson3;
package org.keycloak.json.jackson3;

import tools.jackson.core.JsonGenerator;
import tools.jackson.databind.SerializationContext;
import tools.jackson.databind.ValueSerializer;

class StringOrArraySerializer3 extends ValueSerializer<Object> {
public class StringOrArraySerializer3 extends ValueSerializer<Object> {
@Override
public void serialize(Object o, JsonGenerator gen, SerializationContext ctxt) {
String[] array = (String[]) o;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
package org.keycloak.json.jackson3;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.json.MultivaluedHashMapValue;
import org.keycloak.json.ResourceTypeMap;
import org.keycloak.representations.JsonWebToken;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.idm.authorization.ResourceType;
import org.keycloak.representations.workflows.WorkflowRepresentation;
import org.keycloak.representations.workflows.WorkflowStepRepresentation;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import tools.jackson.databind.json.JsonMapper;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertThrows;

/**
* Client and server run the same representation contracts with their own mapper policies.
*/
public class RepresentationAdaptersTest {

protected JsonMapper mapper() {
return JsonMapper.builder()
.configureForJackson2()
.annotationIntrospector(new KeycloakAnnotationIntrospector3())
.changeDefaultPropertyInclusion(value -> JsonInclude.Value.construct(
JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL))
.build();
}

private final ObjectMapper legacyMapper = new ObjectMapper()
.setSerializationInclusion(JsonInclude.Include.NON_NULL);

@Test
public void stringListMapAcceptsScalarArrayAndNullAttributes() throws Exception {
String json = """
{"username":"alice","attributes":{
"scalar":"value","array":["first","second"],"empty":[],
"null":null,"mixed":[null,"text",true,42],"boolean":false,"number":12}}
""";
var expected = legacyMapper.readValue(json, UserRepresentation.class);
var actual = mapper().readValue(json, UserRepresentation.class);

assertThat(actual.getAttributes(), equalTo(expected.getAttributes()));
assertThat(actual.getAttributes().get("scalar"), equalTo(List.of("value")));
assertThat(actual.getAttributes().get("mixed"), equalTo(Arrays.asList(null, "text", "true", "42")));
assertWireParity(actual);
}

@Test
public void audienceRetainsScalarAndArrayWireForms() throws Exception {
for (String audience : List.of("\"one\"", "[\"one\"]", "[\"one\",\"two\"]", "[]", "null")) {
String json = "{\"aud\":" + audience + "}";
var expected = legacyMapper.readValue(json, JsonWebToken.class);
var actual = mapper().readValue(json, JsonWebToken.class);

assertThat(actual.getAudience(), equalTo(expected.getAudience()));
assertWireParity(actual);
}
var token = new JsonWebToken().audience("one");
assertThat(mapper().readTree(mapper().writeValueAsString(token)).get("aud").stringValue(), equalTo("one"));
}

@Test
public void audiencePreservesLegacyNonTextValues() throws Exception {
for (String audience : List.of("42", "true", "{}", "[null,42,true,{},[],\"one\"]")) {
String json = "{\"aud\":" + audience + "}";
var expected = legacyMapper.readValue(json, JsonWebToken.class);
var actual = mapper().readValue(json, JsonWebToken.class);

assertThat(actual.getAudience(), equalTo(expected.getAudience()));
assertWireParity(actual);
}
}

@Test
public void resourceTypesAcceptArrayAndObjectForms() throws Exception {
String resource = "{\"type\":\"document\",\"scopes\":[\"read\",\"write\"]}";
for (String types : List.of("[" + resource + "]", "{\"document\":" + resource + "}")) {
String json = "{\"resourceTypes\":" + types + "}";
var expected = legacyMapper.readValue(json, ResourceTypesValue.class);
var actual = mapper().readValue(json, ResourceTypesValue.class);

assertThat(actual.resourceTypes.keySet(), equalTo(Set.of("document")));
assertThat(actual.resourceTypes.get("document").getScopes(), equalTo(expected.resourceTypes.get("document").getScopes()));
assertWireParity(actual);
}
}

@Test
public void resourceTypesRejectScalarInput() {
assertThrows(tools.jackson.databind.exc.MismatchedInputException.class,
() -> mapper().readValue("{\"resourceTypes\":42}", ResourceTypesValue.class));
}

@Test
public void multivaluedWorkflowConfigurationSerializationPreservesWireShape() throws Exception {
var workflow = WorkflowRepresentation.withName("test")
.onEvent("user-created")
.withSteps(WorkflowStepRepresentation.create().of("set-user-attribute")
.withConfig("key", "value")
.withConfig("enabled", "true")
.withConfig("values", "first", "second").build())
.build();
assertWireParity(workflow);
}

@Test
public void multivaluedConfigurationPreservesValuesAndFiltersReservedProperties() throws Exception {
String json = """
{"config":{"reserved":"hidden","scalar":"value","flag":true,"values":["first","second"]}}
""";
var expected = legacyMapper.readValue(json, MultivaluedValue.class);
var actual = mapper().readValue(json, MultivaluedValue.class);

assertThat(actual.config, equalTo(expected.config));
assertThat(actual.config.get("flag"), equalTo(List.of("true")));
assertThat(mapper().readTree(mapper().writeValueAsString(actual)).get("config").has("reserved"), is(false));
assertWireParity(actual);
}

@Test
public void nativeJacksonNamingWorksInBothDirections() {
var value = mapper().readValue("{\"some-value\":\"text\"}", NativeNamingValue.class);

assertThat(value.someValue, equalTo("text"));
assertThat(mapper().writeValueAsString(value), equalTo("{\"some-value\":\"text\"}"));
}

private void assertWireParity(Object value) throws Exception {
assertThat(legacyMapper.readTree(mapper().writeValueAsString(value)),
equalTo(legacyMapper.readTree(legacyMapper.writeValueAsString(value))));
}

@tools.jackson.databind.annotation.JsonNaming(tools.jackson.databind.PropertyNamingStrategies.KebabCaseStrategy.class)
public static class NativeNamingValue {
public String someValue;
}

public static class ResourceTypesValue {
@ResourceTypeMap
public Map<String, ResourceType> resourceTypes;
}

public static class MultivaluedValue {
@MultivaluedHashMapValue
public MultivaluedHashMap<String, String> config;

public String getReserved() {
return "visible";
}
}
}
Loading
Loading
0